CustomUnsafeOptPass.cpp 129 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
/*===================== begin_copyright_notice ==================================

Copyright (c) 2017 Intel Corporation

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


======================= end_copyright_notice ==================================*/

/*========================== CustomUnsafeOptPass.cpp ==========================

 This file contains CustomUnsafeOptPass and EarlyOutPatterns
 
 CustomUnsafeOptPass does peephole optimizations which might affect precision.
 This pass combines things like:
    x * 0 = 0               or
    y + x - x = y           or
    fdiv = fmul + inv       or
    fmul+fsub+fcmp = fcmp (if condition allowed)


 EarlyOutPatterns does a few early out cases that adds control flow to
 avoid heavy computation that is not needed. 
 For example, if a long/expensive sequence of instruction result is 0 when 
 one of the input r0 is 0, we can modify the sequence to
     if(r0==0)
     {
        result = 0;
     }
     else
     {
        do the actual calculation
     }
 The cases are added with existing workload analysis and should be limited to
 the target shader since adding control flow can add overhead to other shaders.
 
=============================================================================*/


#include "Compiler/CustomUnsafeOptPass.hpp"
#include "Compiler/CISACodeGen/helper.h"
#include "Compiler/IGCPassSupport.h"
#include "common/debug/Debug.hpp"
#include "common/igc_regkeys.hpp"
#include "common/LLVMUtils.h"
#include "common/LLVMWarningsPush.hpp"
#include "GenISAIntrinsics/GenIntrinsics.h"

#include <llvm/ADT/Statistic.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/Pass.h>
#include <llvm/IR/InstVisitor.h>
#include <llvm/IR/PatternMatch.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/Analysis/LoopPass.h>
#include "common/LLVMWarningsPop.hpp"

#include <set>

using namespace llvm;
using namespace IGC;

// Register pass to igc-opt
#define PASS_FLAG "igc-custom-unsafe-opt-pass"
#define PASS_DESCRIPTION "Unsafe Optimizations Pass"
#define PASS_CFG_ONLY false
#define PASS_ANALYSIS false
IGC_INITIALIZE_PASS_BEGIN(CustomUnsafeOptPass, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)
IGC_INITIALIZE_PASS_DEPENDENCY(CodeGenContextWrapper)
IGC_INITIALIZE_PASS_DEPENDENCY(MetaDataUtilsWrapper);
IGC_INITIALIZE_PASS_END(CustomUnsafeOptPass, PASS_FLAG, PASS_DESCRIPTION, PASS_CFG_ONLY, PASS_ANALYSIS)

char CustomUnsafeOptPass::ID = 0;

#define DEBUG_TYPE "CustomUnSafeOptPass"

STATISTIC(Stat_FcmpRemoved,  "Number of insts removed in FCmp Opt");
STATISTIC(Stat_FloatRemoved,  "Number of insts removed in Float Opt");
STATISTIC(Stat_DiscardRemoved,  "Number of insts removed in Discard Opt");

static bool allowUnsafeMathOpt(CodeGenContext* ctx, llvm::BinaryOperator& op)
{
    // always allow unsafe opt if instruction has the flag
    if(llvm::isa<llvm::FPMathOperator>(op) && op.getFastMathFlags().isFast())
    {
        return true;
    }

    // then checking compiler options in metadata
    if(ctx->getModuleMetaData()->compOpt.FastRelaxedMath)
    {
        return true;
    }

116 117 118 119
    if (IGC_IS_FLAG_ENABLED(EnableFastMath))
    {
        return true;
    }
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652

    return false;
}

CustomUnsafeOptPass::CustomUnsafeOptPass()
    : FunctionPass(ID),
      m_disableReorderingOpt(0),
      m_ctx(nullptr),
      m_pMdUtils(nullptr)
{
    initializeCustomUnsafeOptPassPass(*PassRegistry::getPassRegistry());
}

bool CustomUnsafeOptPass::runOnFunction(Function &F)
{
    if (IGC_IS_FLAG_ENABLED(DisableCustomUnsafeOpt))
    {
        return false;
    }

    m_ctx = getAnalysis<CodeGenContextWrapper>().getCodeGenContext();
    m_pMdUtils = getAnalysis<MetaDataUtilsWrapper>().getMetaDataUtils();

    m_disableReorderingOpt = false;

    if (m_ctx->type == ShaderType::VERTEX_SHADER)
    {
        m_disableReorderingOpt = true;
    }
    if (m_ctx->type == ShaderType::COMPUTE_SHADER && m_ctx->m_floatDenormMode64 == FLOAT_DENORM_RETAIN)
    {
        m_disableReorderingOpt = true;
    }

    int iterCount = 0;

    m_isChanged = true;
    // re-run the pass if the shader is changed within the pass.
    // also set a iterCount<=10 to make sure it doesn't run into infinate loop unexpectedly.
    while (m_isChanged && iterCount<=10)
    {
        iterCount++;
        m_isChanged = false;
        visit(F);
    }

    // Do reassociate to emit more mad.
    reassociateMulAdd(F);

    return true;
}

void CustomUnsafeOptPass::visitInstruction(Instruction &I)
{
    // nothing
}

bool CustomUnsafeOptPass::possibleForFmadOpt( llvm::Instruction *inst )
{
    if( inst->getOpcode() == Instruction::FAdd )
    {
        if(BinaryOperator* src0 = llvm::dyn_cast<llvm::BinaryOperator>(inst->getOperand(0)))
        {
            if(src0->getOpcode() == Instruction::FMul)
            {
                return true;
            }
        }
        if(BinaryOperator* src1 = llvm::dyn_cast<llvm::BinaryOperator>(inst->getOperand(1)))
        {
            if(src1->getOpcode() == Instruction::FMul)
            {
                return true;
            }
        }
    }
    return false;
}

bool CustomUnsafeOptPass::visitBinaryOperatorFmulFaddPropagation(BinaryOperator &I)
{
    if (m_disableReorderingOpt)
    {
        return false;
    }

/*
    Pattern 1:
        From
            %r2.x_1 = fmul float %r2.x_, %r1.y_, !dbg !10
            %r2.y_2 = fmul float %r2.y_, %r1.y_, !dbg !10    -> Src1
            %r2.z_3 = fmul float %r2.z_, %r1.y_, !dbg !10

            %oC0.x_ = fmul float %r2.x_1, 0x3FE3333340000000, !dbg !12
            %oC0.y_ = fmul float %r2.y_2, 0x3FE3333340000000, !dbg !12  -> Base
            %oC0.z_ = fmul float %r2.z_3, 0x3FE3333340000000, !dbg !12

        To
            %r2.x_1 = fmul float 0x3FE3333340000000, %r1.y_, !dbg !10
            %oC0.x_ = fmul float %r2.x_1, %r2.x_, !dbg !12
            %oC0.y_ = fmul float %r2.x_1, %r2.y_, !dbg !12
            %oC0.z_ = fmul float %r2.x_1, %r2.z_, !dbg !12

     Pattern 2:
        From
            %r0.x_ = fmul float %r1.x_, %r2.z_, !dbg !10
            %r0.y_ = fmul float %r1.y_, %r2.z_, !dbg !10                -> Src1
            %r0.z_ = fmul float %r1.z_, %r2.z_, !dbg !10
            %r2.x_1 = fmul float %r2.x_, 0x3FE6666660000000, !dbg !12
            %r2.y_2 = fmul float %r2.y_, 0x3FE6666660000000, !dbg !12   -> Src2
            %r2.z_3 = fmul float %r2.z_, 0x3FE6666660000000, !dbg !12
            %oC0.x_ = fmul float %r0.x_, %r2.x_1, !dbg !14
            %oC0.y_ = fmul float %r0.y_, %r2.y_2, !dbg !14              -> Base
            %oC0.z_ = fmul float %r0.z_, %r2.z_3, !dbg !14

        To
            %r0.x_ = fmul float 0x3FE6666660000000, %r2.z_, !dbg !10
            %r2.x_1 = fmul float %r2.x_, %r0.x_, !dbg !12
            %r2.y_2 = fmul float %r2.y_, %r0.x_, !dbg !12
            %r2.z_3 = fmul float %r2.z_, %r0.x_, !dbg !12
            %oC0.x_ = fmul float %r1.x_, %r2.x_1, !dbg !14
            %oC0.y_ = fmul float %r1.y_, %r2.y_2, !dbg !14
            %oC0.z_ = fmul float %r1.z_, %r2.z_3, !dbg !14
*/
    llvm::Instruction::BinaryOps opcode = I.getOpcode();

    // only fmul or fadd can call into this function
    assert( opcode == Instruction::FMul || opcode == Instruction::FAdd );

    llvm::Instruction* instBase[4];
    llvm::Instruction* instSrc1[4];
    llvm::Instruction* instSrc2[4];
    int sameSrcIdBase = 0;
    int sameSrcId1 = 0;
    int sameSrcId2 = 0;
    int numOfSet = 0;
    bool matchPattern1 = false;
    bool matchPattern2 = false;

    for( int i=0; i<4; i++ )
    {
        instBase[i] = NULL;
        instSrc1[i] = NULL;
        instSrc2[i] = NULL;
    }

    instBase[0] = llvm::dyn_cast<llvm::Instruction>( &I );
    if( instBase[0] == nullptr ||
        instBase[0]->getOperand(0) == instBase[0]->getOperand(1) )
    {
        return false;
    }

    instBase[1] = GetNextInstruction(instBase[0]);

    if (instBase[1] &&
        instBase[1]->getOpcode() != opcode)
    {
        instBase[1] = GetNextInstruction(instBase[1]);
    }

    if( instBase[1] == nullptr ||
        instBase[1]->getOpcode() != opcode ||
        instBase[1]->getOperand(0) == instBase[1]->getOperand(1) )
    {
        return false;
    }

    if( instBase[0]->getOperand(0) == instBase[1]->getOperand(0) )
    {
        sameSrcIdBase = 0;
        numOfSet = 2;
        matchPattern1 = true;
    }
    else if( instBase[0]->getOperand(1) == instBase[1]->getOperand(1) )
    {
        sameSrcIdBase = 1;
        numOfSet = 2;
        matchPattern1 = true;
    }
    else
    {
        matchPattern2 = true;
    }
    for( int i=2; i<4; i++ )
    {
        instBase[i] = GetNextInstruction(instBase[i-1]);

        if (instBase[i] &&
            instBase[i - 1]->getOpcode() != instBase[i]->getOpcode())
        {
            instBase[i] = GetNextInstruction(instBase[i]);
        }

        if( !instBase[i] ||
            instBase[i]->getOpcode() != opcode ||
            instBase[i]->getOperand(0) == instBase[i]->getOperand(1) ||
            possibleForFmadOpt( instBase[i] ) )
        {
            break;
        }
        numOfSet = i+1;
    }

    if( numOfSet < 2 )
    {
        return false;
    }

    if( matchPattern1 )
    {
        for( int i=0; i<numOfSet; i++ )
        {
            if( i > 0 &&
                instBase[i]->getOperand(sameSrcIdBase) != instBase[0]->getOperand(sameSrcIdBase) )
            {
                numOfSet = i;
                break;
            }

            instSrc1[i] = llvm::dyn_cast<llvm::Instruction>( instBase[i]->getOperand( 1-sameSrcIdBase ) );

            if( !instSrc1[i] ||
                !instSrc1[i]->hasOneUse() ||
                instSrc1[i]->getOpcode() != opcode ||
                possibleForFmadOpt( instSrc1[i] ) )
            {
                numOfSet = i;
                break;
            }
        }

        if( numOfSet > 1 )
        {
            if( instSrc1[0]->getOperand(0) == instSrc1[1]->getOperand(0) )
            {
                sameSrcId1 = 0;
            }
            else if( instSrc1[0]->getOperand(1) == instSrc1[1]->getOperand(1) )
            {
                sameSrcId1 = 1;
            }
            else
            {
                return false;
            }

            // instructions for the pattern can not overlap with each other
            for (int si = 0; si < numOfSet; si++)
            {
                for (int sj = 0; sj < numOfSet; sj++)
                {
                    if (instBase[si] == instSrc1[sj])
                    {
                        return false;
                    }
                }
            }

            for( int i=2; i<numOfSet; i++ )
            {
                if( instSrc1[i]->getOperand(sameSrcId1) != instSrc1[0]->getOperand(sameSrcId1) )
                {
                    numOfSet = i;
                    break;
                }
            }
        }

        if( numOfSet > 1 &&
            opcode == Instruction::FMul )
        {
            if( !dyn_cast<ConstantFP>( instSrc1[0]->getOperand( sameSrcId1 ) ) )
            {
                if (llvm::Instruction *tempInstr = llvm::dyn_cast<llvm::Instruction>( instSrc1[0]->getOperand( sameSrcId1 ) ))
                {
                    if( tempInstr->getOpcode() == Instruction::FDiv )
                    {
                        ConstantFP *C0 = dyn_cast<ConstantFP>( tempInstr->getOperand(0) );
                        if( C0 && C0->isExactlyValue( 1.0 ) )
                        {
                            numOfSet = 0;
                        }
                    }

                    IGC::EOPCODE intrinsic_name = IGC::GetOpCode(tempInstr);
                    if(intrinsic_name==IGC::llvm_exp)
                    {
                        numOfSet = 0;
                    }
                }
            }
        }

        // start the optimization for pattern 1
        if( numOfSet > 1 )
        {
            Value* tempOp = instBase[0]->getOperand(sameSrcIdBase);
            for( int i=0; i<numOfSet; i++ )
            {
                instBase[i]->setOperand( 1-sameSrcIdBase, instBase[0]->getOperand(1-sameSrcIdBase) );
            }
            for( int i=0; i<numOfSet; i++ )
            {
                instBase[i]->setOperand( sameSrcIdBase, instSrc1[i]->getOperand(1-sameSrcId1) );
            }
            instSrc1[0]->setOperand( 1-sameSrcId1, tempOp );
            // move instSrc1[0] to before base
            instSrc1[0]->moveBefore( instBase[0] );
            return true;
        }
    }
    else  // check pattern 2
    {
        for( int i=0; i < numOfSet; i++ )
        {
            if( instBase[i]->getOperand(0) == instBase[i]->getOperand(1) ||
                dyn_cast<ConstantFP>( instBase[i]->getOperand(0) ) ||
                dyn_cast<ConstantFP>( instBase[i]->getOperand(1) ) ||
                possibleForFmadOpt( instBase[i] ) )
            {
                numOfSet = i;
                break;
            }
        }

        if( numOfSet > 1 )
        {
            for( int i=0; i < numOfSet; i++ )
            {
                instSrc1[i] = llvm::dyn_cast<llvm::Instruction>( instBase[i]->getOperand( 0 ) );
                instSrc2[i] = llvm::dyn_cast<llvm::Instruction>( instBase[i]->getOperand( 1 ) );
                if( !instSrc1[i] || !instSrc1[i]->hasOneUse() || instSrc1[i]->getOpcode() != opcode ||
                    !instSrc2[i] || !instSrc2[i]->hasOneUse() || instSrc2[i]->getOpcode() != opcode ||
                    possibleForFmadOpt( instSrc1[i] ) || possibleForFmadOpt( instSrc2[i] ) )
                {
                    numOfSet = i;
                    break;
                }
            }
        }

        if( numOfSet > 1 )
        {
            if( instSrc1[0]->getOperand(0) == instSrc1[1]->getOperand(0) )
            {
                sameSrcId1 = 0;
            }
            else if( instSrc1[0]->getOperand(1) == instSrc1[1]->getOperand(1) )
            {
                sameSrcId1 = 1;
            }
            else
            {
                return false;
            }

            if( instSrc2[0]->getOperand(0) == instSrc2[1]->getOperand(0) )
            {
                sameSrcId2 = 0;
            }
            else if( instSrc2[0]->getOperand(1) == instSrc2[1]->getOperand(1) )
            {
                sameSrcId2 = 1;
            }
            else
            {
                return false;
            }

            // instructions for the pattern can not overlap with each other
            for (int si = 0; si < numOfSet; si++)
            {
                for (int sj = 0; sj < numOfSet; sj++)
                {
                    for (int sk = 0; sk < numOfSet; sk++)
                    {
                        if (instBase[si] == instSrc1[sj] || instBase[si] == instSrc2[sk] || instSrc1[sj] == instSrc2[sk])
                        {
                            return false;
                        }
                    }
                }
            }

            for( int i=2; i < numOfSet; i++ )
            {
                if( instSrc1[0]->getOperand(sameSrcId1) != instSrc1[i]->getOperand(sameSrcId1) ||
                    instSrc2[0]->getOperand(sameSrcId2) != instSrc2[i]->getOperand(sameSrcId2) )
                {
                    numOfSet = i;
                    break;
                }
            }
        }

        // start the optimization for pattern 2
        if( numOfSet > 1 )
        {
            Value* tempOp = instSrc2[0]->getOperand(sameSrcId2);

            for( int i=0; i<numOfSet; i++ )
            {
                instSrc2[i]->setOperand( sameSrcId2, instBase[0]->getOperand(0) );
            }

            for( int i=0; i<numOfSet; i++ )
            {
                instBase[i]->setOperand( 0, instSrc1[i]->getOperand(1-sameSrcId1) );
            }

            instSrc1[0]->setOperand( 1-sameSrcId1, tempOp );

            for( int i=0; i<numOfSet; i++ )
            {
                instSrc2[i]->moveBefore( instBase[0] );
            }
            instSrc1[0]->moveBefore( instSrc2[0] );
            return true;
        }
    }
    return false;
}

bool CustomUnsafeOptPass::removeCommonMultiplier(llvm::Value *I, llvm::Value *commonMultiplier)
{
    Value *numerator = NULL;
    Value *denumerator = NULL;
    if (isFDiv(I, numerator, denumerator))
    {
        llvm::Instruction* multiplier = llvm::dyn_cast<llvm::Instruction>(numerator);
        if (multiplier && multiplier->getOpcode() == Instruction::FMul &&
            multiplier->getOperand(1) == commonMultiplier)
        {
            multiplier->setOperand(1, ConstantFP::get(multiplier->getType(), 1.0));
            return true;
        }
    }
    return false;
}

bool CustomUnsafeOptPass::visitBinaryOperatorExtractCommonMultiplier(BinaryOperator &I)
{
    bool patternFound = false;

    if (m_disableReorderingOpt || !I.hasOneUse())
    {
        return patternFound;
    }

    llvm::Instruction* src0 = llvm::dyn_cast<llvm::Instruction>(I.getOperand(0));

    Value *numerator0 = NULL;
    Value *denumerator0 = NULL;

    if (src0 && src0->hasOneUse() && isFDiv(src0, numerator0, denumerator0))
    {
        if (llvm::Instruction *inst = llvm::dyn_cast<llvm::Instruction>(numerator0))
        {
            if (inst->getOpcode() == Instruction::FMul)
            {
                if (llvm::Instruction* commonMultiplier = llvm::dyn_cast<llvm::Instruction>(inst->getOperand(1)))
                {
                    llvm::Instruction* sumComponent = llvm::dyn_cast<llvm::Instruction>(I.getOperand(1));
                    llvm::Instruction* currentRoot = &I;
                    llvm::Instruction* previousRoot = nullptr;
                    while (1)
                    {
                        if (sumComponent && sumComponent->hasOneUse())
                        {
                            previousRoot = currentRoot;
                            if (removeCommonMultiplier(sumComponent, commonMultiplier))
                            {
                                currentRoot = dyn_cast<Instruction>(*currentRoot->user_begin());
                                sumComponent = llvm::dyn_cast<llvm::Instruction>(currentRoot->getOperand(1));
                                patternFound = true;
                            }
                            else
                            {
                                break;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    if (patternFound)
                    {
                        Instruction *newResult = copyIRFlags(BinaryOperator::CreateFMul(commonMultiplier, previousRoot, ""), &I);
                        newResult->insertAfter(previousRoot);
                        previousRoot->replaceAllUsesWith(newResult);
                        newResult->setOperand(1, previousRoot);
                        inst->setOperand(1, ConstantFP::get(inst->getType(), 1.0));
                    }
                }
            }
        }
    }

    return patternFound;
}


bool CustomUnsafeOptPass::visitBinaryOperatorToFmad(BinaryOperator &I)
{
    if (m_disableReorderingOpt)
    {
        return false;
    }

    /*
    // take care of the case: C1*(a + C0) = a*C1 + C0*C1
    from
        %38 = fadd float %30, 0x3FAC28F5C0000000
        %39 = fmul float %38, 0x3FEE54EDE0000000
    to
        %38 = fmul float %33, 0x3FEE54EDE0000000
        %39 = fadd float %38, 0x3FAAB12340000000

    fmul+fadd can be replaced with fmad later in matchMad()
    */

    assert(I.getOpcode() == Instruction::FMul);

    Instruction* mulInst = (Instruction*)(&I);
    Instruction* addInst = dyn_cast<Instruction>(I.getOperand(0));

    if (!addInst || (addInst->getOpcode() != Instruction::FAdd && addInst->getOpcode() != Instruction::FSub))
    {
        return false;
    }

653 654
    ConstantFP* C0 = dyn_cast<ConstantFP>(addInst->getOperand(1));
    ConstantFP* C1 = dyn_cast<ConstantFP>(mulInst->getOperand(1));
655

656
    if(!C0 || !C1 || !addInst->hasOneUse())
657 658 659 660
    {
        return false;
    }

661
    Value *op0 = copyIRFlags(BinaryOperator::CreateFMul(addInst->getOperand(0), C1, "", &I), &I);
662

663 664 665
    APFloat C0Float = C0->getValueAPF();
    C0Float.multiply(C1->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
    Value *op1 = ConstantFP::get(C0->getContext(), C0Float);
666 667 668 669 670 671 672

    if (addInst->getOpcode() == Instruction::FAdd)
    {
        I.replaceAllUsesWith(copyIRFlags(BinaryOperator::CreateFAdd(op0, op1, "", &I), &I));
    }
    else
    {
673
        I.replaceAllUsesWith(copyIRFlags(BinaryOperator::CreateFSub(op0, op1, "", &I), &I));
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
    }

    m_isChanged = true;

    return true;
}

bool CustomUnsafeOptPass::visitBinaryOperatorFmulToFmad(BinaryOperator &I)
{
    bool patternFound = false;

    if (m_disableReorderingOpt || (m_ctx->type == ShaderType::PIXEL_SHADER) || (m_ctx->type == ShaderType::COMPUTE_SHADER))
    {
        return patternFound;
    }

    /*
    // take care of the case: x*(1 - a) = x - x*a
    // needed for a OGL lrp pattern match, also enable more cases for the fmad optimization later

    from
        %6 = fsub float 1.000000e+00, %res_s1
        %7 = fmul float %res_s2, %6
    to
        %6 = fmul float %res_s2, %res_s1
        %7 = fsub float %res_s2, %6
    */

    assert(I.getOpcode() == Instruction::FMul);

    // check for x*(1 +/- a), (1 +/- a)*x, x*(a +/- 1), (a +/- 1)*x
    // also checks if x is a constant. 1 can be any other constant in this case.
    bool enableOpt = false;
    uint xIndex = 0;
    uint immOneIndex = 0;
    llvm::Instruction* FsubOrFaddInst = nullptr;
    for (xIndex = 0; xIndex < 2; xIndex++)
    {
        FsubOrFaddInst = llvm::dyn_cast<llvm::Instruction>(I.getOperand(1 - xIndex));
        if (FsubOrFaddInst &&
            FsubOrFaddInst->hasOneUse() &&
            (FsubOrFaddInst->getOpcode() == Instruction::FSub || FsubOrFaddInst->getOpcode() == Instruction::FAdd) )
        {
            ConstantFP *Cx = dyn_cast<ConstantFP>(I.getOperand(xIndex));
            ConstantFP *C0 = dyn_cast<ConstantFP>(FsubOrFaddInst->getOperand(0));
            if (C0 && !C0->isZero() && (C0->isExactlyValue(1.f) || Cx))
            {
                enableOpt = true;
                immOneIndex = 0;
                break;
            }
            ConstantFP *C1 = dyn_cast<ConstantFP>(FsubOrFaddInst->getOperand(1));
            if (C1 && !C1->isZero() && (C1->isExactlyValue(1.f) || Cx))
            {
                enableOpt = true;
                immOneIndex = 1;
                break;
            }
        }
    }

    // start optimization
    if (enableOpt)
    {
        Value *op1 = nullptr;
        Value *op2 = nullptr;
        ConstantFP *Cx = dyn_cast<ConstantFP>(I.getOperand(xIndex));

        if (immOneIndex == 0)
        {
            if (Cx)
            {
                ConstantFP *C0 = dyn_cast<ConstantFP>(FsubOrFaddInst->getOperand(0));
                APFloat CxFloat = Cx->getValueAPF();
                CxFloat.multiply(C0->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                op1 = ConstantFP::get(C0->getContext(), CxFloat);
            }
            else
            {
                op1 = I.getOperand(xIndex);
            }
            op2 = copyIRFlags(BinaryOperator::CreateFMul(I.getOperand(xIndex), FsubOrFaddInst->getOperand(1), "", &I), &I);
        }
        else
        {
            op1 = copyIRFlags(BinaryOperator::CreateFMul(I.getOperand(xIndex), FsubOrFaddInst->getOperand(0), "", &I), &I);
            if (Cx)
            {
                ConstantFP *C1 = dyn_cast<ConstantFP>(FsubOrFaddInst->getOperand(1));
                APFloat CxFloat = Cx->getValueAPF();
                CxFloat.multiply(C1->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                op2 = ConstantFP::get(C1->getContext(), CxFloat);
            }
            else
            {
                op2 = I.getOperand(xIndex);
            }
        }

        if (FsubOrFaddInst->getOpcode() == Instruction::FSub)
        {
            I.replaceAllUsesWith(
                copyIRFlags(BinaryOperator::CreateFSub(op1, op2, "", &I), &I));
        }
        else
        {
            I.replaceAllUsesWith(
                copyIRFlags(BinaryOperator::CreateFAdd(op1, op2, "", &I), &I));
        }
        m_isChanged = true;
        patternFound = true;
    }
    return patternFound;
}

bool CustomUnsafeOptPass::isFDiv(Value *I, Value *&numerator, Value *&denominator)
{
    bool result = false;
    if (llvm::Instruction *div = llvm::dyn_cast<llvm::Instruction>(I))
    {
        if (div->getOpcode() == Instruction::FDiv)
        {
            numerator = div->getOperand(0);
            denominator = div->getOperand(1);
            result = true;
        }
        else if (div->getOpcode() == Instruction::FMul)
        {
            if (llvm::Instruction *inv = llvm::dyn_cast<llvm::Instruction>(div->getOperand(1)))
            {
                if (inv->getOpcode() == Instruction::FDiv &&
                    dyn_cast<ConstantFP>(inv->getOperand(0)) &&
                    dyn_cast<ConstantFP>(inv->getOperand(0))->isExactlyValue(1.0))
                {
                    numerator = div->getOperand(0);
                    denominator = inv->getOperand(1);
                    result = true;
                }
            }
        }
    }
    return result;
}

bool CustomUnsafeOptPass::visitBinaryOperatorDivAddDiv(BinaryOperator &I)
{
    // A/B +C/D can be changed to (A * D +C * B)/(B * D).
    if (m_disableReorderingOpt)
    {
        return false;
    }

    Value *numerator0 = NULL;
    Value *numerator1 = NULL;
    Value *denumerator0 = NULL;
    Value *denumerator1 = NULL;

    if (isFDiv(I.getOperand(0), numerator0, denumerator0) &&
        isFDiv(I.getOperand(1), numerator1, denumerator1) &&
        denumerator0 != denumerator1)
    {
        Value *mul0 = copyIRFlags(BinaryOperator::CreateFMul(numerator0, denumerator1, "", &I), &I);
        Value *mul1 = copyIRFlags(BinaryOperator::CreateFMul(numerator1, denumerator0, "", &I), &I);
        Value *mul2 = copyIRFlags(BinaryOperator::CreateFMul(denumerator0, denumerator1, "", &I), &I);
        Value *mul2inv = copyIRFlags(BinaryOperator::CreateFDiv(ConstantFP::get(mul2->getType(), 1.0), mul2, "", &I), &I);
        Value *add_mul0_mul1 = copyIRFlags(BinaryOperator::CreateFAdd(mul0, mul1, "", &I), &I);
        I.replaceAllUsesWith(copyIRFlags(BinaryOperator::CreateFMul(add_mul0_mul1, mul2inv, "", &I), &I));
        return true;
    }
    return false;
}
    
bool CustomUnsafeOptPass::visitBinaryOperatorDivDivOp(BinaryOperator &I)
{
    if (m_disableReorderingOpt)
    {
        return false;
    }

    llvm::Instruction* prevInst = llvm::dyn_cast<llvm::Instruction>( I.getOperand( 1 ) );
    bool patternFound = false;

    if( prevInst && prevInst->getOpcode() == Instruction::FDiv )
    {
        Value * prevInstOp = prevInst->getOperand( 0 );
        ConstantFP *C0 = dyn_cast<ConstantFP>(prevInstOp);

        if (C0 && C0->isExactlyValue(1.0))
        {
            ConstantFP * Iconst = dyn_cast<ConstantFP>(I.getOperand(0));
            if (Iconst && Iconst->isExactlyValue(1.0))
            {
                // a = 1 / b
                // c = 1 / a
                //    =>
                // c = b
                I.replaceAllUsesWith(prevInst->getOperand(1));
            }
            else
            {
                // a = 1 / b
                // d = c / a
                //    =>
                // d = c * b
                I.replaceAllUsesWith(
                    copyIRFlags(BinaryOperator::CreateFMul(I.getOperand(0), prevInst->getOperand(1), "", &I), &I));
            }
            ++Stat_FloatRemoved;
            patternFound = true;
            m_isChanged = true;
        }
    }

    return patternFound;
}

bool CustomUnsafeOptPass::visitBinaryOperatorAddSubOp(BinaryOperator &I)
{
    bool patternFound = false;
    if (m_disableReorderingOpt)
    {
        return patternFound;
    }

    // a = b + x
    // d = a - x
    //    =>
    // d = b
    assert( I.getOpcode() == Instruction::FAdd || I.getOpcode() == Instruction::FSub );

    Value* op[2];
    op[0] = I.getOperand(0);
    op[1] = I.getOperand(1);

    for( int i=0; i<2; i++)
    {
        llvm::Instruction* sourceInst = llvm::dyn_cast<llvm::Instruction>( op[i] );
        if( !sourceInst )
        {
            continue;
        }

        if( I.getOpcode() == Instruction::FAdd && sourceInst->getOpcode() == Instruction::FSub)
        {
            // a = b - x
            // d = a + x
            //    =>
            // d = b
            if (op[1 - i] == sourceInst->getOperand(1))
            {
                I.replaceAllUsesWith( sourceInst->getOperand(0) );
                ++Stat_FloatRemoved;
                m_isChanged = true;
                patternFound = true;
                break;
            }
        }
        else if( I.getOpcode() == Instruction::FSub && sourceInst->getOpcode() == Instruction::FSub)
        {
            // a = x - b
            // d = x - a
            //    =>
            // d = b
            if( i == 1 && op[0] == sourceInst->getOperand(0) )
            {
                I.replaceAllUsesWith(sourceInst->getOperand(1));
                ++Stat_FloatRemoved;
                m_isChanged = true;
                patternFound = true;
            }
        }
        else if( I.getOpcode() == Instruction::FSub && sourceInst->getOpcode() == Instruction::FAdd)
        {
            Value* srcOp[2];
            srcOp[0] = sourceInst->getOperand(0);
            srcOp[1] = sourceInst->getOperand(1);
            if( i == 0 )
            {
                for( int srci=0; srci<2; srci++ )
                {
                    if( op[1-i] == srcOp[srci] )
                    {
                        I.replaceAllUsesWith( srcOp[1-srci] );
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                        patternFound = true;
                        break;
                    }
                }
            }
            else if( i == 1 )
            {
                for( int srci=0; srci<2; srci++ )
                {
                    if( op[1-i] == srcOp[srci] )
                    {
                        I.replaceAllUsesWith(
                            copyIRFlags(BinaryOperator::CreateFSub(
                                            ConstantFP::get(op[0]->getType(), 0), srcOp[1-srci], "", &I),
                                        &I));
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                        patternFound = true;
                        break;
                    }
                }
            }
        }
        else
        {
            continue;
        }
    }
    return patternFound;
}

bool CustomUnsafeOptPass::visitBinaryOperatorPropNegate(BinaryOperator &I)
{
    if (m_disableReorderingOpt)
    {
        return false;
    }

    bool foundPattern = false;

    // a = 0 - b
    // c = a + d
    //    =>
    // c = d - b
    assert( I.getOpcode() == Instruction::FAdd );

    for( int i=0; i<2; i++ )
    {
        llvm::Instruction* prevInst = llvm::dyn_cast<llvm::Instruction>( I.getOperand( i ) );
        if( prevInst && prevInst->getOpcode() == Instruction::FSub )
        {
            ConstantFP *fp0 = dyn_cast<ConstantFP>( prevInst->getOperand( 0 ) );
            if( fp0 && fp0->isZero() )
            {
                I.replaceAllUsesWith(
                    copyIRFlags(BinaryOperator::CreateFSub(
                                    I.getOperand(1 - i), prevInst->getOperand(1), "", &I),
                                &I));
                ++Stat_FloatRemoved;
                m_isChanged = true;
                foundPattern = true;
                break;
            }
        }
    }
    return foundPattern;
}

bool CustomUnsafeOptPass::visitBinaryOperatorNegateMultiply(BinaryOperator &I)
{
    // a = b * c
    // d = 0 - a
    //    =>
    // d = (-b) * c
    assert(I.getOpcode() == Instruction::FSub);
    bool patternFound = false;
    bool replaced = false;

    if (I.getOperand(1)->hasOneUse())
    {
        llvm::Instruction* fmulInst = llvm::dyn_cast<llvm::Instruction>(I.getOperand(1));
        if (fmulInst && fmulInst->getOpcode() == Instruction::FMul)
        {
            // if one of the mul src is imm, apply the negate on that imm
            for (int i = 0; i < 2; i++)
            {
                if (llvm::Instruction* fmulSrc = llvm::dyn_cast<llvm::Instruction>(fmulInst->getOperand(i)))
                {
                    if (ConstantFP *fp = dyn_cast<ConstantFP>(fmulSrc))
                    {
                        APFloat newConstantFloat = fp->getValueAPF();
                        newConstantFloat.changeSign();
                        Constant* newConstant = ConstantFP::get(fmulSrc->getContext(), newConstantFloat);
                        fmulSrc->setOperand(i, newConstant);
                        I.replaceAllUsesWith(fmulInst);
                        replaced = true;
                        break;
                    }
                }
            }

            // otherwise replace mul src0 with the negate
            if (!replaced)
            {
                fmulInst->setOperand(0, BinaryOperator::CreateFSub(ConstantFP::get(fmulInst->getType(), 0), fmulInst->getOperand(0), "", fmulInst));
                I.replaceAllUsesWith(fmulInst);
            }
            ++Stat_FloatRemoved;
            m_isChanged = true;
            patternFound = true;
        }
    }
    return patternFound;
}

bool CustomUnsafeOptPass::visitBinaryOperatorTwoConstants(BinaryOperator &I)
{
    bool patternFound = false;

    if (m_disableReorderingOpt)
    {
        return patternFound;
    }

    // a = b + C0
    // d = a + C1
    //    =>
    // d = b + ( C0 + C1 )

    // this optimization works on fadd, fsub, and fmul

    assert( dyn_cast<ConstantFP>( I.getOperand(0) ) || dyn_cast<ConstantFP>( I.getOperand(1) ) );

    llvm::Instruction::BinaryOps opcode = I.getOpcode();
    assert( opcode == Instruction::FAdd || opcode == Instruction::FSub || opcode == Instruction::FMul );

    int regSrcNum = (dyn_cast<ConstantFP>(I.getOperand(0))) ? 1 : 0;
    Value * Iop = I.getOperand( regSrcNum );

    llvm::Instruction* prevInst = llvm::dyn_cast<llvm::Instruction>( Iop );

    if (!prevInst)
    {
        return patternFound;
    }

    if( prevInst->getOpcode() != Instruction::FMul &&
        prevInst->getOpcode() != Instruction::FAdd &&
        prevInst->getOpcode() != Instruction::FSub )
    {
        return patternFound;
    }

    // check if prevInst has one constant in the srcs.
    if( dyn_cast<ConstantFP>( prevInst->getOperand(0) ) || dyn_cast<ConstantFP>( prevInst->getOperand(1) ) )
    {
        if (!prevInst->hasOneUse() &&
            I.getOpcode() == Instruction::FSub )
        {
            ConstantFP *ConstantZero = dyn_cast<ConstantFP>(I.getOperand(0));
            if (ConstantZero && ConstantZero->isZeroValue())
            {
                return patternFound;
            }
        }

        int prevInstRegSrcNum = (dyn_cast<ConstantFP>( prevInst->getOperand(0)) ) ? 1 : 0;

        Value * prevInstOp = prevInst->getOperand( prevInstRegSrcNum );

        ConstantFP *C0 = dyn_cast<ConstantFP>( prevInst->getOperand( 1-prevInstRegSrcNum ) );
        ConstantFP *C1 = dyn_cast<ConstantFP>( I.getOperand( 1-regSrcNum ) );

        assert( C0 && C1 );

        APFloat newConstantFloat(0.0);
        bool orderConstantFirst = false;
        bool changeOpToAdd = false;
        bool changeOpToSub = false;
        if( prevInst->getOpcode() == Instruction::FMul && opcode == Instruction::FMul )
        {
            newConstantFloat = C0->getValueAPF();
            newConstantFloat.multiply(C1->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
        }
        else if( prevInst->getOpcode() == Instruction::FAdd && opcode == Instruction::FAdd )
        {
            newConstantFloat = C0->getValueAPF();
            newConstantFloat.add(C1->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
        }
        else if( prevInst->getOpcode() == Instruction::FSub && opcode == Instruction::FSub )
        {
            if( prevInstRegSrcNum == 0 && regSrcNum == 0)
            {
                newConstantFloat = C0->getValueAPF();
                newConstantFloat.add(C1->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
            }
            else if( prevInstRegSrcNum == 0 && regSrcNum == 1)
            {
                newConstantFloat = C0->getValueAPF();
                newConstantFloat.add(C1->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                orderConstantFirst = true;
            }
            else if( prevInstRegSrcNum == 1 && regSrcNum == 0)
            {
                newConstantFloat = C0->getValueAPF();
                newConstantFloat.subtract(C1->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                orderConstantFirst = true;
            }
            else if( prevInstRegSrcNum == 1 && regSrcNum == 1)
            {
                newConstantFloat = C1->getValueAPF();
                newConstantFloat.subtract(C0->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                changeOpToAdd = true;
            }

        }
        else if( prevInst->getOpcode() == Instruction::FAdd && opcode == Instruction::FSub )
        {
            if( regSrcNum == 0 )
            {
                newConstantFloat = C0->getValueAPF();
                newConstantFloat.subtract(C1->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                changeOpToAdd = true;
            }
            else
            {
                newConstantFloat = C1->getValueAPF();
                newConstantFloat.subtract(C0->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                orderConstantFirst = true;
            }
        }
        else if( prevInst->getOpcode() == Instruction::FSub && opcode == Instruction::FAdd )
        {
            if( prevInstRegSrcNum == 0 )
            {
                newConstantFloat = C1->getValueAPF();
                newConstantFloat.subtract(C0->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                changeOpToAdd = true;
            }
            else
            {
                newConstantFloat = C1->getValueAPF();
                newConstantFloat.add(C0->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                changeOpToSub = true;
                orderConstantFirst = true;
            }
        }
        else
        {
            return patternFound;
        }

        ++Stat_FloatRemoved;
        Constant* newConstant = ConstantFP::get(C1->getContext(), newConstantFloat);
        if( newConstant->isZeroValue() && !orderConstantFirst)
        {
            if( opcode == Instruction::FAdd || opcode == Instruction::FSub )
            {
                I.replaceAllUsesWith( prevInstOp );
                patternFound = true;
                m_isChanged = true;
            }
            else if( opcode == Instruction::FMul )
            {
                I.replaceAllUsesWith( ConstantFP::get( Iop->getType(), 0 ) );
                patternFound = true;
                m_isChanged = true;
            }
        }
        else
        {
            if (changeOpToAdd)
            {
               I.replaceAllUsesWith(
                   copyIRFlags(BinaryOperator::CreateFAdd(prevInstOp, newConstant, "", &I), &I));
            }
            else if( changeOpToSub )
            {
               if( orderConstantFirst )
               {
                   I.replaceAllUsesWith(
                       copyIRFlags(BinaryOperator::CreateFSub(newConstant, prevInstOp, "", &I), &I));
               }
               else
               {
                   I.replaceAllUsesWith(
                       copyIRFlags(BinaryOperator::CreateFSub(prevInstOp, newConstant, "", &I), &I));
               }
            }
            else
            {
                I.setOperand( orderConstantFirst, prevInstOp );
                I.setOperand( 1-orderConstantFirst, newConstant );
            }
            patternFound = true;
        }
    }
    return patternFound;
}

bool CustomUnsafeOptPass::visitBinaryOperatorDivRsq(BinaryOperator &I)
{
    if (GenIntrinsicInst *genIntr = dyn_cast<GenIntrinsicInst>(I.getOperand(1)))
    {
        if (genIntr->getIntrinsicID() == GenISAIntrinsic::GenISA_rsq)
        {
            if (ConstantFP *fp0 = dyn_cast<ConstantFP>(I.getOperand(0)))
            {
                llvm::IRBuilder<> builder(I.getContext());
                llvm::CallInst* sqrt_call = llvm::IntrinsicInst::Create(
                    llvm::Intrinsic::getDeclaration(m_ctx->getModule(), Intrinsic::sqrt, builder.getFloatTy()), genIntr->getOperand(0), "", &I);

                if (fp0->isExactlyValue(1.0))
                {
                    // 1/rsq -> sqrt
                    I.replaceAllUsesWith(sqrt_call);
                }
                else
                {
                    // a/rsq -> a*sqrt
                    I.replaceAllUsesWith(
                        copyIRFlags(BinaryOperator::CreateFMul(I.getOperand(0), sqrt_call, "", &I), &I));
                }
                return true;
            }
        }
    }
    return false;
}

bool CustomUnsafeOptPass::visitBinaryOperatorAddDiv(BinaryOperator &I)
{
    llvm::Instruction* faddInst = llvm::dyn_cast<llvm::Instruction>(I.getOperand(0));

    if (faddInst &&
        (faddInst->getOpcode() == Instruction::FAdd ||
        faddInst->getOpcode() == Instruction::FSub) &&
        faddInst->hasOneUse())
    {
        for (int i = 0; i < 2; i++)
        {
            if (faddInst->getOperand(i) == I.getOperand(1))
            {
                Value *div = BinaryOperator::CreateFDiv(faddInst->getOperand(1-i), I.getOperand(1), "", faddInst);
                Value *one = ConstantFP::get(I.getType(), 1.0);

                if (faddInst->getOpcode() == Instruction::FAdd)
                {
                    if (i == 0)
                    {
                        I.replaceAllUsesWith(copyIRFlags(BinaryOperator::CreateFAdd(one, div, "", &I), &I));
                    }
                    else
                    {
                        I.replaceAllUsesWith(copyIRFlags(BinaryOperator::CreateFAdd(div, one, "", &I), &I));
                    }
                }
                else if (faddInst->getOpcode() == Instruction::FSub)
                {
                    if (i == 0)
                    {
                        I.replaceAllUsesWith(copyIRFlags(BinaryOperator::CreateFSub(one, div, "", &I), &I));
                    }
                    else
                    {
                        I.replaceAllUsesWith(copyIRFlags(BinaryOperator::CreateFSub(div, one, "", &I), &I));
                    }
                }
                return true;
            }
        }
    }
    return false;
}

bool CustomUnsafeOptPass::visitExchangeCB(llvm::BinaryOperator &I)
{
    // a = b x CB0
    // c = b x CB1
    // e = a + c
    //    =>
    // e = b x ( CB0 + CB1 )

    // CB can be constant buffer load or immediate constant. 
    // The goal is to put loop invariant calculations together and hoist it out of a loop. 

    Instruction* inst0 = dyn_cast<Instruction>(I.getOperand(0));
    Instruction* inst1 = dyn_cast<Instruction>(I.getOperand(1));

    if (!inst0 || !inst1 || inst0->getOpcode() != Instruction::FMul || inst1->getOpcode() != Instruction::FMul)
    {
        return false;
    }

    unsigned bufId = 0;
    unsigned cbIndex0 = 0;
    unsigned cbIndex1 = 0;
    unsigned hasCB = 0;
    bool directBuf = false;

    for (int i = 0; i < 2; i++)
    {
        if (LoadInst* ld0 = dyn_cast<LoadInst>(inst0->getOperand(i)))
        {
            if (IGC::DecodeAS4GFXResource(ld0->getPointerAddressSpace(), directBuf, bufId) == CONSTANT_BUFFER && directBuf)
            {
                cbIndex0 = i;
                hasCB++;
            }
        }
        else if (dyn_cast<Constant>(inst0->getOperand(i)))
        {
            cbIndex0 = i;
            hasCB++;
        }
    }

    if (hasCB != 1)
        return false;

    hasCB = 0;
    for (int i = 0; i < 2; i++)
    {
        if (LoadInst* ld1 = dyn_cast<LoadInst>(inst1->getOperand(i)))
        {
            if (IGC::DecodeAS4GFXResource(ld1->getPointerAddressSpace(), directBuf, bufId) == CONSTANT_BUFFER && directBuf)
            {
                cbIndex1 = i;
                hasCB++;
            }
            else if (dyn_cast<Constant>(inst1->getOperand(i)))
            {
                cbIndex1 = i;
                hasCB++;
            }
        }
    }

    if (hasCB != 1)
        return false;
    
    if (inst0->getOperand(1 - cbIndex0) != inst1->getOperand(1 - cbIndex1))
        return false;

    // perform the change
    Value *CBsum = copyIRFlags(BinaryOperator::CreateFAdd(inst0->getOperand(cbIndex0), inst1->getOperand(cbIndex1), "", &I), &I);
    I.replaceAllUsesWith(copyIRFlags(BinaryOperator::CreateFMul(inst0->getOperand(1 - cbIndex0), CBsum, "", &I), &I));
    
    return true;
}

void CustomUnsafeOptPass::visitBinaryOperator(BinaryOperator &I)
{
    if (I.use_empty())
    {
        return;
    }

    if (allowUnsafeMathOpt(m_ctx, I))
    {
        Value*	op0 = I.getOperand(0);
        Value*	op1 = I.getOperand(1);
        if (op0->getType()->isFPOrFPVectorTy() && op1->getType()->isFPOrFPVectorTy() )
        {
            ConstantFP *fp0 = dyn_cast<ConstantFP>( op0 );
            ConstantFP *fp1 = dyn_cast<ConstantFP>( op1 );
            Type *opType = op0->getType();

            switch (I.getOpcode())
            {
                case Instruction::FSub:
                    if (op0 == op1)
                    {
                        // X - X => 0
                        I.replaceAllUsesWith(ConstantFP::get(opType, 0));
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    else if( fp1 && fp1->isZero() )
                    {
                        // X - 0 => X
                        I.replaceAllUsesWith(op0);
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    else if( fp0 && fp0->isZero() )
                    {
                        m_isChanged |= visitBinaryOperatorNegateMultiply(I);
                    }
                    else
                    {
                        bool patternFound = false;
                        if (fp0 || fp1)
                        {
                            // a = b + C0
                            // d = a + C1
                            //    =>
                            // d = b + ( C0 + C1 )
                            patternFound = visitBinaryOperatorTwoConstants(I);
                        }
                        else
                        {
                            // a = b + x
                            // d = a - x
                            //    =>
                            // d = b
                            patternFound = visitBinaryOperatorAddSubOp(I);
                        }
                        m_isChanged |= patternFound;
                    }

                    break;

                case Instruction::FAdd:
                    if( fp0 && fp0->isZero() )
                    {
                        // 0 + X => X
                        I.replaceAllUsesWith( op1 );
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    else if( fp1 && fp1->isZero() )
                    {
                        // X + 0 => X
                        I.replaceAllUsesWith( op0 );
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    else
                    {
                        bool patternFound = false;
                        if (fp0 || fp1)
                        {
                            // a = b + C0
                            // d = a + C1
                            //    =>
                            // d = b + ( C0 + C1 )
                            patternFound = visitBinaryOperatorTwoConstants(I);
                        }

                        if (op0 != op1)
                        {
                            // a = b - x
                            // d = a + x
                            //    =>
                            // d = b
                            if (!patternFound)
                            {
                                patternFound = visitBinaryOperatorAddSubOp(I);
                            }

                            // a = 0 - b
                            // c = a + d
                            //    =>
                            // c = d - b
                            if (!patternFound)
                            {
                                patternFound = visitBinaryOperatorPropNegate(I);
                            }
                        }

                        // fmul/fadd propagation
                        if (!patternFound)
                        {
                            patternFound = visitBinaryOperatorFmulFaddPropagation(I);
                        }

                        // A/B +C/D can be changed to (A * D +C * B)/(B * D).
                        if (!patternFound && IGC_IS_FLAG_ENABLED(EnableSumFractions))
                        {
                            patternFound = visitBinaryOperatorDivAddDiv(I);
                        }

                        if (!patternFound && IGC_IS_FLAG_ENABLED(EnableExtractCommonMultiplier))
                        {
                            patternFound = visitBinaryOperatorExtractCommonMultiplier(I);
                        }

                        if (!patternFound)
                        {
                            patternFound = visitExchangeCB(I);
                        }
                        m_isChanged |= patternFound;
                    }
                    break;

                case Instruction::FMul:
                    if ( (fp0 && fp0->isZero()) ||
                         (fp1 && fp1->isZero()) )
                    {
                        // X * 0 => 0
                        // 0 * X => 0
                        I.replaceAllUsesWith(ConstantFP::get(opType, 0));
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    else if ( fp0 && fp0->isExactlyValue( 1.0 ) )
                    {
                        // 1 * X => X
                        I.replaceAllUsesWith(op1);
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    else if ( fp1 && fp1->isExactlyValue( 1.0 ) )
                    {
                        // X * 1 => X
                        I.replaceAllUsesWith(op0);
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    // X * -1 => -X
                    else if( fp1 && fp1->isExactlyValue( -1.0 ) )
                    {
                        I.replaceAllUsesWith(
                            copyIRFlags(BinaryOperator::CreateFSub(ConstantFP::get(opType, 0), op0, "", &I), &I));
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    else if( fp0 && fp0->isExactlyValue( -1.0 ) )
                    {
                        I.replaceAllUsesWith(
                            copyIRFlags(BinaryOperator::CreateFSub(ConstantFP::get(opType, 0), op1, "", &I), &I));
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    else
                    {
                        bool patternFound = false;

                        if (fp0 || fp1)
                        {
                            // a = b * C0
                            // d = a * C1
                            //    =>
                            // d = b * ( C0 * C1 )
                            patternFound = visitBinaryOperatorTwoConstants(I);
                        }

                        // fmul/fadd propagation
                        if (!patternFound)
                        {
                            patternFound = visitBinaryOperatorFmulFaddPropagation(I);
                        }

                        //x*(1 - a) = x - x*a
                        if (!patternFound)
                        {
                            patternFound = visitBinaryOperatorFmulToFmad(I);
                        }

                        //C1*(a + C0) = a*C1 + C0*C1
                        if (!patternFound)
                        {
                            patternFound = visitBinaryOperatorToFmad(I);
                        }

                        m_isChanged |= patternFound;
                    }
                    break;

                case Instruction::FDiv:
                    if ( fp0 && fp0->isZero() )
                    {
                        // 0 / X => 0
                        I.replaceAllUsesWith(ConstantFP::get(opType, 0));
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    else if ( fp1 && fp1->isExactlyValue( 1.0 ) )
                    {
                        // X / 1 => X
                        I.replaceAllUsesWith(op0);
                        ++Stat_FloatRemoved;
                        m_isChanged = true;
                    }
                    else
                    {
                        // a = 1 / b
                        // c = 1 / a
                        //    =>
                        // c = b
                        //     or
                        // a = 1 / b
                        // d = c / a
                        //    =>
                        // d = b * c
                        bool patternFound = false;
                        patternFound = visitBinaryOperatorDivDivOp(I);

                        // 1/rsq -> rsq or a/rsq -> a * sqrt
                        if (!patternFound)
                        {
                            patternFound = visitBinaryOperatorDivRsq(I);
                        }

                        // skip for double type.
                        if (opType->getTypeID() == llvm::Type::FloatTyID || opType->getTypeID() == llvm::Type::HalfTyID)
                        {
                            // add r6.x, -r6.y, |r6.x|
                            // div_sat r6.x, r6.x, r6.y
                            //     To
                            // div r6.y, l(1.000000, 1.000000, 1.000000, 1.000000), r6.y
                            // mad_sat r6.x, | r6.x | , r6.y, l(-1.000000)
                            if (!patternFound)
                            {
                                patternFound = visitBinaryOperatorAddDiv(I);
                            }

                            // FDIV to FMUL+INV
                            if (!patternFound)
                            {
                                if (!(fp0 && fp0->isExactlyValue(1.0)))
                                {
                                    if (m_ctx->getModuleMetaData()->compOpt.FastRelaxedMath || I.hasAllowReciprocal())
                                    {
                                        Value *invOp = copyIRFlags(BinaryOperator::CreateFDiv(ConstantFP::get(opType, 1.0), op1, "", &I), &I);
                                        I.replaceAllUsesWith(
                                            copyIRFlags(BinaryOperator::CreateFMul(op0, invOp, "", &I), &I));
                                        patternFound = true;
                                    }
                                }
                            }
                        }
                        m_isChanged |= patternFound;
                    }
                    break;

                default:
                    break;
            }
        }
    }
}

bool CustomUnsafeOptPass::visitFCmpInstFCmpFAddOp(FCmpInst &FC)
{
    //  %3 = fadd float %2, 0x40015C29
    //  %4 = fcmp uge float %3, 0.0
    //         =>
    //  %4 = fcmp uge float %2, -(0x40015C29)
    // only do the optimization if we add has only one use since it could prevent us to do
    // other optimization otherwise

    Value* fcmpOp1 = FC.getOperand(1);
    ConstantFP *fcmpConstant = dyn_cast<ConstantFP>(fcmpOp1);
    if( fcmpConstant )
    {
        llvm::Instruction* faddInst = llvm::dyn_cast<llvm::Instruction>( FC.getOperand(0) );
        if( faddInst &&
            ( faddInst->getOpcode() == Instruction::FAdd ||
            faddInst->getOpcode() == Instruction::FSub ) &&
            faddInst->hasOneUse())
        {
            Value* faddOp1 = faddInst->getOperand(1);
            ConstantFP *faddConstant = dyn_cast<ConstantFP>(faddOp1);
            if( faddConstant )
            {
                APFloat newConstantFloat(0.0);
                if( faddInst->getOpcode() == Instruction::FAdd )
                {
                    newConstantFloat = fcmpConstant->getValueAPF();
                    newConstantFloat.subtract(faddConstant->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                }
                else
                {
                    newConstantFloat = fcmpConstant->getValueAPF();
                    newConstantFloat.add(faddConstant->getValueAPF(), llvm::APFloat::rmNearestTiesToEven);
                }

                ConstantFP* newConstant = ConstantFP::get(fcmpConstant->getContext(), newConstantFloat);
                FC.setOperand( 0, faddInst->getOperand(0) );
                FC.setOperand( 1, newConstant );
                ++Stat_FcmpRemoved;
                return true;
            }
        }
    }
    return false;
}

bool CustomUnsafeOptPass::visitFMulFCmpOp(FCmpInst &FC)
{
    // pattern match fmul+fsub+fcmp into fcmp
    bool patternFound = false;
    llvm::Instruction* prevInst[2];
    prevInst[0] = llvm::dyn_cast<llvm::Instruction>(FC.getOperand(0));
    prevInst[1] = llvm::dyn_cast<llvm::Instruction>(FC.getOperand(1));

    if (!prevInst[0] || !prevInst[1])
    {
        return false;
    }

    for (int i = 0; i < 2; i++)
    {
        if (prevInst[i]->getOpcode() != Instruction::FSub ||
            prevInst[1 - i]->getOpcode() != Instruction::FMul)
        {
            continue;
        }
        ConstantFP *fpc = dyn_cast<ConstantFP>(prevInst[i]->getOperand(0));
        if (!fpc || !fpc->isZero() || prevInst[i]->getOperand(1) != prevInst[1 - i])
        {
            continue;
        }
        // Found the following template:
        //   op_<1-i>: %mul = fmul float %x, %y
        //   op_<i>  : %sub = fsub float 0.000000e+00, %mul
        //             %cmp = fcmp <cmpOp> float %op_0, %op_1

        if (prevInst[1 - i]->getOperand(0) == prevInst[1 - i]->getOperand(1))
        {
            // %x == %y --> %mul =  (x^2) always >=0
            //              %sub = -(x^2) always <=0

            if ((FC.getPredicate() == FCmpInst::FCMP_OLT && i == 0) ||
                (FC.getPredicate() == FCmpInst::FCMP_OGT && i == 1))
            {
                // Optimize:
                //   %cmp = fcmp olt float %sub, %mul       -> cmp.lt -(x^2), (x^2)
                // or:
                //   %cmp = fcmp ogt float %mul, %sub       -> cmp.gt (x^2), -(x^2)
                // into:
                //   %cmp = fcmp one float %x, 0          -> cmp.ne (x^2), 0
                FC.setPredicate(FCmpInst::FCMP_ONE);
                FC.setOperand(0, prevInst[1 - i]->getOperand(0));
                FC.setOperand(1, ConstantFP::get(Type::getFloatTy(FC.getContext()), 0));
                patternFound = true;
                break;
            }
        }
        else if (ConstantFP *fmulConstant = dyn_cast<ConstantFP>(prevInst[1 - i]->getOperand(1)))
        {
            if (fmulConstant->isZeroValue())
            {
                continue;
            }
            // Optimize:
            //   %mul = fmul float %x, 5.000000e-01     ->   (x * constant)
            //   %sub = fsub float 0.000000e+00, %mul   ->  -(x * constant)
            //   %cmp = fcmp <cmpOp> float %mul, %sub
            // into:
            //   %cmp = fcmp <cmpOp> float %x, 0  [if (constant>0)]
            // or:
            //   %cmp = fcmp <cmpOp> float 0, %x  [if (constant<0)]

            if (fmulConstant->isNegative())
            {
                if (i == 0)
                {
                    //handling case:
                    //    %mul = fmul float %x, -5.000000e-01     ->   (x * constant) 
                    //    %sub = fsub float 0.000000e+00, %mul   ->  -(x * constant) 
                    //    %cmp = fcmp <cmpOp> float %sub, %mul
                    // into:
                    //    %cmp = fcmp <cmpOp> float %x, 0  [since (constant<0)]
                    FC.setOperand(1, ConstantFP::get(Type::getFloatTy(FC.getContext()), 0));
                    FC.setOperand(0, prevInst[1 - i]->getOperand(0));
                    patternFound = true;
                }
                else
                {
                    //handling case:
                    //    %mul = fmul float %x, -5.000000e-01     ->   (x * constant) 
                    //    %sub = fsub float 0.000000e+00, %mul   ->  -(x * constant) 
                    //    %cmp = fcmp <cmpOp> float %mul, %sub
                    // into:
                    //    %cmp = fcmp <cmpOp> float 0, %x  [since (constant<0)]
                    FC.setOperand(0, ConstantFP::get(Type::getFloatTy(FC.getContext()), 0));
                    FC.setOperand(1, prevInst[1 - i]->getOperand(0));
                    patternFound = true;
                }
            }
            else
            {
                //handling case:
                //    %mul = fmul float %x, 5.000000e-01     ->   (x * constant)
                //    %sub = fsub float 0.000000e+00, %mul   ->  -(x * constant)
                //    %cmp = fcmp <cmpOp> float %sub, %mul
                if (i == 0)
                {
                    FC.setOperand(0, ConstantFP::get(Type::getFloatTy(FC.getContext()), 0));
                    FC.setOperand(1, prevInst[1 - i]->getOperand(0));
                    patternFound = true;
                }
                else
                {
                    //handling case:
                    //    %mul = fmul float %x, 5.000000e-01     ->   (x * constant)
                    //    %sub = fsub float 0.000000e+00, %mul   ->  -(x * constant)
                    //    %cmp = fcmp <cmpOp> float %mul, %sub

                    FC.setOperand(0, prevInst[1 - i]->getOperand(0));
                    FC.setOperand(1, ConstantFP::get(Type::getFloatTy(FC.getContext()), 0));
                    patternFound = true;
                }
            }
            break;
        }
    }
    return patternFound;
}

bool CustomUnsafeOptPass::visitFCmpInstFCmpSelOp(FCmpInst &FC)
{
    //  %17 = fcmp ole float %16, 0.000000e+00
    //  %18 = select i1 %17, float 0.000000e+00, float 1.000000e+00
    //  %19 = fsub float -0.000000e+00, %18
    //  %20 = fcmp ueq float %18, %19
    //         =>
    //  %20 = fcmp ole float %16, 0.000000e+00
    llvm::Instruction* fSubInst = llvm::dyn_cast<llvm::Instruction>( FC.getOperand(1) );
    if( fSubInst &&
        fSubInst->getOpcode() == Instruction::FSub )
    {
        ConstantFP *fSubConstant = dyn_cast<ConstantFP>(fSubInst->getOperand(0));

        llvm::Instruction* selectInst = llvm::dyn_cast<llvm::Instruction>( FC.getOperand(0) );

        if( selectInst &&
            selectInst->getOpcode() == Instruction::Select &&
            selectInst == llvm::dyn_cast<llvm::Instruction>( fSubInst->getOperand(1) ) &&
            fSubConstant &&
            fSubConstant->isZero())
        {
            ConstantFP *selectConstant1 = dyn_cast<ConstantFP>(selectInst->getOperand(1));
            ConstantFP *selectConstant2 = dyn_cast<ConstantFP>(selectInst->getOperand(2));

            llvm::Instruction* fCmpInst = llvm::dyn_cast<llvm::Instruction>( selectInst->getOperand(0) );

            if (fCmpInst &&
                fCmpInst->getOpcode() == Instruction::FCmp &&
                selectConstant1 && selectConstant2 &&
                selectConstant1->isZero() && !selectConstant2->isZero() )
            {
                FC.setOperand(0,fCmpInst->getOperand(0));
                FC.setOperand(1,fCmpInst->getOperand(1));
                if( FC.getPredicate() == FCmpInst::FCMP_UNE )
                {
                    FC.setPredicate(dyn_cast<FCmpInst>(fCmpInst)->getInversePredicate());
                }
                else
                {
                    FC.setPredicate(dyn_cast<FCmpInst>(fCmpInst)->getPredicate());
                }
                Stat_FcmpRemoved+=3;
                return true;
            }
        }
    }
    return false;
}

void CustomUnsafeOptPass::visitFCmpInst(FCmpInst &FC)
{
    bool patternFound = false;
    if (FC.use_empty())
    {
        return;
    }
    if(FC.getPredicate()==CmpInst::FCMP_UNO)
    {
        if (m_ctx->m_DriverInfo.IgnoreNan())
        {
            FC.replaceAllUsesWith(ConstantInt::getFalse(FC.getType()));
            FC.eraseFromParent();
            ++Stat_FcmpRemoved;
            patternFound = true;
        }
    }
    else if(FC.getPredicate()==CmpInst::FCMP_ORD)
    {
        if (m_ctx->m_DriverInfo.IgnoreNan())
        {
            FC.replaceAllUsesWith(ConstantInt::getTrue(FC.getType()));
            FC.eraseFromParent();
            ++Stat_FcmpRemoved;
            patternFound = true;
        }
    }
    else
    {
        patternFound = visitFCmpInstFCmpFAddOp(FC);
        if (!patternFound &&
            (FC.getPredicate() == FCmpInst::FCMP_UEQ ||
             FC.getPredicate() == FCmpInst::FCMP_UNE ))
        {
            patternFound = visitFCmpInstFCmpSelOp(FC);
        }

        if (!patternFound)
        {
            patternFound = visitFMulFCmpOp(FC);
        }
    }
    m_isChanged |= patternFound;
}

void CustomUnsafeOptPass::visitSelectInst(SelectInst &I)
{
    if (llvm::FCmpInst* cmpInst = llvm::dyn_cast<llvm::FCmpInst>(I.getOperand(0)))
    {
        if (dyn_cast<FCmpInst>(cmpInst)->getPredicate() == FCmpInst::FCMP_OEQ)
        {
            if (ConstantFP* cmpConstant = dyn_cast<ConstantFP>(cmpInst->getOperand(1)))
            {
                if (cmpConstant->isZeroValue())
                {
                    /*
                    %16 = fmul float %15, %0
                    %17 = fadd float %16, %14
                    %24 = fcmp oeq float %0, 0.000000e+00
                    %25 = select i1 % 24, float %14, float %17
                        to
                    %25 = %17

                    */
                    bool foundPattern = false;
                    llvm::Instruction* addInst = llvm::dyn_cast<llvm::Instruction>(I.getOperand(2)); // %17
                    if (addInst && addInst->getOpcode() == Instruction::FAdd)
                    {
                        for (uint j = 0; j < 2; j++)
                        {
                            llvm::Instruction* mulInst = llvm::dyn_cast<llvm::Instruction>(addInst->getOperand(j)); // %16
                            if (mulInst && mulInst->getOpcode() == Instruction::FMul &&
                                addInst->getOperand(1-j) == I.getOperand(1) )
                            {
                                for (uint k = 0; k < 2; k++)
                                {
                                    if (mulInst->getOperand(k) == cmpInst->getOperand(0))
                                    {
                                        I.replaceAllUsesWith(I.getOperand(2));
                                        foundPattern = true;
                                        break;
                                    }
                                }
                                if (foundPattern)
                                    break;
                            }
                        }
                    }
                }
                else if (cmpConstant->isExactlyValue(1.f))
                {
                    /*
                    %21 = fsub float %8, %14
                    %22 = fmul float %21, %0
                    %23 = fadd float %22, %14
                    %24 = fcmp oeq float %0, 1.000000e+00
                    %27 = select i1 %24, float %8, float %23
                        to
                    %27 = %23

                    */
                    bool foundPattern = false;
                    llvm::Instruction* addInst = llvm::dyn_cast<llvm::Instruction>(I.getOperand(2)); // %23
                    if (addInst && addInst->getOpcode() == Instruction::FAdd)
                    {
                        for (uint j = 0; j < 2; j++)
                        {
                            llvm::Instruction* mulInst = llvm::dyn_cast<llvm::Instruction>(addInst->getOperand(j)); // %22
                            if (mulInst && mulInst->getOpcode() == Instruction::FMul)
                            {
                                for (uint k = 0; k < 2; k++)
                                {
                                    llvm::Instruction* subInst = llvm::dyn_cast<llvm::Instruction>(mulInst->getOperand(k)); // %21
                                    if (subInst &&
                                        subInst->getOpcode() == Instruction::FSub &&
                                        subInst->getOperand(0) == I.getOperand(1) &&
                                        subInst->getOperand(1) == addInst->getOperand(1-j) &&
                                        mulInst->getOperand(1 - k) == cmpInst->getOperand(0))
                                    {
                                        I.replaceAllUsesWith(I.getOperand(2));
                                        foundPattern = true;
                                        break;
                                    }
                                }
                                if (foundPattern)
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }
}

void CustomUnsafeOptPass::strengthReducePow(
    IntrinsicInst* intrin, Value* exponent)
{
    Value* src = intrin->getOperand(0);
    IRBuilder<> irb(intrin);
    irb.setFastMathFlags(intrin->getFastMathFlags());
    if (exponent == ConstantFP::get(exponent->getType(), 0.5))
    {
        // pow(x, 0.5) -> sqrt(x)
        llvm::Function* sqrtIntr = llvm::Intrinsic::getDeclaration(
            m_ctx->getModule(), Intrinsic::sqrt, src->getType());
        llvm::CallInst* sqrt = irb.CreateCall(sqrtIntr, src);
        intrin->replaceAllUsesWith(sqrt);
        intrin->eraseFromParent();
    }
    else
    if (exponent == ConstantFP::get(exponent->getType(), 1.0))
    {
        intrin->replaceAllUsesWith(src);
        intrin->eraseFromParent();
    }
    else
    if (exponent == ConstantFP::get(exponent->getType(), 2.0))
    {
        // pow(x, 2.0) -> x * x
        Value* x2 = irb.CreateFMul(src, src);
        intrin->replaceAllUsesWith(x2);
        intrin->eraseFromParent();
    }
    else
    if (exponent == ConstantFP::get(exponent->getType(), 3.0))
    {
        // pow(x, 3.0) -> x * x * x
        Value* x2 = irb.CreateFMul(src, src); 
        Value* x3 = irb.CreateFMul(x2, src); 
        intrin->replaceAllUsesWith(x3);
        intrin->eraseFromParent();
    }
    else
    if (exponent == ConstantFP::get(exponent->getType(), 4.0))
    {
        // pow(x, 4.0) -> (x*x) * (x*x)
        Value* x2 = irb.CreateFMul(src, src); 
        Value* x4 = irb.CreateFMul(x2, x2);
        intrin->replaceAllUsesWith(x4);
        intrin->eraseFromParent();
    }
    else
    if (exponent == ConstantFP::get(exponent->getType(), 5.0))
    {
        // pow(x, 5.0) -> (x*x) * (x*x) * x
        Value* x2 = irb.CreateFMul(src, src);
        Value* x4 = irb.CreateFMul(x2, x2);
        Value* x5 = irb.CreateFMul(x4, src);
        intrin->replaceAllUsesWith(x5);
        intrin->eraseFromParent();
    }
    else
    if (exponent == ConstantFP::get(exponent->getType(), 6.0))
    {
        // pow(x, 6.0) -> (x*x) * (x*x) * (x*x)
        Value* x2 = irb.CreateFMul(src, src); 
        Value* x4 = irb.CreateFMul(x2, x2); 
        Value* x6 = irb.CreateFMul(x4, x2); 
        intrin->replaceAllUsesWith(x6);
        intrin->eraseFromParent();
    }
    else
    if (exponent == ConstantFP::get(exponent->getType(), 8.0))
    {
        // pow(x, 8.0) -> ((x*x) * (x*x)) * ((x*x) * (x*x))
        Value* x2 = irb.CreateFMul(src, src);
        Value* x4 = irb.CreateFMul(x2, x2); 
        Value* x8 = irb.CreateFMul(x4, x4);
        intrin->replaceAllUsesWith(x8);
        intrin->eraseFromParent();
    }
    else
    if (IGC_IS_FLAG_ENABLED(EnablePowToLogMulExp))
    {
        // pow(x, y) -> exp2(log2(x) * y)
        Function* logf = Intrinsic::getDeclaration(
            m_ctx->getModule(), Intrinsic::log2, src->getType());
        Function* expf = Intrinsic::getDeclaration(
            m_ctx->getModule(), Intrinsic::exp2, src->getType());
        CallInst* logv = irb.CreateCall(logf, src);
        Value* mulv = irb.CreateFMul(logv, exponent);
        CallInst* expv = irb.CreateCall(expf, mulv);
        intrin->replaceAllUsesWith(expv);
        intrin->eraseFromParent();
    }
}

void CustomUnsafeOptPass::visitCallInst(llvm::CallInst &I)
{
    if(llvm::IntrinsicInst* intr = dyn_cast<llvm::IntrinsicInst>(&I))
    {
        llvm::Intrinsic::ID ID = intr->getIntrinsicID();
        if(ID == llvm::Intrinsic::pow)
        {
            strengthReducePow(intr, intr->getOperand(1));
        }
        else if (ID == llvm::Intrinsic::sqrt)
        {
            // y*y = x if y = sqrt(x).
            for (auto iter = intr->user_begin(); iter != intr->user_end(); iter++)
            {
                if (llvm::Instruction* mul = dyn_cast<Instruction>(*iter))
                {
                    if (mul->getOpcode() == Instruction::FMul &&
                        mul->getOperand(0) == mul->getOperand(1))
                    {
                        mul->replaceAllUsesWith(intr->getOperand(0));
                    }
                }
            }
        }
    }
}

// Search for reassociation candidate.
static bool searchFAdd(Instruction *DefI, Instruction *UseI, unsigned &level)
{
    // Could search further, however we need to rewrite
    // instructions along the path. So limit this two
    // levels, which should cover common cases.
    if (level >= 2)
        return false;
    if (DefI->getParent() != UseI->getParent() || !DefI->hasOneUse() ||
        UseI->user_empty())
        return false;
    if (UseI->getOpcode() != Instruction::FAdd &&
        UseI->getOpcode() != Instruction::FSub)
        return false;

    // Swap operands such DefI is always the LHS in UseI.
    Value *Op = UseI->getOperand(1);
    bool IsFAdd = UseI->getOpcode() == Instruction::FAdd;
    if (DefI == Op)
    {
        if (IsFAdd)
        {
            cast<BinaryOperator>(UseI)->swapOperands();
            Op = UseI->getOperand(1);
        }
        else
        {
            return false;
        }
    }

    // The rhs is not mul, so could be folded into a mad.
    auto RHS = dyn_cast<Instruction>(Op);
    if (RHS && RHS->getOpcode() != Instruction::FMul)
        return true;

    // For simplicity, only allow the last level to be fsub.
    if (!IsFAdd)
        return false;

    return searchFAdd(UseI, UseI->user_back(), ++level);
}

// Match and re-associate arithmetic computation to emit more
// mad instructions. E.g.
//
// a * b + c * d +/- e -> MUL, MAD, ADD
//
// After reassociation, this becomes
//
// a * b +/- e + c * d -> MAD, MAD
//
void CustomUnsafeOptPass::reassociateMulAdd(Function &F)
{
    if (m_disableReorderingOpt)
    {
        return;
    }

    auto modMD = getAnalysis<MetaDataUtilsWrapper>().getModuleMetaData();
    if (!modMD->compOpt.MadEnable)
    {
        return;
    }

    using namespace PatternMatch;

    for (auto &BB : F.getBasicBlockList())
    {
        for (auto I = BB.begin(); I != BB.end(); /*Empty*/)
        {
            Instruction *Inst = &*I++;
            Value *A, *B, *C, *D;
            // Match Exp = A * B + C * D with a single use so that
            // it is benefical to fold one FSub/FAdd with A * B.
            if (match(Inst, m_OneUse(m_FAdd(m_FMul(m_Value(A), m_Value(B)),
                                            m_FMul(m_Value(C), m_Value(D))))))
            {
                Instruction *L0 = Inst->user_back();
                unsigned level = 0;
                if (searchFAdd(Inst, L0, level))
                {
                    Value *T0 = Inst->getOperand(0);
                    Value *T1 = Inst->getOperand(1);

                    // rewrite the expression tree
                    if (level == 0)
                    {
                        // t0 = A * B
                        // t1 = C * D
                        // t2 = t0 + t1  // Inst
                        // t3 = t2 - E   // L0
                        //
                        // as
                        //
                        // t0 = A * B
                        // t1 = C * D
                        // t2 = t0 + t1   // Inst
                        // ...
                        // t2n = t0 - E   // new Inst
                        // t3n = t2n + t1 // new L0
                        // t3  = t2 - E   // L0
                        IRBuilder<> Builder(L0);
                        Builder.setFastMathFlags(L0->getFastMathFlags());
                        Value *E = L0->getOperand(1);
                        auto OpKind = BinaryOperator::BinaryOps(L0->getOpcode());
                        Value *NewInst = Builder.CreateBinOp(OpKind, T0, E, Inst->getName());
                        Value *NewL0 = Builder.CreateFAdd(NewInst, T1, L0->getName());
                        L0->replaceAllUsesWith(NewL0);
                        m_isChanged = true;
                    }
                    else if (level == 1)
                    {
                        // t0 = A * B
                        // t1 = C * D
                        // t2 = E * F
                        // t3 = t0 + t1 // Inst
                        // t4 = t3 + t2 // L0
                        // t5 = t4 - G  // L1
                        //
                        // as
                        //
                        // t0 = A * B
                        // t1 = C * D
                        // t2 = E * F
                        // t3 = t0 + t1  // Inst
                        // t4 = t3 + t2  // L0
                        // ...
                        // t3n = t0 - G   // NewInst
                        // t4n = t3n + t2 // NewL0
                        // t5n = t4n + t1 // NewL1
                        // t5  = t4 - G   // L1
                        Instruction *L1 = L0->user_back();
                        IRBuilder<> Builder(L1);
                        Builder.setFastMathFlags(L1->getFastMathFlags());
                        Value *T2 = L0->getOperand(1);
                        Value *G = L1->getOperand(1);

                        auto OpKind = BinaryOperator::BinaryOps(L1->getOpcode());
                        Value *NewInst = Builder.CreateBinOp(OpKind, T0, G, Inst->getName());
                        Value *NewL0 = Builder.CreateFAdd(NewInst, T2, L0->getName());
                        Value *NewL1 = Builder.CreateFAdd(NewL0, T1, L1->getName());
                        L1->replaceAllUsesWith(NewL1);
                        m_isChanged = true;
                    }
                }
            }
        }
    }
}

// This pass looks for potential patterns where, if some value evaluates
// to zero, then a long chain of computation will be zero as well and
// we can just skip it (a so called 'early out').  For example:
//
// before:
//
// a = some value; // might be zero
// result = a * expensive_operation();
//
// after:
// 
// a = some value;
// if (a == 0)
//   result = 0;
// else
//   result = a * expensive_operation();
//
// Currently this is used to target d3d workloads
// 
class EarlyOutPatterns : public FunctionPass
{
public:
    static char ID;

2342 2343
    EarlyOutPatterns() : FunctionPass(ID),
        m_ctx(nullptr)
2344 2345 2346 2347 2348 2349 2350 2351
    {
    }
    virtual void getAnalysisUsage(llvm::AnalysisUsage &AU) const
    {
        AU.addRequired<CodeGenContextWrapper>();
    }

    virtual bool runOnFunction(Function &F);
2352
    virtual bool processBlock(BasicBlock* BB);
2353 2354 2355 2356 2357 2358

    virtual llvm::StringRef getPassName() const
    {
        return "EarlyOutPatterns";
    }
private:
2359 2360
    static bool canOptimizeSampleInst(SmallVector<Instruction*, 4> &Channels, GenIntrinsicInst *GII);
    static bool canOptimizeDotProduct(SmallVector<Instruction*, 4> &Values, Instruction *I);
2361
    static bool canOptimizeNdotL(SmallVector<Instruction*, 4> &Values, FCmpInst *FC);
2362 2363 2364 2365 2366 2367 2368 2369
    static bool DotProductMatch(const Instruction *I);
    static bool DotProductSourceMatch(const Instruction *I);
    static BasicBlock* tryFoldAndSplit(
        ArrayRef<Instruction*> Values,
        Instruction *Root,
        const unsigned FoldThreshold,
        const unsigned FoldThresholdMultiChannel,
        const unsigned RatioNeeded);
2370 2371 2372 2373 2374 2375
    static bool trackAddSources(BinaryOperator* addInst);
    static DenseSet<const Value*> tryAndFoldValues(ArrayRef<Instruction*> Values);
    static BasicBlock* SplitBasicBlock(Instruction* inst, const DenseSet<const Value*> &FoldedVals);
    static bool FoldsToZero(const Instruction* inst, const Value* use, const DenseSet<const Value*> &FoldedVals);
    static void MoveOutputToConvergeBlock(BasicBlock* divergeBlock, BasicBlock* convergeBlock);
    static bool EarlyOutBenefit(
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
        const Instruction* earlyOutInst,
        const DenseSet<const Value*> &FoldedVals,
        const unsigned int ratioNeeded);
    static void foldFromAdd(SmallVector<Instruction*, 4> &Values, Instruction *&NewInsertPoint);
    static Instruction* moveToDef(Instruction *Def, ArrayRef<Instruction*> Users);
    static bool isSplitProfitable(
        const Instruction *Root,
        ArrayRef<Instruction*> Values,
        const DenseSet<const Value*> &FoldedVals,
        // Number of instructions which needs to be folded in order for the optimization to be worth it
        const unsigned FoldThreshold,
        // For cases where we need to AND several channels we have a higher threshold
        const unsigned FoldThresholdMultiChannel,
        const unsigned RatioNeeded);
    static BasicBlock* cmpAndSplitAtPoint(
        Instruction *Root,
        ArrayRef<Instruction*> Values,
        const DenseSet<const Value*> &FoldedVals);
2394
    CodeGenContext *m_ctx;
2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405
};

char EarlyOutPatterns::ID = 0;

FunctionPass* IGC::CreateEarlyOutPatternsPass()
{
    return new EarlyOutPatterns();
}

bool EarlyOutPatterns::runOnFunction(Function &F)
{
2406
    m_ctx = getAnalysis<CodeGenContextWrapper>().getCodeGenContext();
2407
    if (IGC_IS_FLAG_ENABLED(DisableEarlyOutPatterns) ||
2408
        m_ctx->m_DriverInfo.WaNOSNotResolved())
2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
    {
        return false;
    }
    bool changed = false;
    for(auto BI = F.begin(), BE = F.end(); BI != BE;)
    {
        BasicBlock* currentBB = &(*BI);
        ++BI;
        changed |= processBlock(currentBB);
    }
    return changed;
}

// Calculates whether the given 'use' evaluates to zero given that 'inst' is known to
// evaluate to zero.
bool EarlyOutPatterns::FoldsToZero(const Instruction* inst, const Value* use, const DenseSet<const Value*> &FoldedVals)
{
fftzeng's avatar
fftzeng committed
2426 2427 2428 2429
    auto isZero = [](const Value* V)
    {
        return isa<ConstantFP>(V) && cast<ConstantFP>(V)->isZero();
    };
2430

fftzeng's avatar
fftzeng committed
2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
    auto geZero = [](const Value* V)
    {
        if (auto *CFP = dyn_cast<ConstantFP>(V))
        {
            auto &APF = CFP->getValueAPF();
            if (CFP->getType()->isDoubleTy())
                return APF.convertToDouble() >= 0.0;
            else if (CFP->getType()->isFloatTy())
                return APF.convertToFloat() >= 0.0f;
        }
2441

fftzeng's avatar
fftzeng committed
2442 2443
        return false;
    };
2444

fftzeng's avatar
fftzeng committed
2445
    if (auto *binInst = dyn_cast<BinaryOperator>(use))
2446
    {
fftzeng's avatar
fftzeng committed
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
        switch (binInst->getOpcode())
        {
        case Instruction::FMul:
        case Instruction::And:
            return true;
            // watch out for the zero in the denominator
        case Instruction::FDiv:
            return inst != binInst->getOperand(1);
        case Instruction::FSub:
            return isZero(binInst->getOperand(0)) ||
                isZero(binInst->getOperand(1));
        default:
            return false;
        }
2461
    }
fftzeng's avatar
fftzeng committed
2462 2463 2464 2465 2466
    else if (auto *BI = dyn_cast<BitCastInst>(use))
    {
        return true;
    }
    else if (auto *SI = dyn_cast<SelectInst>(use))
2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
    {
        // Assuming %x is 0, if the other operand is also
        // 0 the result of the select must be 0 as well.

        // select i1 %p, float 0.0, float %x
        bool zero0 = isZero(SI->getTrueValue());
        // select i1 %p, float %x, float 0.0
        bool zero1 = isZero(SI->getFalseValue());

        if (zero0 || zero1)
            return true;

        // If we have previously visited this select with a
        // folded value, check the map and allow the
        // select to be folded.
        auto *OtherOp = (inst == SI->getTrueValue()) ?
            SI->getFalseValue() :
            SI->getTrueValue();

        return FoldedVals.count(OtherOp) != 0;
    }
2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
    else if (auto* CI = dyn_cast<CallInst>(use))
    {
        // if x == 0
        switch (GetOpCode(CI))
        {
        // max(0, x) or min(x, 0) == 0
        case llvm_max:
            return isZero(CI->getArgOperand(0)) ||
                isZero(CI->getArgOperand(1));
        case llvm_min:
            return geZero(CI->getArgOperand(0)) ||
                geZero(CI->getArgOperand(1));

        // Useful in matching dp3_sat
        case llvm_fsat:
            return true;
        default:
            return false;
        }
    }
2508 2509 2510 2511 2512 2513 2514
    else if (auto* inst = dyn_cast<Instruction>(use))
    {
        if (inst->getOpcode() == Instruction::SExt)
        {
            return true;
        }
    }
2515 2516 2517 2518 2519 2520 2521

    return false;
}

// Count the number of instruction in the new block created if the ratio of instruction duplicated
// by instruction skipped is greater than the threshold return false
bool EarlyOutPatterns::EarlyOutBenefit(
2522 2523 2524
    const Instruction* earlyOutInst,
    const DenseSet<const Value*> &FoldedVals,
    const unsigned int ratioNeeded)
2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543
{
    auto* BB = earlyOutInst->getParent();

    unsigned int numberOfInstruction = 0;
    unsigned int numberOfInstructionDuplicated = 0;

    DenseSet<const Value*> instDuplicated;
    instDuplicated.insert(BB->getTerminator());

    for(auto it = BB->rbegin(); &(*it) != earlyOutInst; ++it)
    { 
        numberOfInstruction++;
        const Instruction* inst = &(*it);

        if (FoldedVals.count(inst) != 0)
            continue;

        bool instNeeded = false;

2544
        // We can't throw away side effects
2545 2546 2547 2548 2549 2550 2551 2552 2553 2554
        if(inst->mayWriteToMemory())
        {
            instNeeded = true;
        }
        else
        {
            for (auto *UI : inst->users())
            {
                if (auto *useInst = dyn_cast<Instruction>(UI))
                {
2555 2556 2557
                    // We must also keep the instruction if its use has
                    // escaped into another BB or, transitively, because
                    // its user must be kept.
2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
                    if(useInst->getParent() != BB || instDuplicated.count(useInst) != 0)
                    {
                        instNeeded = true;
                        break;
                    }
                }
            }
        }

        if(instNeeded)
        {
            bool noOp = false;
            if(inst->getOpcode() == Instruction::FAdd)
            {
2572 2573
                // x + 0 = x, should be folded so don't add it
                // to the count.
2574
                if(FoldedVals.count(inst->getOperand(0)) != 0 ||
2575
                   FoldedVals.count(inst->getOperand(1)) != 0)
2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
                {
                    noOp = true;
                }
            }
            if(!noOp)
            {
                numberOfInstructionDuplicated++;
            }
            instDuplicated.insert(inst);
        }
    }

    return numberOfInstructionDuplicated * ratioNeeded <= numberOfInstruction;
}

void EarlyOutPatterns::foldFromAdd(SmallVector<Instruction*, 4> &Values, Instruction *&NewInsertPoint)
{
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
    // if the sample has only one channel
    if (Values.size() == 1)
    {
        // if it has one use which is a add then try to fold from the add
        if (Values[0]->hasOneUse())
        {
            BinaryOperator* bin = dyn_cast<BinaryOperator>(*Values[0]->user_begin());
            if (bin && bin->getOpcode() == Instruction::FAdd)
            {
                if (trackAddSources(bin))
                {
                    // try to fold the result of the add instead of the sample_C
                    Values[0] = bin;
                    NewInsertPoint = bin;
                }
            }
        }
    }
2611 2612 2613 2614
}

Instruction* EarlyOutPatterns::moveToDef(Instruction *Def, ArrayRef<Instruction*> Users)
{
fftzeng's avatar
fftzeng committed
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633
    Instruction *insertPoint = Def;
    
    for (auto it : Users)
    {
        // has a bitcast between extractelement and sample* instruction.
        // need to move the bitcast too.
        if (it->getOperand(0) != Def)
        {
            auto bitcast = cast<Instruction>(it->getOperand(0));
            bitcast->moveBefore(insertPoint->getNextNode());
            insertPoint = bitcast;
        }
    }
    for ( auto it : Users)
    {
        // move all the users right after the def instruction for simplicity
        it->moveBefore(insertPoint->getNextNode());
        insertPoint = it;
    }
2634

fftzeng's avatar
fftzeng committed
2635
    return insertPoint;
2636 2637 2638
}

bool EarlyOutPatterns::isSplitProfitable(
2639 2640 2641 2642 2643 2644
    const Instruction *Root,
    ArrayRef<Instruction*> Values,
    const DenseSet<const Value*> &FoldedVals,
    const unsigned FoldThreshold,
    const unsigned FoldThresholdMultiChannel,
    const unsigned RatioNeeded)
2645
{
2646
    const unsigned NumInstFolded = FoldedVals.size();
2647

2648 2649 2650 2651 2652
    const bool SplitProfitable =
        (NumInstFolded > FoldThreshold) &&
        // Check if we folded, we need a higher threshold if we have to check more channels
        (Values.size() == 1 || NumInstFolded > FoldThresholdMultiChannel) &&
        EarlyOutBenefit(Root, FoldedVals, RatioNeeded);
2653

2654
    return SplitProfitable;
2655 2656 2657 2658 2659 2660
}

// Once a candidate position 'Root' has been determined to be
// a profitable splitting point, generate the == 0 comparison
// and split the basic block at that point.
BasicBlock* EarlyOutPatterns::cmpAndSplitAtPoint(
2661 2662 2663
    Instruction *Root,
    ArrayRef<Instruction*> Values,
    const DenseSet<const Value*> &FoldedVals)
2664 2665
{
    IRBuilder<> builder(Root->getNextNode());
fftzeng's avatar
fftzeng committed
2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677
    Instruction *splitCondition = nullptr;

    if (Values[0]->getType()->isIntOrIntVectorTy())
    {
        splitCondition = cast<Instruction>(
            builder.CreateICmp(ICmpInst::ICMP_EQ, Values[0], ConstantInt::get(Values[0]->getType(), 0)));
    }
    else
    {
        splitCondition = cast<Instruction>(
            builder.CreateFCmpOEQ(Values[0], ConstantFP::get(Values[0]->getType(), 0.0)));
    }
2678 2679 2680

    for (unsigned int i = 1; i < Values.size(); i++)
    {
fftzeng's avatar
fftzeng committed
2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
        if (Values[i]->getType()->isIntOrIntVectorTy())
        {
            Value* cmp = builder.CreateICmp(ICmpInst::ICMP_EQ, Values[i], ConstantInt::get(Values[i]->getType(), 0));
            splitCondition = cast<Instruction>(builder.CreateAnd(splitCondition, cmp));
        }
        else
        {
            Value* cmp = builder.CreateFCmpOEQ(Values[i], ConstantFP::get(Values[i]->getType(), 0.0));
            splitCondition = cast<Instruction>(builder.CreateAnd(splitCondition, cmp));
        }
2691 2692 2693
    }

    auto* BB = SplitBasicBlock(splitCondition, FoldedVals);
2694
    return BB;
2695 2696 2697
}

BasicBlock* EarlyOutPatterns::tryFoldAndSplit(
2698 2699 2700 2701 2702
    ArrayRef<Instruction*> Values,
    Instruction *Root,
    const unsigned FoldThreshold,
    const unsigned FoldThresholdMultiChannel,
    const unsigned RatioNeeded)
2703
{
2704 2705 2706 2707 2708 2709 2710 2711 2712