Home | History | Annotate | Download | only in CodeGen
      1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This pass munges the code in the input function to better prepare it for
     11 // SelectionDAG-based code generation. This works around limitations in it's
     12 // basic-block-at-a-time approach. It should eventually be removed.
     13 //
     14 //===----------------------------------------------------------------------===//
     15 
     16 #include "llvm/CodeGen/Passes.h"
     17 #include "llvm/ADT/DenseMap.h"
     18 #include "llvm/ADT/SmallSet.h"
     19 #include "llvm/ADT/Statistic.h"
     20 #include "llvm/Analysis/InstructionSimplify.h"
     21 #include "llvm/Analysis/TargetLibraryInfo.h"
     22 #include "llvm/Analysis/TargetTransformInfo.h"
     23 #include "llvm/Analysis/ValueTracking.h"
     24 #include "llvm/IR/CallSite.h"
     25 #include "llvm/IR/Constants.h"
     26 #include "llvm/IR/DataLayout.h"
     27 #include "llvm/IR/DerivedTypes.h"
     28 #include "llvm/IR/Dominators.h"
     29 #include "llvm/IR/Function.h"
     30 #include "llvm/IR/GetElementPtrTypeIterator.h"
     31 #include "llvm/IR/IRBuilder.h"
     32 #include "llvm/IR/InlineAsm.h"
     33 #include "llvm/IR/Instructions.h"
     34 #include "llvm/IR/IntrinsicInst.h"
     35 #include "llvm/IR/MDBuilder.h"
     36 #include "llvm/IR/PatternMatch.h"
     37 #include "llvm/IR/Statepoint.h"
     38 #include "llvm/IR/ValueHandle.h"
     39 #include "llvm/IR/ValueMap.h"
     40 #include "llvm/Pass.h"
     41 #include "llvm/Support/CommandLine.h"
     42 #include "llvm/Support/Debug.h"
     43 #include "llvm/Support/raw_ostream.h"
     44 #include "llvm/Target/TargetLowering.h"
     45 #include "llvm/Target/TargetSubtargetInfo.h"
     46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
     47 #include "llvm/Transforms/Utils/BuildLibCalls.h"
     48 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
     49 #include "llvm/Transforms/Utils/Local.h"
     50 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
     51 using namespace llvm;
     52 using namespace llvm::PatternMatch;
     53 
     54 #define DEBUG_TYPE "codegenprepare"
     55 
     56 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
     57 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
     58 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
     59 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
     60                       "sunken Cmps");
     61 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
     62                        "of sunken Casts");
     63 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
     64                           "computations were sunk");
     65 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
     66 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
     67 STATISTIC(NumAndsAdded,
     68           "Number of and mask instructions added to form ext loads");
     69 STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
     70 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
     71 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
     72 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
     73 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
     74 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
     75 
     76 static cl::opt<bool> DisableBranchOpts(
     77   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
     78   cl::desc("Disable branch optimizations in CodeGenPrepare"));
     79 
     80 static cl::opt<bool>
     81     DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
     82                   cl::desc("Disable GC optimizations in CodeGenPrepare"));
     83 
     84 static cl::opt<bool> DisableSelectToBranch(
     85   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
     86   cl::desc("Disable select to branch conversion."));
     87 
     88 static cl::opt<bool> AddrSinkUsingGEPs(
     89   "addr-sink-using-gep", cl::Hidden, cl::init(false),
     90   cl::desc("Address sinking in CGP using GEPs."));
     91 
     92 static cl::opt<bool> EnableAndCmpSinking(
     93    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
     94    cl::desc("Enable sinkinig and/cmp into branches."));
     95 
     96 static cl::opt<bool> DisableStoreExtract(
     97     "disable-cgp-store-extract", cl::Hidden, cl::init(false),
     98     cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
     99 
    100 static cl::opt<bool> StressStoreExtract(
    101     "stress-cgp-store-extract", cl::Hidden, cl::init(false),
    102     cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
    103 
    104 static cl::opt<bool> DisableExtLdPromotion(
    105     "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
    106     cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
    107              "CodeGenPrepare"));
    108 
    109 static cl::opt<bool> StressExtLdPromotion(
    110     "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
    111     cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
    112              "optimization in CodeGenPrepare"));
    113 
    114 namespace {
    115 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
    116 typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
    117 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
    118 class TypePromotionTransaction;
    119 
    120   class CodeGenPrepare : public FunctionPass {
    121     const TargetMachine *TM;
    122     const TargetLowering *TLI;
    123     const TargetTransformInfo *TTI;
    124     const TargetLibraryInfo *TLInfo;
    125 
    126     /// As we scan instructions optimizing them, this is the next instruction
    127     /// to optimize. Transforms that can invalidate this should update it.
    128     BasicBlock::iterator CurInstIterator;
    129 
    130     /// Keeps track of non-local addresses that have been sunk into a block.
    131     /// This allows us to avoid inserting duplicate code for blocks with
    132     /// multiple load/stores of the same address.
    133     ValueMap<Value*, Value*> SunkAddrs;
    134 
    135     /// Keeps track of all instructions inserted for the current function.
    136     SetOfInstrs InsertedInsts;
    137     /// Keeps track of the type of the related instruction before their
    138     /// promotion for the current function.
    139     InstrToOrigTy PromotedInsts;
    140 
    141     /// True if CFG is modified in any way.
    142     bool ModifiedDT;
    143 
    144     /// True if optimizing for size.
    145     bool OptSize;
    146 
    147     /// DataLayout for the Function being processed.
    148     const DataLayout *DL;
    149 
    150   public:
    151     static char ID; // Pass identification, replacement for typeid
    152     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
    153         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
    154         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
    155       }
    156     bool runOnFunction(Function &F) override;
    157 
    158     const char *getPassName() const override { return "CodeGen Prepare"; }
    159 
    160     void getAnalysisUsage(AnalysisUsage &AU) const override {
    161       AU.addPreserved<DominatorTreeWrapperPass>();
    162       AU.addRequired<TargetLibraryInfoWrapperPass>();
    163       AU.addRequired<TargetTransformInfoWrapperPass>();
    164     }
    165 
    166   private:
    167     bool eliminateFallThrough(Function &F);
    168     bool eliminateMostlyEmptyBlocks(Function &F);
    169     bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
    170     void eliminateMostlyEmptyBlock(BasicBlock *BB);
    171     bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
    172     bool optimizeInst(Instruction *I, bool& ModifiedDT);
    173     bool optimizeMemoryInst(Instruction *I, Value *Addr,
    174                             Type *AccessTy, unsigned AS);
    175     bool optimizeInlineAsmInst(CallInst *CS);
    176     bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
    177     bool moveExtToFormExtLoad(Instruction *&I);
    178     bool optimizeExtUses(Instruction *I);
    179     bool optimizeLoadExt(LoadInst *I);
    180     bool optimizeSelectInst(SelectInst *SI);
    181     bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
    182     bool optimizeSwitchInst(SwitchInst *CI);
    183     bool optimizeExtractElementInst(Instruction *Inst);
    184     bool dupRetToEnableTailCallOpts(BasicBlock *BB);
    185     bool placeDbgValues(Function &F);
    186     bool sinkAndCmp(Function &F);
    187     bool extLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
    188                         Instruction *&Inst,
    189                         const SmallVectorImpl<Instruction *> &Exts,
    190                         unsigned CreatedInstCost);
    191     bool splitBranchCondition(Function &F);
    192     bool simplifyOffsetableRelocate(Instruction &I);
    193     void stripInvariantGroupMetadata(Instruction &I);
    194   };
    195 }
    196 
    197 char CodeGenPrepare::ID = 0;
    198 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
    199                    "Optimize for code generation", false, false)
    200 
    201 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
    202   return new CodeGenPrepare(TM);
    203 }
    204 
    205 bool CodeGenPrepare::runOnFunction(Function &F) {
    206   if (skipOptnoneFunction(F))
    207     return false;
    208 
    209   DL = &F.getParent()->getDataLayout();
    210 
    211   bool EverMadeChange = false;
    212   // Clear per function information.
    213   InsertedInsts.clear();
    214   PromotedInsts.clear();
    215 
    216   ModifiedDT = false;
    217   if (TM)
    218     TLI = TM->getSubtargetImpl(F)->getTargetLowering();
    219   TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
    220   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
    221   OptSize = F.optForSize();
    222 
    223   /// This optimization identifies DIV instructions that can be
    224   /// profitably bypassed and carried out with a shorter, faster divide.
    225   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
    226     const DenseMap<unsigned int, unsigned int> &BypassWidths =
    227        TLI->getBypassSlowDivWidths();
    228     for (Function::iterator I = F.begin(); I != F.end(); I++)
    229       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
    230   }
    231 
    232   // Eliminate blocks that contain only PHI nodes and an
    233   // unconditional branch.
    234   EverMadeChange |= eliminateMostlyEmptyBlocks(F);
    235 
    236   // llvm.dbg.value is far away from the value then iSel may not be able
    237   // handle it properly. iSel will drop llvm.dbg.value if it can not
    238   // find a node corresponding to the value.
    239   EverMadeChange |= placeDbgValues(F);
    240 
    241   // If there is a mask, compare against zero, and branch that can be combined
    242   // into a single target instruction, push the mask and compare into branch
    243   // users. Do this before OptimizeBlock -> OptimizeInst ->
    244   // OptimizeCmpExpression, which perturbs the pattern being searched for.
    245   if (!DisableBranchOpts) {
    246     EverMadeChange |= sinkAndCmp(F);
    247     EverMadeChange |= splitBranchCondition(F);
    248   }
    249 
    250   bool MadeChange = true;
    251   while (MadeChange) {
    252     MadeChange = false;
    253     for (Function::iterator I = F.begin(); I != F.end(); ) {
    254       BasicBlock *BB = &*I++;
    255       bool ModifiedDTOnIteration = false;
    256       MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
    257 
    258       // Restart BB iteration if the dominator tree of the Function was changed
    259       if (ModifiedDTOnIteration)
    260         break;
    261     }
    262     EverMadeChange |= MadeChange;
    263   }
    264 
    265   SunkAddrs.clear();
    266 
    267   if (!DisableBranchOpts) {
    268     MadeChange = false;
    269     SmallPtrSet<BasicBlock*, 8> WorkList;
    270     for (BasicBlock &BB : F) {
    271       SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
    272       MadeChange |= ConstantFoldTerminator(&BB, true);
    273       if (!MadeChange) continue;
    274 
    275       for (SmallVectorImpl<BasicBlock*>::iterator
    276              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
    277         if (pred_begin(*II) == pred_end(*II))
    278           WorkList.insert(*II);
    279     }
    280 
    281     // Delete the dead blocks and any of their dead successors.
    282     MadeChange |= !WorkList.empty();
    283     while (!WorkList.empty()) {
    284       BasicBlock *BB = *WorkList.begin();
    285       WorkList.erase(BB);
    286       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
    287 
    288       DeleteDeadBlock(BB);
    289 
    290       for (SmallVectorImpl<BasicBlock*>::iterator
    291              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
    292         if (pred_begin(*II) == pred_end(*II))
    293           WorkList.insert(*II);
    294     }
    295 
    296     // Merge pairs of basic blocks with unconditional branches, connected by
    297     // a single edge.
    298     if (EverMadeChange || MadeChange)
    299       MadeChange |= eliminateFallThrough(F);
    300 
    301     EverMadeChange |= MadeChange;
    302   }
    303 
    304   if (!DisableGCOpts) {
    305     SmallVector<Instruction *, 2> Statepoints;
    306     for (BasicBlock &BB : F)
    307       for (Instruction &I : BB)
    308         if (isStatepoint(I))
    309           Statepoints.push_back(&I);
    310     for (auto &I : Statepoints)
    311       EverMadeChange |= simplifyOffsetableRelocate(*I);
    312   }
    313 
    314   return EverMadeChange;
    315 }
    316 
    317 /// Merge basic blocks which are connected by a single edge, where one of the
    318 /// basic blocks has a single successor pointing to the other basic block,
    319 /// which has a single predecessor.
    320 bool CodeGenPrepare::eliminateFallThrough(Function &F) {
    321   bool Changed = false;
    322   // Scan all of the blocks in the function, except for the entry block.
    323   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
    324     BasicBlock *BB = &*I++;
    325     // If the destination block has a single pred, then this is a trivial
    326     // edge, just collapse it.
    327     BasicBlock *SinglePred = BB->getSinglePredecessor();
    328 
    329     // Don't merge if BB's address is taken.
    330     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
    331 
    332     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
    333     if (Term && !Term->isConditional()) {
    334       Changed = true;
    335       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
    336       // Remember if SinglePred was the entry block of the function.
    337       // If so, we will need to move BB back to the entry position.
    338       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
    339       MergeBasicBlockIntoOnlyPred(BB, nullptr);
    340 
    341       if (isEntry && BB != &BB->getParent()->getEntryBlock())
    342         BB->moveBefore(&BB->getParent()->getEntryBlock());
    343 
    344       // We have erased a block. Update the iterator.
    345       I = BB->getIterator();
    346     }
    347   }
    348   return Changed;
    349 }
    350 
    351 /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
    352 /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
    353 /// edges in ways that are non-optimal for isel. Start by eliminating these
    354 /// blocks so we can split them the way we want them.
    355 bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
    356   bool MadeChange = false;
    357   // Note that this intentionally skips the entry block.
    358   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
    359     BasicBlock *BB = &*I++;
    360 
    361     // If this block doesn't end with an uncond branch, ignore it.
    362     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
    363     if (!BI || !BI->isUnconditional())
    364       continue;
    365 
    366     // If the instruction before the branch (skipping debug info) isn't a phi
    367     // node, then other stuff is happening here.
    368     BasicBlock::iterator BBI = BI->getIterator();
    369     if (BBI != BB->begin()) {
    370       --BBI;
    371       while (isa<DbgInfoIntrinsic>(BBI)) {
    372         if (BBI == BB->begin())
    373           break;
    374         --BBI;
    375       }
    376       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
    377         continue;
    378     }
    379 
    380     // Do not break infinite loops.
    381     BasicBlock *DestBB = BI->getSuccessor(0);
    382     if (DestBB == BB)
    383       continue;
    384 
    385     if (!canMergeBlocks(BB, DestBB))
    386       continue;
    387 
    388     eliminateMostlyEmptyBlock(BB);
    389     MadeChange = true;
    390   }
    391   return MadeChange;
    392 }
    393 
    394 /// Return true if we can merge BB into DestBB if there is a single
    395 /// unconditional branch between them, and BB contains no other non-phi
    396 /// instructions.
    397 bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
    398                                     const BasicBlock *DestBB) const {
    399   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
    400   // the successor.  If there are more complex condition (e.g. preheaders),
    401   // don't mess around with them.
    402   BasicBlock::const_iterator BBI = BB->begin();
    403   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
    404     for (const User *U : PN->users()) {
    405       const Instruction *UI = cast<Instruction>(U);
    406       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
    407         return false;
    408       // If User is inside DestBB block and it is a PHINode then check
    409       // incoming value. If incoming value is not from BB then this is
    410       // a complex condition (e.g. preheaders) we want to avoid here.
    411       if (UI->getParent() == DestBB) {
    412         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
    413           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
    414             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
    415             if (Insn && Insn->getParent() == BB &&
    416                 Insn->getParent() != UPN->getIncomingBlock(I))
    417               return false;
    418           }
    419       }
    420     }
    421   }
    422 
    423   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
    424   // and DestBB may have conflicting incoming values for the block.  If so, we
    425   // can't merge the block.
    426   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
    427   if (!DestBBPN) return true;  // no conflict.
    428 
    429   // Collect the preds of BB.
    430   SmallPtrSet<const BasicBlock*, 16> BBPreds;
    431   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
    432     // It is faster to get preds from a PHI than with pred_iterator.
    433     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
    434       BBPreds.insert(BBPN->getIncomingBlock(i));
    435   } else {
    436     BBPreds.insert(pred_begin(BB), pred_end(BB));
    437   }
    438 
    439   // Walk the preds of DestBB.
    440   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
    441     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
    442     if (BBPreds.count(Pred)) {   // Common predecessor?
    443       BBI = DestBB->begin();
    444       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
    445         const Value *V1 = PN->getIncomingValueForBlock(Pred);
    446         const Value *V2 = PN->getIncomingValueForBlock(BB);
    447 
    448         // If V2 is a phi node in BB, look up what the mapped value will be.
    449         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
    450           if (V2PN->getParent() == BB)
    451             V2 = V2PN->getIncomingValueForBlock(Pred);
    452 
    453         // If there is a conflict, bail out.
    454         if (V1 != V2) return false;
    455       }
    456     }
    457   }
    458 
    459   return true;
    460 }
    461 
    462 
    463 /// Eliminate a basic block that has only phi's and an unconditional branch in
    464 /// it.
    465 void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
    466   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
    467   BasicBlock *DestBB = BI->getSuccessor(0);
    468 
    469   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
    470 
    471   // If the destination block has a single pred, then this is a trivial edge,
    472   // just collapse it.
    473   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
    474     if (SinglePred != DestBB) {
    475       // Remember if SinglePred was the entry block of the function.  If so, we
    476       // will need to move BB back to the entry position.
    477       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
    478       MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
    479 
    480       if (isEntry && BB != &BB->getParent()->getEntryBlock())
    481         BB->moveBefore(&BB->getParent()->getEntryBlock());
    482 
    483       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
    484       return;
    485     }
    486   }
    487 
    488   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
    489   // to handle the new incoming edges it is about to have.
    490   PHINode *PN;
    491   for (BasicBlock::iterator BBI = DestBB->begin();
    492        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
    493     // Remove the incoming value for BB, and remember it.
    494     Value *InVal = PN->removeIncomingValue(BB, false);
    495 
    496     // Two options: either the InVal is a phi node defined in BB or it is some
    497     // value that dominates BB.
    498     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
    499     if (InValPhi && InValPhi->getParent() == BB) {
    500       // Add all of the input values of the input PHI as inputs of this phi.
    501       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
    502         PN->addIncoming(InValPhi->getIncomingValue(i),
    503                         InValPhi->getIncomingBlock(i));
    504     } else {
    505       // Otherwise, add one instance of the dominating value for each edge that
    506       // we will be adding.
    507       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
    508         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
    509           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
    510       } else {
    511         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
    512           PN->addIncoming(InVal, *PI);
    513       }
    514     }
    515   }
    516 
    517   // The PHIs are now updated, change everything that refers to BB to use
    518   // DestBB and remove BB.
    519   BB->replaceAllUsesWith(DestBB);
    520   BB->eraseFromParent();
    521   ++NumBlocksElim;
    522 
    523   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
    524 }
    525 
    526 // Computes a map of base pointer relocation instructions to corresponding
    527 // derived pointer relocation instructions given a vector of all relocate calls
    528 static void computeBaseDerivedRelocateMap(
    529     const SmallVectorImpl<User *> &AllRelocateCalls,
    530     DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
    531         RelocateInstMap) {
    532   // Collect information in two maps: one primarily for locating the base object
    533   // while filling the second map; the second map is the final structure holding
    534   // a mapping between Base and corresponding Derived relocate calls
    535   DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
    536   for (auto &U : AllRelocateCalls) {
    537     GCRelocateOperands ThisRelocate(U);
    538     IntrinsicInst *I = cast<IntrinsicInst>(U);
    539     auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
    540                             ThisRelocate.getDerivedPtrIndex());
    541     RelocateIdxMap.insert(std::make_pair(K, I));
    542   }
    543   for (auto &Item : RelocateIdxMap) {
    544     std::pair<unsigned, unsigned> Key = Item.first;
    545     if (Key.first == Key.second)
    546       // Base relocation: nothing to insert
    547       continue;
    548 
    549     IntrinsicInst *I = Item.second;
    550     auto BaseKey = std::make_pair(Key.first, Key.first);
    551 
    552     // We're iterating over RelocateIdxMap so we cannot modify it.
    553     auto MaybeBase = RelocateIdxMap.find(BaseKey);
    554     if (MaybeBase == RelocateIdxMap.end())
    555       // TODO: We might want to insert a new base object relocate and gep off
    556       // that, if there are enough derived object relocates.
    557       continue;
    558 
    559     RelocateInstMap[MaybeBase->second].push_back(I);
    560   }
    561 }
    562 
    563 // Accepts a GEP and extracts the operands into a vector provided they're all
    564 // small integer constants
    565 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
    566                                           SmallVectorImpl<Value *> &OffsetV) {
    567   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
    568     // Only accept small constant integer operands
    569     auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
    570     if (!Op || Op->getZExtValue() > 20)
    571       return false;
    572   }
    573 
    574   for (unsigned i = 1; i < GEP->getNumOperands(); i++)
    575     OffsetV.push_back(GEP->getOperand(i));
    576   return true;
    577 }
    578 
    579 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
    580 // replace, computes a replacement, and affects it.
    581 static bool
    582 simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
    583                           const SmallVectorImpl<IntrinsicInst *> &Targets) {
    584   bool MadeChange = false;
    585   for (auto &ToReplace : Targets) {
    586     GCRelocateOperands MasterRelocate(RelocatedBase);
    587     GCRelocateOperands ThisRelocate(ToReplace);
    588 
    589     assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
    590            "Not relocating a derived object of the original base object");
    591     if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
    592       // A duplicate relocate call. TODO: coalesce duplicates.
    593       continue;
    594     }
    595 
    596     if (RelocatedBase->getParent() != ToReplace->getParent()) {
    597       // Base and derived relocates are in different basic blocks.
    598       // In this case transform is only valid when base dominates derived
    599       // relocate. However it would be too expensive to check dominance
    600       // for each such relocate, so we skip the whole transformation.
    601       continue;
    602     }
    603 
    604     Value *Base = ThisRelocate.getBasePtr();
    605     auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
    606     if (!Derived || Derived->getPointerOperand() != Base)
    607       continue;
    608 
    609     SmallVector<Value *, 2> OffsetV;
    610     if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
    611       continue;
    612 
    613     // Create a Builder and replace the target callsite with a gep
    614     assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
    615 
    616     // Insert after RelocatedBase
    617     IRBuilder<> Builder(RelocatedBase->getNextNode());
    618     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
    619 
    620     // If gc_relocate does not match the actual type, cast it to the right type.
    621     // In theory, there must be a bitcast after gc_relocate if the type does not
    622     // match, and we should reuse it to get the derived pointer. But it could be
    623     // cases like this:
    624     // bb1:
    625     //  ...
    626     //  %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
    627     //  br label %merge
    628     //
    629     // bb2:
    630     //  ...
    631     //  %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
    632     //  br label %merge
    633     //
    634     // merge:
    635     //  %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
    636     //  %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
    637     //
    638     // In this case, we can not find the bitcast any more. So we insert a new bitcast
    639     // no matter there is already one or not. In this way, we can handle all cases, and
    640     // the extra bitcast should be optimized away in later passes.
    641     Value *ActualRelocatedBase = RelocatedBase;
    642     if (RelocatedBase->getType() != Base->getType()) {
    643       ActualRelocatedBase =
    644           Builder.CreateBitCast(RelocatedBase, Base->getType());
    645     }
    646     Value *Replacement = Builder.CreateGEP(
    647         Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
    648     Replacement->takeName(ToReplace);
    649     // If the newly generated derived pointer's type does not match the original derived
    650     // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
    651     Value *ActualReplacement = Replacement;
    652     if (Replacement->getType() != ToReplace->getType()) {
    653       ActualReplacement =
    654           Builder.CreateBitCast(Replacement, ToReplace->getType());
    655     }
    656     ToReplace->replaceAllUsesWith(ActualReplacement);
    657     ToReplace->eraseFromParent();
    658 
    659     MadeChange = true;
    660   }
    661   return MadeChange;
    662 }
    663 
    664 // Turns this:
    665 //
    666 // %base = ...
    667 // %ptr = gep %base + 15
    668 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
    669 // %base' = relocate(%tok, i32 4, i32 4)
    670 // %ptr' = relocate(%tok, i32 4, i32 5)
    671 // %val = load %ptr'
    672 //
    673 // into this:
    674 //
    675 // %base = ...
    676 // %ptr = gep %base + 15
    677 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
    678 // %base' = gc.relocate(%tok, i32 4, i32 4)
    679 // %ptr' = gep %base' + 15
    680 // %val = load %ptr'
    681 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
    682   bool MadeChange = false;
    683   SmallVector<User *, 2> AllRelocateCalls;
    684 
    685   for (auto *U : I.users())
    686     if (isGCRelocate(dyn_cast<Instruction>(U)))
    687       // Collect all the relocate calls associated with a statepoint
    688       AllRelocateCalls.push_back(U);
    689 
    690   // We need atleast one base pointer relocation + one derived pointer
    691   // relocation to mangle
    692   if (AllRelocateCalls.size() < 2)
    693     return false;
    694 
    695   // RelocateInstMap is a mapping from the base relocate instruction to the
    696   // corresponding derived relocate instructions
    697   DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
    698   computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
    699   if (RelocateInstMap.empty())
    700     return false;
    701 
    702   for (auto &Item : RelocateInstMap)
    703     // Item.first is the RelocatedBase to offset against
    704     // Item.second is the vector of Targets to replace
    705     MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
    706   return MadeChange;
    707 }
    708 
    709 /// SinkCast - Sink the specified cast instruction into its user blocks
    710 static bool SinkCast(CastInst *CI) {
    711   BasicBlock *DefBB = CI->getParent();
    712 
    713   /// InsertedCasts - Only insert a cast in each block once.
    714   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
    715 
    716   bool MadeChange = false;
    717   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
    718        UI != E; ) {
    719     Use &TheUse = UI.getUse();
    720     Instruction *User = cast<Instruction>(*UI);
    721 
    722     // Figure out which BB this cast is used in.  For PHI's this is the
    723     // appropriate predecessor block.
    724     BasicBlock *UserBB = User->getParent();
    725     if (PHINode *PN = dyn_cast<PHINode>(User)) {
    726       UserBB = PN->getIncomingBlock(TheUse);
    727     }
    728 
    729     // Preincrement use iterator so we don't invalidate it.
    730     ++UI;
    731 
    732     // If the block selected to receive the cast is an EH pad that does not
    733     // allow non-PHI instructions before the terminator, we can't sink the
    734     // cast.
    735     if (UserBB->getTerminator()->isEHPad())
    736       continue;
    737 
    738     // If this user is in the same block as the cast, don't change the cast.
    739     if (UserBB == DefBB) continue;
    740 
    741     // If we have already inserted a cast into this block, use it.
    742     CastInst *&InsertedCast = InsertedCasts[UserBB];
    743 
    744     if (!InsertedCast) {
    745       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
    746       assert(InsertPt != UserBB->end());
    747       InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
    748                                       CI->getType(), "", &*InsertPt);
    749     }
    750 
    751     // Replace a use of the cast with a use of the new cast.
    752     TheUse = InsertedCast;
    753     MadeChange = true;
    754     ++NumCastUses;
    755   }
    756 
    757   // If we removed all uses, nuke the cast.
    758   if (CI->use_empty()) {
    759     CI->eraseFromParent();
    760     MadeChange = true;
    761   }
    762 
    763   return MadeChange;
    764 }
    765 
    766 /// If the specified cast instruction is a noop copy (e.g. it's casting from
    767 /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
    768 /// reduce the number of virtual registers that must be created and coalesced.
    769 ///
    770 /// Return true if any changes are made.
    771 ///
    772 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
    773                                        const DataLayout &DL) {
    774   // If this is a noop copy,
    775   EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
    776   EVT DstVT = TLI.getValueType(DL, CI->getType());
    777 
    778   // This is an fp<->int conversion?
    779   if (SrcVT.isInteger() != DstVT.isInteger())
    780     return false;
    781 
    782   // If this is an extension, it will be a zero or sign extension, which
    783   // isn't a noop.
    784   if (SrcVT.bitsLT(DstVT)) return false;
    785 
    786   // If these values will be promoted, find out what they will be promoted
    787   // to.  This helps us consider truncates on PPC as noop copies when they
    788   // are.
    789   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
    790       TargetLowering::TypePromoteInteger)
    791     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
    792   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
    793       TargetLowering::TypePromoteInteger)
    794     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
    795 
    796   // If, after promotion, these are the same types, this is a noop copy.
    797   if (SrcVT != DstVT)
    798     return false;
    799 
    800   return SinkCast(CI);
    801 }
    802 
    803 /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
    804 /// possible.
    805 ///
    806 /// Return true if any changes were made.
    807 static bool CombineUAddWithOverflow(CmpInst *CI) {
    808   Value *A, *B;
    809   Instruction *AddI;
    810   if (!match(CI,
    811              m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
    812     return false;
    813 
    814   Type *Ty = AddI->getType();
    815   if (!isa<IntegerType>(Ty))
    816     return false;
    817 
    818   // We don't want to move around uses of condition values this late, so we we
    819   // check if it is legal to create the call to the intrinsic in the basic
    820   // block containing the icmp:
    821 
    822   if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
    823     return false;
    824 
    825 #ifndef NDEBUG
    826   // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
    827   // for now:
    828   if (AddI->hasOneUse())
    829     assert(*AddI->user_begin() == CI && "expected!");
    830 #endif
    831 
    832   Module *M = CI->getModule();
    833   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
    834 
    835   auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
    836 
    837   auto *UAddWithOverflow =
    838       CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
    839   auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
    840   auto *Overflow =
    841       ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
    842 
    843   CI->replaceAllUsesWith(Overflow);
    844   AddI->replaceAllUsesWith(UAdd);
    845   CI->eraseFromParent();
    846   AddI->eraseFromParent();
    847   return true;
    848 }
    849 
    850 /// Sink the given CmpInst into user blocks to reduce the number of virtual
    851 /// registers that must be created and coalesced. This is a clear win except on
    852 /// targets with multiple condition code registers (PowerPC), where it might
    853 /// lose; some adjustment may be wanted there.
    854 ///
    855 /// Return true if any changes are made.
    856 static bool SinkCmpExpression(CmpInst *CI) {
    857   BasicBlock *DefBB = CI->getParent();
    858 
    859   /// Only insert a cmp in each block once.
    860   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
    861 
    862   bool MadeChange = false;
    863   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
    864        UI != E; ) {
    865     Use &TheUse = UI.getUse();
    866     Instruction *User = cast<Instruction>(*UI);
    867 
    868     // Preincrement use iterator so we don't invalidate it.
    869     ++UI;
    870 
    871     // Don't bother for PHI nodes.
    872     if (isa<PHINode>(User))
    873       continue;
    874 
    875     // Figure out which BB this cmp is used in.
    876     BasicBlock *UserBB = User->getParent();
    877 
    878     // If this user is in the same block as the cmp, don't change the cmp.
    879     if (UserBB == DefBB) continue;
    880 
    881     // If we have already inserted a cmp into this block, use it.
    882     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
    883 
    884     if (!InsertedCmp) {
    885       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
    886       assert(InsertPt != UserBB->end());
    887       InsertedCmp =
    888           CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
    889                           CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
    890     }
    891 
    892     // Replace a use of the cmp with a use of the new cmp.
    893     TheUse = InsertedCmp;
    894     MadeChange = true;
    895     ++NumCmpUses;
    896   }
    897 
    898   // If we removed all uses, nuke the cmp.
    899   if (CI->use_empty()) {
    900     CI->eraseFromParent();
    901     MadeChange = true;
    902   }
    903 
    904   return MadeChange;
    905 }
    906 
    907 static bool OptimizeCmpExpression(CmpInst *CI) {
    908   if (SinkCmpExpression(CI))
    909     return true;
    910 
    911   if (CombineUAddWithOverflow(CI))
    912     return true;
    913 
    914   return false;
    915 }
    916 
    917 /// Check if the candidates could be combined with a shift instruction, which
    918 /// includes:
    919 /// 1. Truncate instruction
    920 /// 2. And instruction and the imm is a mask of the low bits:
    921 /// imm & (imm+1) == 0
    922 static bool isExtractBitsCandidateUse(Instruction *User) {
    923   if (!isa<TruncInst>(User)) {
    924     if (User->getOpcode() != Instruction::And ||
    925         !isa<ConstantInt>(User->getOperand(1)))
    926       return false;
    927 
    928     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
    929 
    930     if ((Cimm & (Cimm + 1)).getBoolValue())
    931       return false;
    932   }
    933   return true;
    934 }
    935 
    936 /// Sink both shift and truncate instruction to the use of truncate's BB.
    937 static bool
    938 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
    939                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
    940                      const TargetLowering &TLI, const DataLayout &DL) {
    941   BasicBlock *UserBB = User->getParent();
    942   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
    943   TruncInst *TruncI = dyn_cast<TruncInst>(User);
    944   bool MadeChange = false;
    945 
    946   for (Value::user_iterator TruncUI = TruncI->user_begin(),
    947                             TruncE = TruncI->user_end();
    948        TruncUI != TruncE;) {
    949 
    950     Use &TruncTheUse = TruncUI.getUse();
    951     Instruction *TruncUser = cast<Instruction>(*TruncUI);
    952     // Preincrement use iterator so we don't invalidate it.
    953 
    954     ++TruncUI;
    955 
    956     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
    957     if (!ISDOpcode)
    958       continue;
    959 
    960     // If the use is actually a legal node, there will not be an
    961     // implicit truncate.
    962     // FIXME: always querying the result type is just an
    963     // approximation; some nodes' legality is determined by the
    964     // operand or other means. There's no good way to find out though.
    965     if (TLI.isOperationLegalOrCustom(
    966             ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
    967       continue;
    968 
    969     // Don't bother for PHI nodes.
    970     if (isa<PHINode>(TruncUser))
    971       continue;
    972 
    973     BasicBlock *TruncUserBB = TruncUser->getParent();
    974 
    975     if (UserBB == TruncUserBB)
    976       continue;
    977 
    978     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
    979     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
    980 
    981     if (!InsertedShift && !InsertedTrunc) {
    982       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
    983       assert(InsertPt != TruncUserBB->end());
    984       // Sink the shift
    985       if (ShiftI->getOpcode() == Instruction::AShr)
    986         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
    987                                                    "", &*InsertPt);
    988       else
    989         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
    990                                                    "", &*InsertPt);
    991 
    992       // Sink the trunc
    993       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
    994       TruncInsertPt++;
    995       assert(TruncInsertPt != TruncUserBB->end());
    996 
    997       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
    998                                        TruncI->getType(), "", &*TruncInsertPt);
    999 
   1000       MadeChange = true;
   1001 
   1002       TruncTheUse = InsertedTrunc;
   1003     }
   1004   }
   1005   return MadeChange;
   1006 }
   1007 
   1008 /// Sink the shift *right* instruction into user blocks if the uses could
   1009 /// potentially be combined with this shift instruction and generate BitExtract
   1010 /// instruction. It will only be applied if the architecture supports BitExtract
   1011 /// instruction. Here is an example:
   1012 /// BB1:
   1013 ///   %x.extract.shift = lshr i64 %arg1, 32
   1014 /// BB2:
   1015 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
   1016 /// ==>
   1017 ///
   1018 /// BB2:
   1019 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
   1020 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
   1021 ///
   1022 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
   1023 /// instruction.
   1024 /// Return true if any changes are made.
   1025 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
   1026                                 const TargetLowering &TLI,
   1027                                 const DataLayout &DL) {
   1028   BasicBlock *DefBB = ShiftI->getParent();
   1029 
   1030   /// Only insert instructions in each block once.
   1031   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
   1032 
   1033   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
   1034 
   1035   bool MadeChange = false;
   1036   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
   1037        UI != E;) {
   1038     Use &TheUse = UI.getUse();
   1039     Instruction *User = cast<Instruction>(*UI);
   1040     // Preincrement use iterator so we don't invalidate it.
   1041     ++UI;
   1042 
   1043     // Don't bother for PHI nodes.
   1044     if (isa<PHINode>(User))
   1045       continue;
   1046 
   1047     if (!isExtractBitsCandidateUse(User))
   1048       continue;
   1049 
   1050     BasicBlock *UserBB = User->getParent();
   1051 
   1052     if (UserBB == DefBB) {
   1053       // If the shift and truncate instruction are in the same BB. The use of
   1054       // the truncate(TruncUse) may still introduce another truncate if not
   1055       // legal. In this case, we would like to sink both shift and truncate
   1056       // instruction to the BB of TruncUse.
   1057       // for example:
   1058       // BB1:
   1059       // i64 shift.result = lshr i64 opnd, imm
   1060       // trunc.result = trunc shift.result to i16
   1061       //
   1062       // BB2:
   1063       //   ----> We will have an implicit truncate here if the architecture does
   1064       //   not have i16 compare.
   1065       // cmp i16 trunc.result, opnd2
   1066       //
   1067       if (isa<TruncInst>(User) && shiftIsLegal
   1068           // If the type of the truncate is legal, no trucate will be
   1069           // introduced in other basic blocks.
   1070           &&
   1071           (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
   1072         MadeChange =
   1073             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
   1074 
   1075       continue;
   1076     }
   1077     // If we have already inserted a shift into this block, use it.
   1078     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
   1079 
   1080     if (!InsertedShift) {
   1081       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
   1082       assert(InsertPt != UserBB->end());
   1083 
   1084       if (ShiftI->getOpcode() == Instruction::AShr)
   1085         InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
   1086                                                    "", &*InsertPt);
   1087       else
   1088         InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
   1089                                                    "", &*InsertPt);
   1090 
   1091       MadeChange = true;
   1092     }
   1093 
   1094     // Replace a use of the shift with a use of the new shift.
   1095     TheUse = InsertedShift;
   1096   }
   1097 
   1098   // If we removed all uses, nuke the shift.
   1099   if (ShiftI->use_empty())
   1100     ShiftI->eraseFromParent();
   1101 
   1102   return MadeChange;
   1103 }
   1104 
   1105 // Translate a masked load intrinsic like
   1106 // <16 x i32 > @llvm.masked.load( <16 x i32>* %addr, i32 align,
   1107 //                               <16 x i1> %mask, <16 x i32> %passthru)
   1108 // to a chain of basic blocks, with loading element one-by-one if
   1109 // the appropriate mask bit is set
   1110 //
   1111 //  %1 = bitcast i8* %addr to i32*
   1112 //  %2 = extractelement <16 x i1> %mask, i32 0
   1113 //  %3 = icmp eq i1 %2, true
   1114 //  br i1 %3, label %cond.load, label %else
   1115 //
   1116 //cond.load:                                        ; preds = %0
   1117 //  %4 = getelementptr i32* %1, i32 0
   1118 //  %5 = load i32* %4
   1119 //  %6 = insertelement <16 x i32> undef, i32 %5, i32 0
   1120 //  br label %else
   1121 //
   1122 //else:                                             ; preds = %0, %cond.load
   1123 //  %res.phi.else = phi <16 x i32> [ %6, %cond.load ], [ undef, %0 ]
   1124 //  %7 = extractelement <16 x i1> %mask, i32 1
   1125 //  %8 = icmp eq i1 %7, true
   1126 //  br i1 %8, label %cond.load1, label %else2
   1127 //
   1128 //cond.load1:                                       ; preds = %else
   1129 //  %9 = getelementptr i32* %1, i32 1
   1130 //  %10 = load i32* %9
   1131 //  %11 = insertelement <16 x i32> %res.phi.else, i32 %10, i32 1
   1132 //  br label %else2
   1133 //
   1134 //else2:                                            ; preds = %else, %cond.load1
   1135 //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
   1136 //  %12 = extractelement <16 x i1> %mask, i32 2
   1137 //  %13 = icmp eq i1 %12, true
   1138 //  br i1 %13, label %cond.load4, label %else5
   1139 //
   1140 static void ScalarizeMaskedLoad(CallInst *CI) {
   1141   Value *Ptr  = CI->getArgOperand(0);
   1142   Value *Alignment = CI->getArgOperand(1);
   1143   Value *Mask = CI->getArgOperand(2);
   1144   Value *Src0 = CI->getArgOperand(3);
   1145 
   1146   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
   1147   VectorType *VecType = dyn_cast<VectorType>(CI->getType());
   1148   assert(VecType && "Unexpected return type of masked load intrinsic");
   1149 
   1150   Type *EltTy = CI->getType()->getVectorElementType();
   1151 
   1152   IRBuilder<> Builder(CI->getContext());
   1153   Instruction *InsertPt = CI;
   1154   BasicBlock *IfBlock = CI->getParent();
   1155   BasicBlock *CondBlock = nullptr;
   1156   BasicBlock *PrevIfBlock = CI->getParent();
   1157 
   1158   Builder.SetInsertPoint(InsertPt);
   1159   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
   1160 
   1161   // Short-cut if the mask is all-true.
   1162   bool IsAllOnesMask = isa<Constant>(Mask) &&
   1163     cast<Constant>(Mask)->isAllOnesValue();
   1164 
   1165   if (IsAllOnesMask) {
   1166     Value *NewI = Builder.CreateAlignedLoad(Ptr, AlignVal);
   1167     CI->replaceAllUsesWith(NewI);
   1168     CI->eraseFromParent();
   1169     return;
   1170   }
   1171 
   1172   // Adjust alignment for the scalar instruction.
   1173   AlignVal = std::min(AlignVal, VecType->getScalarSizeInBits()/8);
   1174   // Bitcast %addr fron i8* to EltTy*
   1175   Type *NewPtrType =
   1176     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
   1177   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
   1178   unsigned VectorWidth = VecType->getNumElements();
   1179 
   1180   Value *UndefVal = UndefValue::get(VecType);
   1181 
   1182   // The result vector
   1183   Value *VResult = UndefVal;
   1184 
   1185   if (isa<ConstantVector>(Mask)) {
   1186     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
   1187       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
   1188           continue;
   1189       Value *Gep =
   1190           Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
   1191       LoadInst* Load = Builder.CreateAlignedLoad(Gep, AlignVal);
   1192       VResult = Builder.CreateInsertElement(VResult, Load,
   1193                                             Builder.getInt32(Idx));
   1194     }
   1195     Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
   1196     CI->replaceAllUsesWith(NewI);
   1197     CI->eraseFromParent();
   1198     return;
   1199   }
   1200 
   1201   PHINode *Phi = nullptr;
   1202   Value *PrevPhi = UndefVal;
   1203 
   1204   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
   1205 
   1206     // Fill the "else" block, created in the previous iteration
   1207     //
   1208     //  %res.phi.else3 = phi <16 x i32> [ %11, %cond.load1 ], [ %res.phi.else, %else ]
   1209     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
   1210     //  %to_load = icmp eq i1 %mask_1, true
   1211     //  br i1 %to_load, label %cond.load, label %else
   1212     //
   1213     if (Idx > 0) {
   1214       Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
   1215       Phi->addIncoming(VResult, CondBlock);
   1216       Phi->addIncoming(PrevPhi, PrevIfBlock);
   1217       PrevPhi = Phi;
   1218       VResult = Phi;
   1219     }
   1220 
   1221     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
   1222     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
   1223                                     ConstantInt::get(Predicate->getType(), 1));
   1224 
   1225     // Create "cond" block
   1226     //
   1227     //  %EltAddr = getelementptr i32* %1, i32 0
   1228     //  %Elt = load i32* %EltAddr
   1229     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
   1230     //
   1231     CondBlock = IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.load");
   1232     Builder.SetInsertPoint(InsertPt);
   1233 
   1234     Value *Gep =
   1235         Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
   1236     LoadInst *Load = Builder.CreateAlignedLoad(Gep, AlignVal);
   1237     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx));
   1238 
   1239     // Create "else" block, fill it in the next iteration
   1240     BasicBlock *NewIfBlock =
   1241         CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
   1242     Builder.SetInsertPoint(InsertPt);
   1243     Instruction *OldBr = IfBlock->getTerminator();
   1244     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
   1245     OldBr->eraseFromParent();
   1246     PrevIfBlock = IfBlock;
   1247     IfBlock = NewIfBlock;
   1248   }
   1249 
   1250   Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
   1251   Phi->addIncoming(VResult, CondBlock);
   1252   Phi->addIncoming(PrevPhi, PrevIfBlock);
   1253   Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
   1254   CI->replaceAllUsesWith(NewI);
   1255   CI->eraseFromParent();
   1256 }
   1257 
   1258 // Translate a masked store intrinsic, like
   1259 // void @llvm.masked.store(<16 x i32> %src, <16 x i32>* %addr, i32 align,
   1260 //                               <16 x i1> %mask)
   1261 // to a chain of basic blocks, that stores element one-by-one if
   1262 // the appropriate mask bit is set
   1263 //
   1264 //   %1 = bitcast i8* %addr to i32*
   1265 //   %2 = extractelement <16 x i1> %mask, i32 0
   1266 //   %3 = icmp eq i1 %2, true
   1267 //   br i1 %3, label %cond.store, label %else
   1268 //
   1269 // cond.store:                                       ; preds = %0
   1270 //   %4 = extractelement <16 x i32> %val, i32 0
   1271 //   %5 = getelementptr i32* %1, i32 0
   1272 //   store i32 %4, i32* %5
   1273 //   br label %else
   1274 //
   1275 // else:                                             ; preds = %0, %cond.store
   1276 //   %6 = extractelement <16 x i1> %mask, i32 1
   1277 //   %7 = icmp eq i1 %6, true
   1278 //   br i1 %7, label %cond.store1, label %else2
   1279 //
   1280 // cond.store1:                                      ; preds = %else
   1281 //   %8 = extractelement <16 x i32> %val, i32 1
   1282 //   %9 = getelementptr i32* %1, i32 1
   1283 //   store i32 %8, i32* %9
   1284 //   br label %else2
   1285 //   . . .
   1286 static void ScalarizeMaskedStore(CallInst *CI) {
   1287   Value *Src = CI->getArgOperand(0);
   1288   Value *Ptr  = CI->getArgOperand(1);
   1289   Value *Alignment = CI->getArgOperand(2);
   1290   Value *Mask = CI->getArgOperand(3);
   1291 
   1292   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
   1293   VectorType *VecType = dyn_cast<VectorType>(Src->getType());
   1294   assert(VecType && "Unexpected data type in masked store intrinsic");
   1295 
   1296   Type *EltTy = VecType->getElementType();
   1297 
   1298   IRBuilder<> Builder(CI->getContext());
   1299   Instruction *InsertPt = CI;
   1300   BasicBlock *IfBlock = CI->getParent();
   1301   Builder.SetInsertPoint(InsertPt);
   1302   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
   1303 
   1304   // Short-cut if the mask is all-true.
   1305   bool IsAllOnesMask = isa<Constant>(Mask) &&
   1306     cast<Constant>(Mask)->isAllOnesValue();
   1307 
   1308   if (IsAllOnesMask) {
   1309     Builder.CreateAlignedStore(Src, Ptr, AlignVal);
   1310     CI->eraseFromParent();
   1311     return;
   1312   }
   1313 
   1314   // Adjust alignment for the scalar instruction.
   1315   AlignVal = std::max(AlignVal, VecType->getScalarSizeInBits()/8);
   1316   // Bitcast %addr fron i8* to EltTy*
   1317   Type *NewPtrType =
   1318     EltTy->getPointerTo(cast<PointerType>(Ptr->getType())->getAddressSpace());
   1319   Value *FirstEltPtr = Builder.CreateBitCast(Ptr, NewPtrType);
   1320   unsigned VectorWidth = VecType->getNumElements();
   1321 
   1322   if (isa<ConstantVector>(Mask)) {
   1323     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
   1324       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
   1325           continue;
   1326       Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
   1327       Value *Gep =
   1328           Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
   1329       Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
   1330     }
   1331     CI->eraseFromParent();
   1332     return;
   1333   }
   1334 
   1335   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
   1336 
   1337     // Fill the "else" block, created in the previous iteration
   1338     //
   1339     //  %mask_1 = extractelement <16 x i1> %mask, i32 Idx
   1340     //  %to_store = icmp eq i1 %mask_1, true
   1341     //  br i1 %to_store, label %cond.store, label %else
   1342     //
   1343     Value *Predicate = Builder.CreateExtractElement(Mask, Builder.getInt32(Idx));
   1344     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
   1345                                     ConstantInt::get(Predicate->getType(), 1));
   1346 
   1347     // Create "cond" block
   1348     //
   1349     //  %OneElt = extractelement <16 x i32> %Src, i32 Idx
   1350     //  %EltAddr = getelementptr i32* %1, i32 0
   1351     //  %store i32 %OneElt, i32* %EltAddr
   1352     //
   1353     BasicBlock *CondBlock =
   1354         IfBlock->splitBasicBlock(InsertPt->getIterator(), "cond.store");
   1355     Builder.SetInsertPoint(InsertPt);
   1356 
   1357     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx));
   1358     Value *Gep =
   1359         Builder.CreateInBoundsGEP(EltTy, FirstEltPtr, Builder.getInt32(Idx));
   1360     Builder.CreateAlignedStore(OneElt, Gep, AlignVal);
   1361 
   1362     // Create "else" block, fill it in the next iteration
   1363     BasicBlock *NewIfBlock =
   1364         CondBlock->splitBasicBlock(InsertPt->getIterator(), "else");
   1365     Builder.SetInsertPoint(InsertPt);
   1366     Instruction *OldBr = IfBlock->getTerminator();
   1367     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
   1368     OldBr->eraseFromParent();
   1369     IfBlock = NewIfBlock;
   1370   }
   1371   CI->eraseFromParent();
   1372 }
   1373 
   1374 // Translate a masked gather intrinsic like
   1375 // <16 x i32 > @llvm.masked.gather.v16i32( <16 x i32*> %Ptrs, i32 4,
   1376 //                               <16 x i1> %Mask, <16 x i32> %Src)
   1377 // to a chain of basic blocks, with loading element one-by-one if
   1378 // the appropriate mask bit is set
   1379 //
   1380 // % Ptrs = getelementptr i32, i32* %base, <16 x i64> %ind
   1381 // % Mask0 = extractelement <16 x i1> %Mask, i32 0
   1382 // % ToLoad0 = icmp eq i1 % Mask0, true
   1383 // br i1 % ToLoad0, label %cond.load, label %else
   1384 //
   1385 // cond.load:
   1386 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
   1387 // % Load0 = load i32, i32* % Ptr0, align 4
   1388 // % Res0 = insertelement <16 x i32> undef, i32 % Load0, i32 0
   1389 // br label %else
   1390 //
   1391 // else:
   1392 // %res.phi.else = phi <16 x i32>[% Res0, %cond.load], [undef, % 0]
   1393 // % Mask1 = extractelement <16 x i1> %Mask, i32 1
   1394 // % ToLoad1 = icmp eq i1 % Mask1, true
   1395 // br i1 % ToLoad1, label %cond.load1, label %else2
   1396 //
   1397 // cond.load1:
   1398 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
   1399 // % Load1 = load i32, i32* % Ptr1, align 4
   1400 // % Res1 = insertelement <16 x i32> %res.phi.else, i32 % Load1, i32 1
   1401 // br label %else2
   1402 // . . .
   1403 // % Result = select <16 x i1> %Mask, <16 x i32> %res.phi.select, <16 x i32> %Src
   1404 // ret <16 x i32> %Result
   1405 static void ScalarizeMaskedGather(CallInst *CI) {
   1406   Value *Ptrs = CI->getArgOperand(0);
   1407   Value *Alignment = CI->getArgOperand(1);
   1408   Value *Mask = CI->getArgOperand(2);
   1409   Value *Src0 = CI->getArgOperand(3);
   1410 
   1411   VectorType *VecType = dyn_cast<VectorType>(CI->getType());
   1412 
   1413   assert(VecType && "Unexpected return type of masked load intrinsic");
   1414 
   1415   IRBuilder<> Builder(CI->getContext());
   1416   Instruction *InsertPt = CI;
   1417   BasicBlock *IfBlock = CI->getParent();
   1418   BasicBlock *CondBlock = nullptr;
   1419   BasicBlock *PrevIfBlock = CI->getParent();
   1420   Builder.SetInsertPoint(InsertPt);
   1421   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
   1422 
   1423   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
   1424 
   1425   Value *UndefVal = UndefValue::get(VecType);
   1426 
   1427   // The result vector
   1428   Value *VResult = UndefVal;
   1429   unsigned VectorWidth = VecType->getNumElements();
   1430 
   1431   // Shorten the way if the mask is a vector of constants.
   1432   bool IsConstMask = isa<ConstantVector>(Mask);
   1433 
   1434   if (IsConstMask) {
   1435     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
   1436       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
   1437         continue;
   1438       Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
   1439                                                 "Ptr" + Twine(Idx));
   1440       LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
   1441                                                  "Load" + Twine(Idx));
   1442       VResult = Builder.CreateInsertElement(VResult, Load,
   1443                                             Builder.getInt32(Idx),
   1444                                             "Res" + Twine(Idx));
   1445     }
   1446     Value *NewI = Builder.CreateSelect(Mask, VResult, Src0);
   1447     CI->replaceAllUsesWith(NewI);
   1448     CI->eraseFromParent();
   1449     return;
   1450   }
   1451 
   1452   PHINode *Phi = nullptr;
   1453   Value *PrevPhi = UndefVal;
   1454 
   1455   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
   1456 
   1457     // Fill the "else" block, created in the previous iteration
   1458     //
   1459     //  %Mask1 = extractelement <16 x i1> %Mask, i32 1
   1460     //  %ToLoad1 = icmp eq i1 %Mask1, true
   1461     //  br i1 %ToLoad1, label %cond.load, label %else
   1462     //
   1463     if (Idx > 0) {
   1464       Phi = Builder.CreatePHI(VecType, 2, "res.phi.else");
   1465       Phi->addIncoming(VResult, CondBlock);
   1466       Phi->addIncoming(PrevPhi, PrevIfBlock);
   1467       PrevPhi = Phi;
   1468       VResult = Phi;
   1469     }
   1470 
   1471     Value *Predicate = Builder.CreateExtractElement(Mask,
   1472                                                     Builder.getInt32(Idx),
   1473                                                     "Mask" + Twine(Idx));
   1474     Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
   1475                                     ConstantInt::get(Predicate->getType(), 1),
   1476                                     "ToLoad" + Twine(Idx));
   1477 
   1478     // Create "cond" block
   1479     //
   1480     //  %EltAddr = getelementptr i32* %1, i32 0
   1481     //  %Elt = load i32* %EltAddr
   1482     //  VResult = insertelement <16 x i32> VResult, i32 %Elt, i32 Idx
   1483     //
   1484     CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.load");
   1485     Builder.SetInsertPoint(InsertPt);
   1486 
   1487     Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
   1488                                               "Ptr" + Twine(Idx));
   1489     LoadInst *Load = Builder.CreateAlignedLoad(Ptr, AlignVal,
   1490                                                "Load" + Twine(Idx));
   1491     VResult = Builder.CreateInsertElement(VResult, Load, Builder.getInt32(Idx),
   1492                                           "Res" + Twine(Idx));
   1493 
   1494     // Create "else" block, fill it in the next iteration
   1495     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
   1496     Builder.SetInsertPoint(InsertPt);
   1497     Instruction *OldBr = IfBlock->getTerminator();
   1498     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
   1499     OldBr->eraseFromParent();
   1500     PrevIfBlock = IfBlock;
   1501     IfBlock = NewIfBlock;
   1502   }
   1503 
   1504   Phi = Builder.CreatePHI(VecType, 2, "res.phi.select");
   1505   Phi->addIncoming(VResult, CondBlock);
   1506   Phi->addIncoming(PrevPhi, PrevIfBlock);
   1507   Value *NewI = Builder.CreateSelect(Mask, Phi, Src0);
   1508   CI->replaceAllUsesWith(NewI);
   1509   CI->eraseFromParent();
   1510 }
   1511 
   1512 // Translate a masked scatter intrinsic, like
   1513 // void @llvm.masked.scatter.v16i32(<16 x i32> %Src, <16 x i32*>* %Ptrs, i32 4,
   1514 //                                  <16 x i1> %Mask)
   1515 // to a chain of basic blocks, that stores element one-by-one if
   1516 // the appropriate mask bit is set.
   1517 //
   1518 // % Ptrs = getelementptr i32, i32* %ptr, <16 x i64> %ind
   1519 // % Mask0 = extractelement <16 x i1> % Mask, i32 0
   1520 // % ToStore0 = icmp eq i1 % Mask0, true
   1521 // br i1 %ToStore0, label %cond.store, label %else
   1522 //
   1523 // cond.store:
   1524 // % Elt0 = extractelement <16 x i32> %Src, i32 0
   1525 // % Ptr0 = extractelement <16 x i32*> %Ptrs, i32 0
   1526 // store i32 %Elt0, i32* % Ptr0, align 4
   1527 // br label %else
   1528 //
   1529 // else:
   1530 // % Mask1 = extractelement <16 x i1> % Mask, i32 1
   1531 // % ToStore1 = icmp eq i1 % Mask1, true
   1532 // br i1 % ToStore1, label %cond.store1, label %else2
   1533 //
   1534 // cond.store1:
   1535 // % Elt1 = extractelement <16 x i32> %Src, i32 1
   1536 // % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
   1537 // store i32 % Elt1, i32* % Ptr1, align 4
   1538 // br label %else2
   1539 //   . . .
   1540 static void ScalarizeMaskedScatter(CallInst *CI) {
   1541   Value *Src = CI->getArgOperand(0);
   1542   Value *Ptrs = CI->getArgOperand(1);
   1543   Value *Alignment = CI->getArgOperand(2);
   1544   Value *Mask = CI->getArgOperand(3);
   1545 
   1546   assert(isa<VectorType>(Src->getType()) &&
   1547          "Unexpected data type in masked scatter intrinsic");
   1548   assert(isa<VectorType>(Ptrs->getType()) &&
   1549          isa<PointerType>(Ptrs->getType()->getVectorElementType()) &&
   1550          "Vector of pointers is expected in masked scatter intrinsic");
   1551 
   1552   IRBuilder<> Builder(CI->getContext());
   1553   Instruction *InsertPt = CI;
   1554   BasicBlock *IfBlock = CI->getParent();
   1555   Builder.SetInsertPoint(InsertPt);
   1556   Builder.SetCurrentDebugLocation(CI->getDebugLoc());
   1557 
   1558   unsigned AlignVal = cast<ConstantInt>(Alignment)->getZExtValue();
   1559   unsigned VectorWidth = Src->getType()->getVectorNumElements();
   1560 
   1561   // Shorten the way if the mask is a vector of constants.
   1562   bool IsConstMask = isa<ConstantVector>(Mask);
   1563 
   1564   if (IsConstMask) {
   1565     for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
   1566       if (cast<ConstantVector>(Mask)->getOperand(Idx)->isNullValue())
   1567         continue;
   1568       Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
   1569                                                    "Elt" + Twine(Idx));
   1570       Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
   1571                                                 "Ptr" + Twine(Idx));
   1572       Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
   1573     }
   1574     CI->eraseFromParent();
   1575     return;
   1576   }
   1577   for (unsigned Idx = 0; Idx < VectorWidth; ++Idx) {
   1578     // Fill the "else" block, created in the previous iteration
   1579     //
   1580     //  % Mask1 = extractelement <16 x i1> % Mask, i32 Idx
   1581     //  % ToStore = icmp eq i1 % Mask1, true
   1582     //  br i1 % ToStore, label %cond.store, label %else
   1583     //
   1584     Value *Predicate = Builder.CreateExtractElement(Mask,
   1585                                                     Builder.getInt32(Idx),
   1586                                                     "Mask" + Twine(Idx));
   1587     Value *Cmp =
   1588        Builder.CreateICmp(ICmpInst::ICMP_EQ, Predicate,
   1589                           ConstantInt::get(Predicate->getType(), 1),
   1590                           "ToStore" + Twine(Idx));
   1591 
   1592     // Create "cond" block
   1593     //
   1594     //  % Elt1 = extractelement <16 x i32> %Src, i32 1
   1595     //  % Ptr1 = extractelement <16 x i32*> %Ptrs, i32 1
   1596     //  %store i32 % Elt1, i32* % Ptr1
   1597     //
   1598     BasicBlock *CondBlock = IfBlock->splitBasicBlock(InsertPt, "cond.store");
   1599     Builder.SetInsertPoint(InsertPt);
   1600 
   1601     Value *OneElt = Builder.CreateExtractElement(Src, Builder.getInt32(Idx),
   1602                                                  "Elt" + Twine(Idx));
   1603     Value *Ptr = Builder.CreateExtractElement(Ptrs, Builder.getInt32(Idx),
   1604                                               "Ptr" + Twine(Idx));
   1605     Builder.CreateAlignedStore(OneElt, Ptr, AlignVal);
   1606 
   1607     // Create "else" block, fill it in the next iteration
   1608     BasicBlock *NewIfBlock = CondBlock->splitBasicBlock(InsertPt, "else");
   1609     Builder.SetInsertPoint(InsertPt);
   1610     Instruction *OldBr = IfBlock->getTerminator();
   1611     BranchInst::Create(CondBlock, NewIfBlock, Cmp, OldBr);
   1612     OldBr->eraseFromParent();
   1613     IfBlock = NewIfBlock;
   1614   }
   1615   CI->eraseFromParent();
   1616 }
   1617 
   1618 /// If counting leading or trailing zeros is an expensive operation and a zero
   1619 /// input is defined, add a check for zero to avoid calling the intrinsic.
   1620 ///
   1621 /// We want to transform:
   1622 ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
   1623 ///
   1624 /// into:
   1625 ///   entry:
   1626 ///     %cmpz = icmp eq i64 %A, 0
   1627 ///     br i1 %cmpz, label %cond.end, label %cond.false
   1628 ///   cond.false:
   1629 ///     %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
   1630 ///     br label %cond.end
   1631 ///   cond.end:
   1632 ///     %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
   1633 ///
   1634 /// If the transform is performed, return true and set ModifiedDT to true.
   1635 static bool despeculateCountZeros(IntrinsicInst *CountZeros,
   1636                                   const TargetLowering *TLI,
   1637                                   const DataLayout *DL,
   1638                                   bool &ModifiedDT) {
   1639   if (!TLI || !DL)
   1640     return false;
   1641 
   1642   // If a zero input is undefined, it doesn't make sense to despeculate that.
   1643   if (match(CountZeros->getOperand(1), m_One()))
   1644     return false;
   1645 
   1646   // If it's cheap to speculate, there's nothing to do.
   1647   auto IntrinsicID = CountZeros->getIntrinsicID();
   1648   if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
   1649       (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
   1650     return false;
   1651 
   1652   // Only handle legal scalar cases. Anything else requires too much work.
   1653   Type *Ty = CountZeros->getType();
   1654   unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
   1655   if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSize())
   1656     return false;
   1657 
   1658   // The intrinsic will be sunk behind a compare against zero and branch.
   1659   BasicBlock *StartBlock = CountZeros->getParent();
   1660   BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
   1661 
   1662   // Create another block after the count zero intrinsic. A PHI will be added
   1663   // in this block to select the result of the intrinsic or the bit-width
   1664   // constant if the input to the intrinsic is zero.
   1665   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
   1666   BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
   1667 
   1668   // Set up a builder to create a compare, conditional branch, and PHI.
   1669   IRBuilder<> Builder(CountZeros->getContext());
   1670   Builder.SetInsertPoint(StartBlock->getTerminator());
   1671   Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
   1672 
   1673   // Replace the unconditional branch that was created by the first split with
   1674   // a compare against zero and a conditional branch.
   1675   Value *Zero = Constant::getNullValue(Ty);
   1676   Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
   1677   Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
   1678   StartBlock->getTerminator()->eraseFromParent();
   1679 
   1680   // Create a PHI in the end block to select either the output of the intrinsic
   1681   // or the bit width of the operand.
   1682   Builder.SetInsertPoint(&EndBlock->front());
   1683   PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
   1684   CountZeros->replaceAllUsesWith(PN);
   1685   Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
   1686   PN->addIncoming(BitWidth, StartBlock);
   1687   PN->addIncoming(CountZeros, CallBlock);
   1688 
   1689   // We are explicitly handling the zero case, so we can set the intrinsic's
   1690   // undefined zero argument to 'true'. This will also prevent reprocessing the
   1691   // intrinsic; we only despeculate when a zero input is defined.
   1692   CountZeros->setArgOperand(1, Builder.getTrue());
   1693   ModifiedDT = true;
   1694   return true;
   1695 }
   1696 
   1697 bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
   1698   BasicBlock *BB = CI->getParent();
   1699 
   1700   // Lower inline assembly if we can.
   1701   // If we found an inline asm expession, and if the target knows how to
   1702   // lower it to normal LLVM code, do so now.
   1703   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
   1704     if (TLI->ExpandInlineAsm(CI)) {
   1705       // Avoid invalidating the iterator.
   1706       CurInstIterator = BB->begin();
   1707       // Avoid processing instructions out of order, which could cause
   1708       // reuse before a value is defined.
   1709       SunkAddrs.clear();
   1710       return true;
   1711     }
   1712     // Sink address computing for memory operands into the block.
   1713     if (optimizeInlineAsmInst(CI))
   1714       return true;
   1715   }
   1716 
   1717   // Align the pointer arguments to this call if the target thinks it's a good
   1718   // idea
   1719   unsigned MinSize, PrefAlign;
   1720   if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
   1721     for (auto &Arg : CI->arg_operands()) {
   1722       // We want to align both objects whose address is used directly and
   1723       // objects whose address is used in casts and GEPs, though it only makes
   1724       // sense for GEPs if the offset is a multiple of the desired alignment and
   1725       // if size - offset meets the size threshold.
   1726       if (!Arg->getType()->isPointerTy())
   1727         continue;
   1728       APInt Offset(DL->getPointerSizeInBits(
   1729                        cast<PointerType>(Arg->getType())->getAddressSpace()),
   1730                    0);
   1731       Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
   1732       uint64_t Offset2 = Offset.getLimitedValue();
   1733       if ((Offset2 & (PrefAlign-1)) != 0)
   1734         continue;
   1735       AllocaInst *AI;
   1736       if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
   1737           DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
   1738         AI->setAlignment(PrefAlign);
   1739       // Global variables can only be aligned if they are defined in this
   1740       // object (i.e. they are uniquely initialized in this object), and
   1741       // over-aligning global variables that have an explicit section is
   1742       // forbidden.
   1743       GlobalVariable *GV;
   1744       if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->hasUniqueInitializer() &&
   1745           !GV->hasSection() && GV->getAlignment() < PrefAlign &&
   1746           DL->getTypeAllocSize(GV->getType()->getElementType()) >=
   1747               MinSize + Offset2)
   1748         GV->setAlignment(PrefAlign);
   1749     }
   1750     // If this is a memcpy (or similar) then we may be able to improve the
   1751     // alignment
   1752     if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
   1753       unsigned Align = getKnownAlignment(MI->getDest(), *DL);
   1754       if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
   1755         Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
   1756       if (Align > MI->getAlignment())
   1757         MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
   1758     }
   1759   }
   1760 
   1761   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
   1762   if (II) {
   1763     switch (II->getIntrinsicID()) {
   1764     default: break;
   1765     case Intrinsic::objectsize: {
   1766       // Lower all uses of llvm.objectsize.*
   1767       bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
   1768       Type *ReturnTy = CI->getType();
   1769       Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
   1770 
   1771       // Substituting this can cause recursive simplifications, which can
   1772       // invalidate our iterator.  Use a WeakVH to hold onto it in case this
   1773       // happens.
   1774       WeakVH IterHandle(&*CurInstIterator);
   1775 
   1776       replaceAndRecursivelySimplify(CI, RetVal,
   1777                                     TLInfo, nullptr);
   1778 
   1779       // If the iterator instruction was recursively deleted, start over at the
   1780       // start of the block.
   1781       if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
   1782         CurInstIterator = BB->begin();
   1783         SunkAddrs.clear();
   1784       }
   1785       return true;
   1786     }
   1787     case Intrinsic::masked_load: {
   1788       // Scalarize unsupported vector masked load
   1789       if (!TTI->isLegalMaskedLoad(CI->getType())) {
   1790         ScalarizeMaskedLoad(CI);
   1791         ModifiedDT = true;
   1792         return true;
   1793       }
   1794       return false;
   1795     }
   1796     case Intrinsic::masked_store: {
   1797       if (!TTI->isLegalMaskedStore(CI->getArgOperand(0)->getType())) {
   1798         ScalarizeMaskedStore(CI);
   1799         ModifiedDT = true;
   1800         return true;
   1801       }
   1802       return false;
   1803     }
   1804     case Intrinsic::masked_gather: {
   1805       if (!TTI->isLegalMaskedGather(CI->getType())) {
   1806         ScalarizeMaskedGather(CI);
   1807         ModifiedDT = true;
   1808         return true;
   1809       }
   1810       return false;
   1811     }
   1812     case Intrinsic::masked_scatter: {
   1813       if (!TTI->isLegalMaskedScatter(CI->getArgOperand(0)->getType())) {
   1814         ScalarizeMaskedScatter(CI);
   1815         ModifiedDT = true;
   1816         return true;
   1817       }
   1818       return false;
   1819     }
   1820     case Intrinsic::aarch64_stlxr:
   1821     case Intrinsic::aarch64_stxr: {
   1822       ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
   1823       if (!ExtVal || !ExtVal->hasOneUse() ||
   1824           ExtVal->getParent() == CI->getParent())
   1825         return false;
   1826       // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
   1827       ExtVal->moveBefore(CI);
   1828       // Mark this instruction as "inserted by CGP", so that other
   1829       // optimizations don't touch it.
   1830       InsertedInsts.insert(ExtVal);
   1831       return true;
   1832     }
   1833     case Intrinsic::invariant_group_barrier:
   1834       II->replaceAllUsesWith(II->getArgOperand(0));
   1835       II->eraseFromParent();
   1836       return true;
   1837 
   1838     case Intrinsic::cttz:
   1839     case Intrinsic::ctlz:
   1840       // If counting zeros is expensive, try to avoid it.
   1841       return despeculateCountZeros(II, TLI, DL, ModifiedDT);
   1842     }
   1843 
   1844     if (TLI) {
   1845       // Unknown address space.
   1846       // TODO: Target hook to pick which address space the intrinsic cares
   1847       // about?
   1848       unsigned AddrSpace = ~0u;
   1849       SmallVector<Value*, 2> PtrOps;
   1850       Type *AccessTy;
   1851       if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy, AddrSpace))
   1852         while (!PtrOps.empty())
   1853           if (optimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy, AddrSpace))
   1854             return true;
   1855     }
   1856   }
   1857 
   1858   // From here on out we're working with named functions.
   1859   if (!CI->getCalledFunction()) return false;
   1860 
   1861   // Lower all default uses of _chk calls.  This is very similar
   1862   // to what InstCombineCalls does, but here we are only lowering calls
   1863   // to fortified library functions (e.g. __memcpy_chk) that have the default
   1864   // "don't know" as the objectsize.  Anything else should be left alone.
   1865   FortifiedLibCallSimplifier Simplifier(TLInfo, true);
   1866   if (Value *V = Simplifier.optimizeCall(CI)) {
   1867     CI->replaceAllUsesWith(V);
   1868     CI->eraseFromParent();
   1869     return true;
   1870   }
   1871   return false;
   1872 }
   1873 
   1874 /// Look for opportunities to duplicate return instructions to the predecessor
   1875 /// to enable tail call optimizations. The case it is currently looking for is:
   1876 /// @code
   1877 /// bb0:
   1878 ///   %tmp0 = tail call i32 @f0()
   1879 ///   br label %return
   1880 /// bb1:
   1881 ///   %tmp1 = tail call i32 @f1()
   1882 ///   br label %return
   1883 /// bb2:
   1884 ///   %tmp2 = tail call i32 @f2()
   1885 ///   br label %return
   1886 /// return:
   1887 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
   1888 ///   ret i32 %retval
   1889 /// @endcode
   1890 ///
   1891 /// =>
   1892 ///
   1893 /// @code
   1894 /// bb0:
   1895 ///   %tmp0 = tail call i32 @f0()
   1896 ///   ret i32 %tmp0
   1897 /// bb1:
   1898 ///   %tmp1 = tail call i32 @f1()
   1899 ///   ret i32 %tmp1
   1900 /// bb2:
   1901 ///   %tmp2 = tail call i32 @f2()
   1902 ///   ret i32 %tmp2
   1903 /// @endcode
   1904 bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
   1905   if (!TLI)
   1906     return false;
   1907 
   1908   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
   1909   if (!RI)
   1910     return false;
   1911 
   1912   PHINode *PN = nullptr;
   1913   BitCastInst *BCI = nullptr;
   1914   Value *V = RI->getReturnValue();
   1915   if (V) {
   1916     BCI = dyn_cast<BitCastInst>(V);
   1917     if (BCI)
   1918       V = BCI->getOperand(0);
   1919 
   1920     PN = dyn_cast<PHINode>(V);
   1921     if (!PN)
   1922       return false;
   1923   }
   1924 
   1925   if (PN && PN->getParent() != BB)
   1926     return false;
   1927 
   1928   // It's not safe to eliminate the sign / zero extension of the return value.
   1929   // See llvm::isInTailCallPosition().
   1930   const Function *F = BB->getParent();
   1931   AttributeSet CallerAttrs = F->getAttributes();
   1932   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
   1933       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
   1934     return false;
   1935 
   1936   // Make sure there are no instructions between the PHI and return, or that the
   1937   // return is the first instruction in the block.
   1938   if (PN) {
   1939     BasicBlock::iterator BI = BB->begin();
   1940     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
   1941     if (&*BI == BCI)
   1942       // Also skip over the bitcast.
   1943       ++BI;
   1944     if (&*BI != RI)
   1945       return false;
   1946   } else {
   1947     BasicBlock::iterator BI = BB->begin();
   1948     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
   1949     if (&*BI != RI)
   1950       return false;
   1951   }
   1952 
   1953   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
   1954   /// call.
   1955   SmallVector<CallInst*, 4> TailCalls;
   1956   if (PN) {
   1957     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
   1958       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
   1959       // Make sure the phi value is indeed produced by the tail call.
   1960       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
   1961           TLI->mayBeEmittedAsTailCall(CI))
   1962         TailCalls.push_back(CI);
   1963     }
   1964   } else {
   1965     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
   1966     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
   1967       if (!VisitedBBs.insert(*PI).second)
   1968         continue;
   1969 
   1970       BasicBlock::InstListType &InstList = (*PI)->getInstList();
   1971       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
   1972       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
   1973       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
   1974       if (RI == RE)
   1975         continue;
   1976 
   1977       CallInst *CI = dyn_cast<CallInst>(&*RI);
   1978       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
   1979         TailCalls.push_back(CI);
   1980     }
   1981   }
   1982 
   1983   bool Changed = false;
   1984   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
   1985     CallInst *CI = TailCalls[i];
   1986     CallSite CS(CI);
   1987 
   1988     // Conservatively require the attributes of the call to match those of the
   1989     // return. Ignore noalias because it doesn't affect the call sequence.
   1990     AttributeSet CalleeAttrs = CS.getAttributes();
   1991     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
   1992           removeAttribute(Attribute::NoAlias) !=
   1993         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
   1994           removeAttribute(Attribute::NoAlias))
   1995       continue;
   1996 
   1997     // Make sure the call instruction is followed by an unconditional branch to
   1998     // the return block.
   1999     BasicBlock *CallBB = CI->getParent();
   2000     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
   2001     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
   2002       continue;
   2003 
   2004     // Duplicate the return into CallBB.
   2005     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
   2006     ModifiedDT = Changed = true;
   2007     ++NumRetsDup;
   2008   }
   2009 
   2010   // If we eliminated all predecessors of the block, delete the block now.
   2011   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
   2012     BB->eraseFromParent();
   2013 
   2014   return Changed;
   2015 }
   2016 
   2017 //===----------------------------------------------------------------------===//
   2018 // Memory Optimization
   2019 //===----------------------------------------------------------------------===//
   2020 
   2021 namespace {
   2022 
   2023 /// This is an extended version of TargetLowering::AddrMode
   2024 /// which holds actual Value*'s for register values.
   2025 struct ExtAddrMode : public TargetLowering::AddrMode {
   2026   Value *BaseReg;
   2027   Value *ScaledReg;
   2028   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
   2029   void print(raw_ostream &OS) const;
   2030   void dump() const;
   2031 
   2032   bool operator==(const ExtAddrMode& O) const {
   2033     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
   2034            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
   2035            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
   2036   }
   2037 };
   2038 
   2039 #ifndef NDEBUG
   2040 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
   2041   AM.print(OS);
   2042   return OS;
   2043 }
   2044 #endif
   2045 
   2046 void ExtAddrMode::print(raw_ostream &OS) const {
   2047   bool NeedPlus = false;
   2048   OS << "[";
   2049   if (BaseGV) {
   2050     OS << (NeedPlus ? " + " : "")
   2051        << "GV:";
   2052     BaseGV->printAsOperand(OS, /*PrintType=*/false);
   2053     NeedPlus = true;
   2054   }
   2055 
   2056   if (BaseOffs) {
   2057     OS << (NeedPlus ? " + " : "")
   2058        << BaseOffs;
   2059     NeedPlus = true;
   2060   }
   2061 
   2062   if (BaseReg) {
   2063     OS << (NeedPlus ? " + " : "")
   2064        << "Base:";
   2065     BaseReg->printAsOperand(OS, /*PrintType=*/false);
   2066     NeedPlus = true;
   2067   }
   2068   if (Scale) {
   2069     OS << (NeedPlus ? " + " : "")
   2070        << Scale << "*";
   2071     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
   2072   }
   2073 
   2074   OS << ']';
   2075 }
   2076 
   2077 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
   2078 void ExtAddrMode::dump() const {
   2079   print(dbgs());
   2080   dbgs() << '\n';
   2081 }
   2082 #endif
   2083 
   2084 /// \brief This class provides transaction based operation on the IR.
   2085 /// Every change made through this class is recorded in the internal state and
   2086 /// can be undone (rollback) until commit is called.
   2087 class TypePromotionTransaction {
   2088 
   2089   /// \brief This represents the common interface of the individual transaction.
   2090   /// Each class implements the logic for doing one specific modification on
   2091   /// the IR via the TypePromotionTransaction.
   2092   class TypePromotionAction {
   2093   protected:
   2094     /// The Instruction modified.
   2095     Instruction *Inst;
   2096 
   2097   public:
   2098     /// \brief Constructor of the action.
   2099     /// The constructor performs the related action on the IR.
   2100     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
   2101 
   2102     virtual ~TypePromotionAction() {}
   2103 
   2104     /// \brief Undo the modification done by this action.
   2105     /// When this method is called, the IR must be in the same state as it was
   2106     /// before this action was applied.
   2107     /// \pre Undoing the action works if and only if the IR is in the exact same
   2108     /// state as it was directly after this action was applied.
   2109     virtual void undo() = 0;
   2110 
   2111     /// \brief Advocate every change made by this action.
   2112     /// When the results on the IR of the action are to be kept, it is important
   2113     /// to call this function, otherwise hidden information may be kept forever.
   2114     virtual void commit() {
   2115       // Nothing to be done, this action is not doing anything.
   2116     }
   2117   };
   2118 
   2119   /// \brief Utility to remember the position of an instruction.
   2120   class InsertionHandler {
   2121     /// Position of an instruction.
   2122     /// Either an instruction:
   2123     /// - Is the first in a basic block: BB is used.
   2124     /// - Has a previous instructon: PrevInst is used.
   2125     union {
   2126       Instruction *PrevInst;
   2127       BasicBlock *BB;
   2128     } Point;
   2129     /// Remember whether or not the instruction had a previous instruction.
   2130     bool HasPrevInstruction;
   2131 
   2132   public:
   2133     /// \brief Record the position of \p Inst.
   2134     InsertionHandler(Instruction *Inst) {
   2135       BasicBlock::iterator It = Inst->getIterator();
   2136       HasPrevInstruction = (It != (Inst->getParent()->begin()));
   2137       if (HasPrevInstruction)
   2138         Point.PrevInst = &*--It;
   2139       else
   2140         Point.BB = Inst->getParent();
   2141     }
   2142 
   2143     /// \brief Insert \p Inst at the recorded position.
   2144     void insert(Instruction *Inst) {
   2145       if (HasPrevInstruction) {
   2146         if (Inst->getParent())
   2147           Inst->removeFromParent();
   2148         Inst->insertAfter(Point.PrevInst);
   2149       } else {
   2150         Instruction *Position = &*Point.BB->getFirstInsertionPt();
   2151         if (Inst->getParent())
   2152           Inst->moveBefore(Position);
   2153         else
   2154           Inst->insertBefore(Position);
   2155       }
   2156     }
   2157   };
   2158 
   2159   /// \brief Move an instruction before another.
   2160   class InstructionMoveBefore : public TypePromotionAction {
   2161     /// Original position of the instruction.
   2162     InsertionHandler Position;
   2163 
   2164   public:
   2165     /// \brief Move \p Inst before \p Before.
   2166     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
   2167         : TypePromotionAction(Inst), Position(Inst) {
   2168       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
   2169       Inst->moveBefore(Before);
   2170     }
   2171 
   2172     /// \brief Move the instruction back to its original position.
   2173     void undo() override {
   2174       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
   2175       Position.insert(Inst);
   2176     }
   2177   };
   2178 
   2179   /// \brief Set the operand of an instruction with a new value.
   2180   class OperandSetter : public TypePromotionAction {
   2181     /// Original operand of the instruction.
   2182     Value *Origin;
   2183     /// Index of the modified instruction.
   2184     unsigned Idx;
   2185 
   2186   public:
   2187     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
   2188     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
   2189         : TypePromotionAction(Inst), Idx(Idx) {
   2190       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
   2191                    << "for:" << *Inst << "\n"
   2192                    << "with:" << *NewVal << "\n");
   2193       Origin = Inst->getOperand(Idx);
   2194       Inst->setOperand(Idx, NewVal);
   2195     }
   2196 
   2197     /// \brief Restore the original value of the instruction.
   2198     void undo() override {
   2199       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
   2200                    << "for: " << *Inst << "\n"
   2201                    << "with: " << *Origin << "\n");
   2202       Inst->setOperand(Idx, Origin);
   2203     }
   2204   };
   2205 
   2206   /// \brief Hide the operands of an instruction.
   2207   /// Do as if this instruction was not using any of its operands.
   2208   class OperandsHider : public TypePromotionAction {
   2209     /// The list of original operands.
   2210     SmallVector<Value *, 4> OriginalValues;
   2211 
   2212   public:
   2213     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
   2214     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
   2215       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
   2216       unsigned NumOpnds = Inst->getNumOperands();
   2217       OriginalValues.reserve(NumOpnds);
   2218       for (unsigned It = 0; It < NumOpnds; ++It) {
   2219         // Save the current operand.
   2220         Value *Val = Inst->getOperand(It);
   2221         OriginalValues.push_back(Val);
   2222         // Set a dummy one.
   2223         // We could use OperandSetter here, but that would imply an overhead
   2224         // that we are not willing to pay.
   2225         Inst->setOperand(It, UndefValue::get(Val->getType()));
   2226       }
   2227     }
   2228 
   2229     /// \brief Restore the original list of uses.
   2230     void undo() override {
   2231       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
   2232       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
   2233         Inst->setOperand(It, OriginalValues[It]);
   2234     }
   2235   };
   2236 
   2237   /// \brief Build a truncate instruction.
   2238   class TruncBuilder : public TypePromotionAction {
   2239     Value *Val;
   2240   public:
   2241     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
   2242     /// result.
   2243     /// trunc Opnd to Ty.
   2244     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
   2245       IRBuilder<> Builder(Opnd);
   2246       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
   2247       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
   2248     }
   2249 
   2250     /// \brief Get the built value.
   2251     Value *getBuiltValue() { return Val; }
   2252 
   2253     /// \brief Remove the built instruction.
   2254     void undo() override {
   2255       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
   2256       if (Instruction *IVal = dyn_cast<Instruction>(Val))
   2257         IVal->eraseFromParent();
   2258     }
   2259   };
   2260 
   2261   /// \brief Build a sign extension instruction.
   2262   class SExtBuilder : public TypePromotionAction {
   2263     Value *Val;
   2264   public:
   2265     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
   2266     /// result.
   2267     /// sext Opnd to Ty.
   2268     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
   2269         : TypePromotionAction(InsertPt) {
   2270       IRBuilder<> Builder(InsertPt);
   2271       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
   2272       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
   2273     }
   2274 
   2275     /// \brief Get the built value.
   2276     Value *getBuiltValue() { return Val; }
   2277 
   2278     /// \brief Remove the built instruction.
   2279     void undo() override {
   2280       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
   2281       if (Instruction *IVal = dyn_cast<Instruction>(Val))
   2282         IVal->eraseFromParent();
   2283     }
   2284   };
   2285 
   2286   /// \brief Build a zero extension instruction.
   2287   class ZExtBuilder : public TypePromotionAction {
   2288     Value *Val;
   2289   public:
   2290     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
   2291     /// result.
   2292     /// zext Opnd to Ty.
   2293     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
   2294         : TypePromotionAction(InsertPt) {
   2295       IRBuilder<> Builder(InsertPt);
   2296       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
   2297       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
   2298     }
   2299 
   2300     /// \brief Get the built value.
   2301     Value *getBuiltValue() { return Val; }
   2302 
   2303     /// \brief Remove the built instruction.
   2304     void undo() override {
   2305       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
   2306       if (Instruction *IVal = dyn_cast<Instruction>(Val))
   2307         IVal->eraseFromParent();
   2308     }
   2309   };
   2310 
   2311   /// \brief Mutate an instruction to another type.
   2312   class TypeMutator : public TypePromotionAction {
   2313     /// Record the original type.
   2314     Type *OrigTy;
   2315 
   2316   public:
   2317     /// \brief Mutate the type of \p Inst into \p NewTy.
   2318     TypeMutator(Instruction *Inst, Type *NewTy)
   2319         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
   2320       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
   2321                    << "\n");
   2322       Inst->mutateType(NewTy);
   2323     }
   2324 
   2325     /// \brief Mutate the instruction back to its original type.
   2326     void undo() override {
   2327       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
   2328                    << "\n");
   2329       Inst->mutateType(OrigTy);
   2330     }
   2331   };
   2332 
   2333   /// \brief Replace the uses of an instruction by another instruction.
   2334   class UsesReplacer : public TypePromotionAction {
   2335     /// Helper structure to keep track of the replaced uses.
   2336     struct InstructionAndIdx {
   2337       /// The instruction using the instruction.
   2338       Instruction *Inst;
   2339       /// The index where this instruction is used for Inst.
   2340       unsigned Idx;
   2341       InstructionAndIdx(Instruction *Inst, unsigned Idx)
   2342           : Inst(Inst), Idx(Idx) {}
   2343     };
   2344 
   2345     /// Keep track of the original uses (pair Instruction, Index).
   2346     SmallVector<InstructionAndIdx, 4> OriginalUses;
   2347     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
   2348 
   2349   public:
   2350     /// \brief Replace all the use of \p Inst by \p New.
   2351     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
   2352       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
   2353                    << "\n");
   2354       // Record the original uses.
   2355       for (Use &U : Inst->uses()) {
   2356         Instruction *UserI = cast<Instruction>(U.getUser());
   2357         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
   2358       }
   2359       // Now, we can replace the uses.
   2360       Inst->replaceAllUsesWith(New);
   2361     }
   2362 
   2363     /// \brief Reassign the original uses of Inst to Inst.
   2364     void undo() override {
   2365       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
   2366       for (use_iterator UseIt = OriginalUses.begin(),
   2367                         EndIt = OriginalUses.end();
   2368            UseIt != EndIt; ++UseIt) {
   2369         UseIt->Inst->setOperand(UseIt->Idx, Inst);
   2370       }
   2371     }
   2372   };
   2373 
   2374   /// \brief Remove an instruction from the IR.
   2375   class InstructionRemover : public TypePromotionAction {
   2376     /// Original position of the instruction.
   2377     InsertionHandler Inserter;
   2378     /// Helper structure to hide all the link to the instruction. In other
   2379     /// words, this helps to do as if the instruction was removed.
   2380     OperandsHider Hider;
   2381     /// Keep track of the uses replaced, if any.
   2382     UsesReplacer *Replacer;
   2383 
   2384   public:
   2385     /// \brief Remove all reference of \p Inst and optinally replace all its
   2386     /// uses with New.
   2387     /// \pre If !Inst->use_empty(), then New != nullptr
   2388     InstructionRemover(Instruction *Inst, Value *New = nullptr)
   2389         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
   2390           Replacer(nullptr) {
   2391       if (New)
   2392         Replacer = new UsesReplacer(Inst, New);
   2393       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
   2394       Inst->removeFromParent();
   2395     }
   2396 
   2397     ~InstructionRemover() override { delete Replacer; }
   2398 
   2399     /// \brief Really remove the instruction.
   2400     void commit() override { delete Inst; }
   2401 
   2402     /// \brief Resurrect the instruction and reassign it to the proper uses if
   2403     /// new value was provided when build this action.
   2404     void undo() override {
   2405       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
   2406       Inserter.insert(Inst);
   2407       if (Replacer)
   2408         Replacer->undo();
   2409       Hider.undo();
   2410     }
   2411   };
   2412 
   2413 public:
   2414   /// Restoration point.
   2415   /// The restoration point is a pointer to an action instead of an iterator
   2416   /// because the iterator may be invalidated but not the pointer.
   2417   typedef const TypePromotionAction *ConstRestorationPt;
   2418   /// Advocate every changes made in that transaction.
   2419   void commit();
   2420   /// Undo all the changes made after the given point.
   2421   void rollback(ConstRestorationPt Point);
   2422   /// Get the current restoration point.
   2423   ConstRestorationPt getRestorationPoint() const;
   2424 
   2425   /// \name API for IR modification with state keeping to support rollback.
   2426   /// @{
   2427   /// Same as Instruction::setOperand.
   2428   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
   2429   /// Same as Instruction::eraseFromParent.
   2430   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
   2431   /// Same as Value::replaceAllUsesWith.
   2432   void replaceAllUsesWith(Instruction *Inst, Value *New);
   2433   /// Same as Value::mutateType.
   2434   void mutateType(Instruction *Inst, Type *NewTy);
   2435   /// Same as IRBuilder::createTrunc.
   2436   Value *createTrunc(Instruction *Opnd, Type *Ty);
   2437   /// Same as IRBuilder::createSExt.
   2438   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
   2439   /// Same as IRBuilder::createZExt.
   2440   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
   2441   /// Same as Instruction::moveBefore.
   2442   void moveBefore(Instruction *Inst, Instruction *Before);
   2443   /// @}
   2444 
   2445 private:
   2446   /// The ordered list of actions made so far.
   2447   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
   2448   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
   2449 };
   2450 
   2451 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
   2452                                           Value *NewVal) {
   2453   Actions.push_back(
   2454       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
   2455 }
   2456 
   2457 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
   2458                                                 Value *NewVal) {
   2459   Actions.push_back(
   2460       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
   2461 }
   2462 
   2463 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
   2464                                                   Value *New) {
   2465   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
   2466 }
   2467 
   2468 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
   2469   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
   2470 }
   2471 
   2472 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
   2473                                              Type *Ty) {
   2474   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
   2475   Value *Val = Ptr->getBuiltValue();
   2476   Actions.push_back(std::move(Ptr));
   2477   return Val;
   2478 }
   2479 
   2480 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
   2481                                             Value *Opnd, Type *Ty) {
   2482   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
   2483   Value *Val = Ptr->getBuiltValue();
   2484   Actions.push_back(std::move(Ptr));
   2485   return Val;
   2486 }
   2487 
   2488 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
   2489                                             Value *Opnd, Type *Ty) {
   2490   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
   2491   Value *Val = Ptr->getBuiltValue();
   2492   Actions.push_back(std::move(Ptr));
   2493   return Val;
   2494 }
   2495 
   2496 void TypePromotionTransaction::moveBefore(Instruction *Inst,
   2497                                           Instruction *Before) {
   2498   Actions.push_back(
   2499       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
   2500 }
   2501 
   2502 TypePromotionTransaction::ConstRestorationPt
   2503 TypePromotionTransaction::getRestorationPoint() const {
   2504   return !Actions.empty() ? Actions.back().get() : nullptr;
   2505 }
   2506 
   2507 void TypePromotionTransaction::commit() {
   2508   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
   2509        ++It)
   2510     (*It)->commit();
   2511   Actions.clear();
   2512 }
   2513 
   2514 void TypePromotionTransaction::rollback(
   2515     TypePromotionTransaction::ConstRestorationPt Point) {
   2516   while (!Actions.empty() && Point != Actions.back().get()) {
   2517     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
   2518     Curr->undo();
   2519   }
   2520 }
   2521 
   2522 /// \brief A helper class for matching addressing modes.
   2523 ///
   2524 /// This encapsulates the logic for matching the target-legal addressing modes.
   2525 class AddressingModeMatcher {
   2526   SmallVectorImpl<Instruction*> &AddrModeInsts;
   2527   const TargetMachine &TM;
   2528   const TargetLowering &TLI;
   2529   const DataLayout &DL;
   2530 
   2531   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
   2532   /// the memory instruction that we're computing this address for.
   2533   Type *AccessTy;
   2534   unsigned AddrSpace;
   2535   Instruction *MemoryInst;
   2536 
   2537   /// This is the addressing mode that we're building up. This is
   2538   /// part of the return value of this addressing mode matching stuff.
   2539   ExtAddrMode &AddrMode;
   2540 
   2541   /// The instructions inserted by other CodeGenPrepare optimizations.
   2542   const SetOfInstrs &InsertedInsts;
   2543   /// A map from the instructions to their type before promotion.
   2544   InstrToOrigTy &PromotedInsts;
   2545   /// The ongoing transaction where every action should be registered.
   2546   TypePromotionTransaction &TPT;
   2547 
   2548   /// This is set to true when we should not do profitability checks.
   2549   /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
   2550   bool IgnoreProfitability;
   2551 
   2552   AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
   2553                         const TargetMachine &TM, Type *AT, unsigned AS,
   2554                         Instruction *MI, ExtAddrMode &AM,
   2555                         const SetOfInstrs &InsertedInsts,
   2556                         InstrToOrigTy &PromotedInsts,
   2557                         TypePromotionTransaction &TPT)
   2558       : AddrModeInsts(AMI), TM(TM),
   2559         TLI(*TM.getSubtargetImpl(*MI->getParent()->getParent())
   2560                  ->getTargetLowering()),
   2561         DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
   2562         MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
   2563         PromotedInsts(PromotedInsts), TPT(TPT) {
   2564     IgnoreProfitability = false;
   2565   }
   2566 public:
   2567 
   2568   /// Find the maximal addressing mode that a load/store of V can fold,
   2569   /// give an access type of AccessTy.  This returns a list of involved
   2570   /// instructions in AddrModeInsts.
   2571   /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
   2572   /// optimizations.
   2573   /// \p PromotedInsts maps the instructions to their type before promotion.
   2574   /// \p The ongoing transaction where every action should be registered.
   2575   static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
   2576                            Instruction *MemoryInst,
   2577                            SmallVectorImpl<Instruction*> &AddrModeInsts,
   2578                            const TargetMachine &TM,
   2579                            const SetOfInstrs &InsertedInsts,
   2580                            InstrToOrigTy &PromotedInsts,
   2581                            TypePromotionTransaction &TPT) {
   2582     ExtAddrMode Result;
   2583 
   2584     bool Success = AddressingModeMatcher(AddrModeInsts, TM, AccessTy, AS,
   2585                                          MemoryInst, Result, InsertedInsts,
   2586                                          PromotedInsts, TPT).matchAddr(V, 0);
   2587     (void)Success; assert(Success && "Couldn't select *anything*?");
   2588     return Result;
   2589   }
   2590 private:
   2591   bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
   2592   bool matchAddr(Value *V, unsigned Depth);
   2593   bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
   2594                           bool *MovedAway = nullptr);
   2595   bool isProfitableToFoldIntoAddressingMode(Instruction *I,
   2596                                             ExtAddrMode &AMBefore,
   2597                                             ExtAddrMode &AMAfter);
   2598   bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
   2599   bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
   2600                              Value *PromotedOperand) const;
   2601 };
   2602 
   2603 /// Try adding ScaleReg*Scale to the current addressing mode.
   2604 /// Return true and update AddrMode if this addr mode is legal for the target,
   2605 /// false if not.
   2606 bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
   2607                                              unsigned Depth) {
   2608   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
   2609   // mode.  Just process that directly.
   2610   if (Scale == 1)
   2611     return matchAddr(ScaleReg, Depth);
   2612 
   2613   // If the scale is 0, it takes nothing to add this.
   2614   if (Scale == 0)
   2615     return true;
   2616 
   2617   // If we already have a scale of this value, we can add to it, otherwise, we
   2618   // need an available scale field.
   2619   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
   2620     return false;
   2621 
   2622   ExtAddrMode TestAddrMode = AddrMode;
   2623 
   2624   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
   2625   // [A+B + A*7] -> [B+A*8].
   2626   TestAddrMode.Scale += Scale;
   2627   TestAddrMode.ScaledReg = ScaleReg;
   2628 
   2629   // If the new address isn't legal, bail out.
   2630   if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
   2631     return false;
   2632 
   2633   // It was legal, so commit it.
   2634   AddrMode = TestAddrMode;
   2635 
   2636   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
   2637   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
   2638   // X*Scale + C*Scale to addr mode.
   2639   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
   2640   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
   2641       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
   2642     TestAddrMode.ScaledReg = AddLHS;
   2643     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
   2644 
   2645     // If this addressing mode is legal, commit it and remember that we folded
   2646     // this instruction.
   2647     if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
   2648       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
   2649       AddrMode = TestAddrMode;
   2650       return true;
   2651     }
   2652   }
   2653 
   2654   // Otherwise, not (x+c)*scale, just return what we have.
   2655   return true;
   2656 }
   2657 
   2658 /// This is a little filter, which returns true if an addressing computation
   2659 /// involving I might be folded into a load/store accessing it.
   2660 /// This doesn't need to be perfect, but needs to accept at least
   2661 /// the set of instructions that MatchOperationAddr can.
   2662 static bool MightBeFoldableInst(Instruction *I) {
   2663   switch (I->getOpcode()) {
   2664   case Instruction::BitCast:
   2665   case Instruction::AddrSpaceCast:
   2666     // Don't touch identity bitcasts.
   2667     if (I->getType() == I->getOperand(0)->getType())
   2668       return false;
   2669     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
   2670   case Instruction::PtrToInt:
   2671     // PtrToInt is always a noop, as we know that the int type is pointer sized.
   2672     return true;
   2673   case Instruction::IntToPtr:
   2674     // We know the input is intptr_t, so this is foldable.
   2675     return true;
   2676   case Instruction::Add:
   2677     return true;
   2678   case Instruction::Mul:
   2679   case Instruction::Shl:
   2680     // Can only handle X*C and X << C.
   2681     return isa<ConstantInt>(I->getOperand(1));
   2682   case Instruction::GetElementPtr:
   2683     return true;
   2684   default:
   2685     return false;
   2686   }
   2687 }
   2688 
   2689 /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
   2690 /// \note \p Val is assumed to be the product of some type promotion.
   2691 /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
   2692 /// to be legal, as the non-promoted value would have had the same state.
   2693 static bool isPromotedInstructionLegal(const TargetLowering &TLI,
   2694                                        const DataLayout &DL, Value *Val) {
   2695   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
   2696   if (!PromotedInst)
   2697     return false;
   2698   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
   2699   // If the ISDOpcode is undefined, it was undefined before the promotion.
   2700   if (!ISDOpcode)
   2701     return true;
   2702   // Otherwise, check if the promoted instruction is legal or not.
   2703   return TLI.isOperationLegalOrCustom(
   2704       ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
   2705 }
   2706 
   2707 /// \brief Hepler class to perform type promotion.
   2708 class TypePromotionHelper {
   2709   /// \brief Utility function to check whether or not a sign or zero extension
   2710   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
   2711   /// either using the operands of \p Inst or promoting \p Inst.
   2712   /// The type of the extension is defined by \p IsSExt.
   2713   /// In other words, check if:
   2714   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
   2715   /// #1 Promotion applies:
   2716   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
   2717   /// #2 Operand reuses:
   2718   /// ext opnd1 to ConsideredExtType.
   2719   /// \p PromotedInsts maps the instructions to their type before promotion.
   2720   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
   2721                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
   2722 
   2723   /// \brief Utility function to determine if \p OpIdx should be promoted when
   2724   /// promoting \p Inst.
   2725   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
   2726     return !(isa<SelectInst>(Inst) && OpIdx == 0);
   2727   }
   2728 
   2729   /// \brief Utility function to promote the operand of \p Ext when this
   2730   /// operand is a promotable trunc or sext or zext.
   2731   /// \p PromotedInsts maps the instructions to their type before promotion.
   2732   /// \p CreatedInstsCost[out] contains the cost of all instructions
   2733   /// created to promote the operand of Ext.
   2734   /// Newly added extensions are inserted in \p Exts.
   2735   /// Newly added truncates are inserted in \p Truncs.
   2736   /// Should never be called directly.
   2737   /// \return The promoted value which is used instead of Ext.
   2738   static Value *promoteOperandForTruncAndAnyExt(
   2739       Instruction *Ext, TypePromotionTransaction &TPT,
   2740       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
   2741       SmallVectorImpl<Instruction *> *Exts,
   2742       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
   2743 
   2744   /// \brief Utility function to promote the operand of \p Ext when this
   2745   /// operand is promotable and is not a supported trunc or sext.
   2746   /// \p PromotedInsts maps the instructions to their type before promotion.
   2747   /// \p CreatedInstsCost[out] contains the cost of all the instructions
   2748   /// created to promote the operand of Ext.
   2749   /// Newly added extensions are inserted in \p Exts.
   2750   /// Newly added truncates are inserted in \p Truncs.
   2751   /// Should never be called directly.
   2752   /// \return The promoted value which is used instead of Ext.
   2753   static Value *promoteOperandForOther(Instruction *Ext,
   2754                                        TypePromotionTransaction &TPT,
   2755                                        InstrToOrigTy &PromotedInsts,
   2756                                        unsigned &CreatedInstsCost,
   2757                                        SmallVectorImpl<Instruction *> *Exts,
   2758                                        SmallVectorImpl<Instruction *> *Truncs,
   2759                                        const TargetLowering &TLI, bool IsSExt);
   2760 
   2761   /// \see promoteOperandForOther.
   2762   static Value *signExtendOperandForOther(
   2763       Instruction *Ext, TypePromotionTransaction &TPT,
   2764       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
   2765       SmallVectorImpl<Instruction *> *Exts,
   2766       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
   2767     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
   2768                                   Exts, Truncs, TLI, true);
   2769   }
   2770 
   2771   /// \see promoteOperandForOther.
   2772   static Value *zeroExtendOperandForOther(
   2773       Instruction *Ext, TypePromotionTransaction &TPT,
   2774       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
   2775       SmallVectorImpl<Instruction *> *Exts,
   2776       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
   2777     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
   2778                                   Exts, Truncs, TLI, false);
   2779   }
   2780 
   2781 public:
   2782   /// Type for the utility function that promotes the operand of Ext.
   2783   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
   2784                            InstrToOrigTy &PromotedInsts,
   2785                            unsigned &CreatedInstsCost,
   2786                            SmallVectorImpl<Instruction *> *Exts,
   2787                            SmallVectorImpl<Instruction *> *Truncs,
   2788                            const TargetLowering &TLI);
   2789   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
   2790   /// action to promote the operand of \p Ext instead of using Ext.
   2791   /// \return NULL if no promotable action is possible with the current
   2792   /// sign extension.
   2793   /// \p InsertedInsts keeps track of all the instructions inserted by the
   2794   /// other CodeGenPrepare optimizations. This information is important
   2795   /// because we do not want to promote these instructions as CodeGenPrepare
   2796   /// will reinsert them later. Thus creating an infinite loop: create/remove.
   2797   /// \p PromotedInsts maps the instructions to their type before promotion.
   2798   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
   2799                           const TargetLowering &TLI,
   2800                           const InstrToOrigTy &PromotedInsts);
   2801 };
   2802 
   2803 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
   2804                                         Type *ConsideredExtType,
   2805                                         const InstrToOrigTy &PromotedInsts,
   2806                                         bool IsSExt) {
   2807   // The promotion helper does not know how to deal with vector types yet.
   2808   // To be able to fix that, we would need to fix the places where we
   2809   // statically extend, e.g., constants and such.
   2810   if (Inst->getType()->isVectorTy())
   2811     return false;
   2812 
   2813   // We can always get through zext.
   2814   if (isa<ZExtInst>(Inst))
   2815     return true;
   2816 
   2817   // sext(sext) is ok too.
   2818   if (IsSExt && isa<SExtInst>(Inst))
   2819     return true;
   2820 
   2821   // We can get through binary operator, if it is legal. In other words, the
   2822   // binary operator must have a nuw or nsw flag.
   2823   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
   2824   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
   2825       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
   2826        (IsSExt && BinOp->hasNoSignedWrap())))
   2827     return true;
   2828 
   2829   // Check if we can do the following simplification.
   2830   // ext(trunc(opnd)) --> ext(opnd)
   2831   if (!isa<TruncInst>(Inst))
   2832     return false;
   2833 
   2834   Value *OpndVal = Inst->getOperand(0);
   2835   // Check if we can use this operand in the extension.
   2836   // If the type is larger than the result type of the extension, we cannot.
   2837   if (!OpndVal->getType()->isIntegerTy() ||
   2838       OpndVal->getType()->getIntegerBitWidth() >
   2839           ConsideredExtType->getIntegerBitWidth())
   2840     return false;
   2841 
   2842   // If the operand of the truncate is not an instruction, we will not have
   2843   // any information on the dropped bits.
   2844   // (Actually we could for constant but it is not worth the extra logic).
   2845   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
   2846   if (!Opnd)
   2847     return false;
   2848 
   2849   // Check if the source of the type is narrow enough.
   2850   // I.e., check that trunc just drops extended bits of the same kind of
   2851   // the extension.
   2852   // #1 get the type of the operand and check the kind of the extended bits.
   2853   const Type *OpndType;
   2854   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
   2855   if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
   2856     OpndType = It->second.getPointer();
   2857   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
   2858     OpndType = Opnd->getOperand(0)->getType();
   2859   else
   2860     return false;
   2861 
   2862   // #2 check that the truncate just drops extended bits.
   2863   return Inst->getType()->getIntegerBitWidth() >=
   2864          OpndType->getIntegerBitWidth();
   2865 }
   2866 
   2867 TypePromotionHelper::Action TypePromotionHelper::getAction(
   2868     Instruction *Ext, const SetOfInstrs &InsertedInsts,
   2869     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
   2870   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
   2871          "Unexpected instruction type");
   2872   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
   2873   Type *ExtTy = Ext->getType();
   2874   bool IsSExt = isa<SExtInst>(Ext);
   2875   // If the operand of the extension is not an instruction, we cannot
   2876   // get through.
   2877   // If it, check we can get through.
   2878   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
   2879     return nullptr;
   2880 
   2881   // Do not promote if the operand has been added by codegenprepare.
   2882   // Otherwise, it means we are undoing an optimization that is likely to be
   2883   // redone, thus causing potential infinite loop.
   2884   if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
   2885     return nullptr;
   2886 
   2887   // SExt or Trunc instructions.
   2888   // Return the related handler.
   2889   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
   2890       isa<ZExtInst>(ExtOpnd))
   2891     return promoteOperandForTruncAndAnyExt;
   2892 
   2893   // Regular instruction.
   2894   // Abort early if we will have to insert non-free instructions.
   2895   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
   2896     return nullptr;
   2897   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
   2898 }
   2899 
   2900 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
   2901     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
   2902     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
   2903     SmallVectorImpl<Instruction *> *Exts,
   2904     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
   2905   // By construction, the operand of SExt is an instruction. Otherwise we cannot
   2906   // get through it and this method should not be called.
   2907   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
   2908   Value *ExtVal = SExt;
   2909   bool HasMergedNonFreeExt = false;
   2910   if (isa<ZExtInst>(SExtOpnd)) {
   2911     // Replace s|zext(zext(opnd))
   2912     // => zext(opnd).
   2913     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
   2914     Value *ZExt =
   2915         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
   2916     TPT.replaceAllUsesWith(SExt, ZExt);
   2917     TPT.eraseInstruction(SExt);
   2918     ExtVal = ZExt;
   2919   } else {
   2920     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
   2921     // => z|sext(opnd).
   2922     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
   2923   }
   2924   CreatedInstsCost = 0;
   2925 
   2926   // Remove dead code.
   2927   if (SExtOpnd->use_empty())
   2928     TPT.eraseInstruction(SExtOpnd);
   2929 
   2930   // Check if the extension is still needed.
   2931   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
   2932   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
   2933     if (ExtInst) {
   2934       if (Exts)
   2935         Exts->push_back(ExtInst);
   2936       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
   2937     }
   2938     return ExtVal;
   2939   }
   2940 
   2941   // At this point we have: ext ty opnd to ty.
   2942   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
   2943   Value *NextVal = ExtInst->getOperand(0);
   2944   TPT.eraseInstruction(ExtInst, NextVal);
   2945   return NextVal;
   2946 }
   2947 
   2948 Value *TypePromotionHelper::promoteOperandForOther(
   2949     Instruction *Ext, TypePromotionTransaction &TPT,
   2950     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
   2951     SmallVectorImpl<Instruction *> *Exts,
   2952     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
   2953     bool IsSExt) {
   2954   // By construction, the operand of Ext is an instruction. Otherwise we cannot
   2955   // get through it and this method should not be called.
   2956   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
   2957   CreatedInstsCost = 0;
   2958   if (!ExtOpnd->hasOneUse()) {
   2959     // ExtOpnd will be promoted.
   2960     // All its uses, but Ext, will need to use a truncated value of the
   2961     // promoted version.
   2962     // Create the truncate now.
   2963     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
   2964     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
   2965       ITrunc->removeFromParent();
   2966       // Insert it just after the definition.
   2967       ITrunc->insertAfter(ExtOpnd);
   2968       if (Truncs)
   2969         Truncs->push_back(ITrunc);
   2970     }
   2971 
   2972     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
   2973     // Restore the operand of Ext (which has been replaced by the previous call
   2974     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
   2975     TPT.setOperand(Ext, 0, ExtOpnd);
   2976   }
   2977 
   2978   // Get through the Instruction:
   2979   // 1. Update its type.
   2980   // 2. Replace the uses of Ext by Inst.
   2981   // 3. Extend each operand that needs to be extended.
   2982 
   2983   // Remember the original type of the instruction before promotion.
   2984   // This is useful to know that the high bits are sign extended bits.
   2985   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
   2986       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
   2987   // Step #1.
   2988   TPT.mutateType(ExtOpnd, Ext->getType());
   2989   // Step #2.
   2990   TPT.replaceAllUsesWith(Ext, ExtOpnd);
   2991   // Step #3.
   2992   Instruction *ExtForOpnd = Ext;
   2993 
   2994   DEBUG(dbgs() << "Propagate Ext to operands\n");
   2995   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
   2996        ++OpIdx) {
   2997     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
   2998     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
   2999         !shouldExtOperand(ExtOpnd, OpIdx)) {
   3000       DEBUG(dbgs() << "No need to propagate\n");
   3001       continue;
   3002     }
   3003     // Check if we can statically extend the operand.
   3004     Value *Opnd = ExtOpnd->getOperand(OpIdx);
   3005     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
   3006       DEBUG(dbgs() << "Statically extend\n");
   3007       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
   3008       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
   3009                             : Cst->getValue().zext(BitWidth);
   3010       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
   3011       continue;
   3012     }
   3013     // UndefValue are typed, so we have to statically sign extend them.
   3014     if (isa<UndefValue>(Opnd)) {
   3015       DEBUG(dbgs() << "Statically extend\n");
   3016       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
   3017       continue;
   3018     }
   3019 
   3020     // Otherwise we have to explicity sign extend the operand.
   3021     // Check if Ext was reused to extend an operand.
   3022     if (!ExtForOpnd) {
   3023       // If yes, create a new one.
   3024       DEBUG(dbgs() << "More operands to ext\n");
   3025       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
   3026         : TPT.createZExt(Ext, Opnd, Ext->getType());
   3027       if (!isa<Instruction>(ValForExtOpnd)) {
   3028         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
   3029         continue;
   3030       }
   3031       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
   3032     }
   3033     if (Exts)
   3034       Exts->push_back(ExtForOpnd);
   3035     TPT.setOperand(ExtForOpnd, 0, Opnd);
   3036 
   3037     // Move the sign extension before the insertion point.
   3038     TPT.moveBefore(ExtForOpnd, ExtOpnd);
   3039     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
   3040     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
   3041     // If more sext are required, new instructions will have to be created.
   3042     ExtForOpnd = nullptr;
   3043   }
   3044   if (ExtForOpnd == Ext) {
   3045     DEBUG(dbgs() << "Extension is useless now\n");
   3046     TPT.eraseInstruction(Ext);
   3047   }
   3048   return ExtOpnd;
   3049 }
   3050 
   3051 /// Check whether or not promoting an instruction to a wider type is profitable.
   3052 /// \p NewCost gives the cost of extension instructions created by the
   3053 /// promotion.
   3054 /// \p OldCost gives the cost of extension instructions before the promotion
   3055 /// plus the number of instructions that have been
   3056 /// matched in the addressing mode the promotion.
   3057 /// \p PromotedOperand is the value that has been promoted.
   3058 /// \return True if the promotion is profitable, false otherwise.
   3059 bool AddressingModeMatcher::isPromotionProfitable(
   3060     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
   3061   DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
   3062   // The cost of the new extensions is greater than the cost of the
   3063   // old extension plus what we folded.
   3064   // This is not profitable.
   3065   if (NewCost > OldCost)
   3066     return false;
   3067   if (NewCost < OldCost)
   3068     return true;
   3069   // The promotion is neutral but it may help folding the sign extension in
   3070   // loads for instance.
   3071   // Check that we did not create an illegal instruction.
   3072   return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
   3073 }
   3074 
   3075 /// Given an instruction or constant expr, see if we can fold the operation
   3076 /// into the addressing mode. If so, update the addressing mode and return
   3077 /// true, otherwise return false without modifying AddrMode.
   3078 /// If \p MovedAway is not NULL, it contains the information of whether or
   3079 /// not AddrInst has to be folded into the addressing mode on success.
   3080 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
   3081 /// because it has been moved away.
   3082 /// Thus AddrInst must not be added in the matched instructions.
   3083 /// This state can happen when AddrInst is a sext, since it may be moved away.
   3084 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
   3085 /// not be referenced anymore.
   3086 bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
   3087                                                unsigned Depth,
   3088                                                bool *MovedAway) {
   3089   // Avoid exponential behavior on extremely deep expression trees.
   3090   if (Depth >= 5) return false;
   3091 
   3092   // By default, all matched instructions stay in place.
   3093   if (MovedAway)
   3094     *MovedAway = false;
   3095 
   3096   switch (Opcode) {
   3097   case Instruction::PtrToInt:
   3098     // PtrToInt is always a noop, as we know that the int type is pointer sized.
   3099     return matchAddr(AddrInst->getOperand(0), Depth);
   3100   case Instruction::IntToPtr: {
   3101     auto AS = AddrInst->getType()->getPointerAddressSpace();
   3102     auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
   3103     // This inttoptr is a no-op if the integer type is pointer sized.
   3104     if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
   3105       return matchAddr(AddrInst->getOperand(0), Depth);
   3106     return false;
   3107   }
   3108   case Instruction::BitCast:
   3109     // BitCast is always a noop, and we can handle it as long as it is
   3110     // int->int or pointer->pointer (we don't want int<->fp or something).
   3111     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
   3112          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
   3113         // Don't touch identity bitcasts.  These were probably put here by LSR,
   3114         // and we don't want to mess around with them.  Assume it knows what it
   3115         // is doing.
   3116         AddrInst->getOperand(0)->getType() != AddrInst->getType())
   3117       return matchAddr(AddrInst->getOperand(0), Depth);
   3118     return false;
   3119   case Instruction::AddrSpaceCast: {
   3120     unsigned SrcAS
   3121       = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
   3122     unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
   3123     if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
   3124       return matchAddr(AddrInst->getOperand(0), Depth);
   3125     return false;
   3126   }
   3127   case Instruction::Add: {
   3128     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
   3129     ExtAddrMode BackupAddrMode = AddrMode;
   3130     unsigned OldSize = AddrModeInsts.size();
   3131     // Start a transaction at this point.
   3132     // The LHS may match but not the RHS.
   3133     // Therefore, we need a higher level restoration point to undo partially
   3134     // matched operation.
   3135     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
   3136         TPT.getRestorationPoint();
   3137 
   3138     if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
   3139         matchAddr(AddrInst->getOperand(0), Depth+1))
   3140       return true;
   3141 
   3142     // Restore the old addr mode info.
   3143     AddrMode = BackupAddrMode;
   3144     AddrModeInsts.resize(OldSize);
   3145     TPT.rollback(LastKnownGood);
   3146 
   3147     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
   3148     if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
   3149         matchAddr(AddrInst->getOperand(1), Depth+1))
   3150       return true;
   3151 
   3152     // Otherwise we definitely can't merge the ADD in.
   3153     AddrMode = BackupAddrMode;
   3154     AddrModeInsts.resize(OldSize);
   3155     TPT.rollback(LastKnownGood);
   3156     break;
   3157   }
   3158   //case Instruction::Or:
   3159   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
   3160   //break;
   3161   case Instruction::Mul:
   3162   case Instruction::Shl: {
   3163     // Can only handle X*C and X << C.
   3164     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
   3165     if (!RHS)
   3166       return false;
   3167     int64_t Scale = RHS->getSExtValue();
   3168     if (Opcode == Instruction::Shl)
   3169       Scale = 1LL << Scale;
   3170 
   3171     return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
   3172   }
   3173   case Instruction::GetElementPtr: {
   3174     // Scan the GEP.  We check it if it contains constant offsets and at most
   3175     // one variable offset.
   3176     int VariableOperand = -1;
   3177     unsigned VariableScale = 0;
   3178 
   3179     int64_t ConstantOffset = 0;
   3180     gep_type_iterator GTI = gep_type_begin(AddrInst);
   3181     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
   3182       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
   3183         const StructLayout *SL = DL.getStructLayout(STy);
   3184         unsigned Idx =
   3185           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
   3186         ConstantOffset += SL->getElementOffset(Idx);
   3187       } else {
   3188         uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
   3189         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
   3190           ConstantOffset += CI->getSExtValue()*TypeSize;
   3191         } else if (TypeSize) {  // Scales of zero don't do anything.
   3192           // We only allow one variable index at the moment.
   3193           if (VariableOperand != -1)
   3194             return false;
   3195 
   3196           // Remember the variable index.
   3197           VariableOperand = i;
   3198           VariableScale = TypeSize;
   3199         }
   3200       }
   3201     }
   3202 
   3203     // A common case is for the GEP to only do a constant offset.  In this case,
   3204     // just add it to the disp field and check validity.
   3205     if (VariableOperand == -1) {
   3206       AddrMode.BaseOffs += ConstantOffset;
   3207       if (ConstantOffset == 0 ||
   3208           TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
   3209         // Check to see if we can fold the base pointer in too.
   3210         if (matchAddr(AddrInst->getOperand(0), Depth+1))
   3211           return true;
   3212       }
   3213       AddrMode.BaseOffs -= ConstantOffset;
   3214       return false;
   3215     }
   3216 
   3217     // Save the valid addressing mode in case we can't match.
   3218     ExtAddrMode BackupAddrMode = AddrMode;
   3219     unsigned OldSize = AddrModeInsts.size();
   3220 
   3221     // See if the scale and offset amount is valid for this target.
   3222     AddrMode.BaseOffs += ConstantOffset;
   3223 
   3224     // Match the base operand of the GEP.
   3225     if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
   3226       // If it couldn't be matched, just stuff the value in a register.
   3227       if (AddrMode.HasBaseReg) {
   3228         AddrMode = BackupAddrMode;
   3229         AddrModeInsts.resize(OldSize);
   3230         return false;
   3231       }
   3232       AddrMode.HasBaseReg = true;
   3233       AddrMode.BaseReg = AddrInst->getOperand(0);
   3234     }
   3235 
   3236     // Match the remaining variable portion of the GEP.
   3237     if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
   3238                           Depth)) {
   3239       // If it couldn't be matched, try stuffing the base into a register
   3240       // instead of matching it, and retrying the match of the scale.
   3241       AddrMode = BackupAddrMode;
   3242       AddrModeInsts.resize(OldSize);
   3243       if (AddrMode.HasBaseReg)
   3244         return false;
   3245       AddrMode.HasBaseReg = true;
   3246       AddrMode.BaseReg = AddrInst->getOperand(0);
   3247       AddrMode.BaseOffs += ConstantOffset;
   3248       if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
   3249                             VariableScale, Depth)) {
   3250         // If even that didn't work, bail.
   3251         AddrMode = BackupAddrMode;
   3252         AddrModeInsts.resize(OldSize);
   3253         return false;
   3254       }
   3255     }
   3256 
   3257     return true;
   3258   }
   3259   case Instruction::SExt:
   3260   case Instruction::ZExt: {
   3261     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
   3262     if (!Ext)
   3263       return false;
   3264 
   3265     // Try to move this ext out of the way of the addressing mode.
   3266     // Ask for a method for doing so.
   3267     TypePromotionHelper::Action TPH =
   3268         TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
   3269     if (!TPH)
   3270       return false;
   3271 
   3272     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
   3273         TPT.getRestorationPoint();
   3274     unsigned CreatedInstsCost = 0;
   3275     unsigned ExtCost = !TLI.isExtFree(Ext);
   3276     Value *PromotedOperand =
   3277         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
   3278     // SExt has been moved away.
   3279     // Thus either it will be rematched later in the recursive calls or it is
   3280     // gone. Anyway, we must not fold it into the addressing mode at this point.
   3281     // E.g.,
   3282     // op = add opnd, 1
   3283     // idx = ext op
   3284     // addr = gep base, idx
   3285     // is now:
   3286     // promotedOpnd = ext opnd            <- no match here
   3287     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
   3288     // addr = gep base, op                <- match
   3289     if (MovedAway)
   3290       *MovedAway = true;
   3291 
   3292     assert(PromotedOperand &&
   3293            "TypePromotionHelper should have filtered out those cases");
   3294 
   3295     ExtAddrMode BackupAddrMode = AddrMode;
   3296     unsigned OldSize = AddrModeInsts.size();
   3297 
   3298     if (!matchAddr(PromotedOperand, Depth) ||
   3299         // The total of the new cost is equal to the cost of the created
   3300         // instructions.
   3301         // The total of the old cost is equal to the cost of the extension plus
   3302         // what we have saved in the addressing mode.
   3303         !isPromotionProfitable(CreatedInstsCost,
   3304                                ExtCost + (AddrModeInsts.size() - OldSize),
   3305                                PromotedOperand)) {
   3306       AddrMode = BackupAddrMode;
   3307       AddrModeInsts.resize(OldSize);
   3308       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
   3309       TPT.rollback(LastKnownGood);
   3310       return false;
   3311     }
   3312     return true;
   3313   }
   3314   }
   3315   return false;
   3316 }
   3317 
   3318 /// If we can, try to add the value of 'Addr' into the current addressing mode.
   3319 /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
   3320 /// unmodified. This assumes that Addr is either a pointer type or intptr_t
   3321 /// for the target.
   3322 ///
   3323 bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
   3324   // Start a transaction at this point that we will rollback if the matching
   3325   // fails.
   3326   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
   3327       TPT.getRestorationPoint();
   3328   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
   3329     // Fold in immediates if legal for the target.
   3330     AddrMode.BaseOffs += CI->getSExtValue();
   3331     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
   3332       return true;
   3333     AddrMode.BaseOffs -= CI->getSExtValue();
   3334   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
   3335     // If this is a global variable, try to fold it into the addressing mode.
   3336     if (!AddrMode.BaseGV) {
   3337       AddrMode.BaseGV = GV;
   3338       if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
   3339         return true;
   3340       AddrMode.BaseGV = nullptr;
   3341     }
   3342   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
   3343     ExtAddrMode BackupAddrMode = AddrMode;
   3344     unsigned OldSize = AddrModeInsts.size();
   3345 
   3346     // Check to see if it is possible to fold this operation.
   3347     bool MovedAway = false;
   3348     if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
   3349       // This instruction may have been moved away. If so, there is nothing
   3350       // to check here.
   3351       if (MovedAway)
   3352         return true;
   3353       // Okay, it's possible to fold this.  Check to see if it is actually
   3354       // *profitable* to do so.  We use a simple cost model to avoid increasing
   3355       // register pressure too much.
   3356       if (I->hasOneUse() ||
   3357           isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
   3358         AddrModeInsts.push_back(I);
   3359         return true;
   3360       }
   3361 
   3362       // It isn't profitable to do this, roll back.
   3363       //cerr << "NOT FOLDING: " << *I;
   3364       AddrMode = BackupAddrMode;
   3365       AddrModeInsts.resize(OldSize);
   3366       TPT.rollback(LastKnownGood);
   3367     }
   3368   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
   3369     if (matchOperationAddr(CE, CE->getOpcode(), Depth))
   3370       return true;
   3371     TPT.rollback(LastKnownGood);
   3372   } else if (isa<ConstantPointerNull>(Addr)) {
   3373     // Null pointer gets folded without affecting the addressing mode.
   3374     return true;
   3375   }
   3376 
   3377   // Worse case, the target should support [reg] addressing modes. :)
   3378   if (!AddrMode.HasBaseReg) {
   3379     AddrMode.HasBaseReg = true;
   3380     AddrMode.BaseReg = Addr;
   3381     // Still check for legality in case the target supports [imm] but not [i+r].
   3382     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
   3383       return true;
   3384     AddrMode.HasBaseReg = false;
   3385     AddrMode.BaseReg = nullptr;
   3386   }
   3387 
   3388   // If the base register is already taken, see if we can do [r+r].
   3389   if (AddrMode.Scale == 0) {
   3390     AddrMode.Scale = 1;
   3391     AddrMode.ScaledReg = Addr;
   3392     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
   3393       return true;
   3394     AddrMode.Scale = 0;
   3395     AddrMode.ScaledReg = nullptr;
   3396   }
   3397   // Couldn't match.
   3398   TPT.rollback(LastKnownGood);
   3399   return false;
   3400 }
   3401 
   3402 /// Check to see if all uses of OpVal by the specified inline asm call are due
   3403 /// to memory operands. If so, return true, otherwise return false.
   3404 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
   3405                                     const TargetMachine &TM) {
   3406   const Function *F = CI->getParent()->getParent();
   3407   const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
   3408   const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
   3409   TargetLowering::AsmOperandInfoVector TargetConstraints =
   3410       TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
   3411                             ImmutableCallSite(CI));
   3412   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
   3413     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
   3414 
   3415     // Compute the constraint code and ConstraintType to use.
   3416     TLI->ComputeConstraintToUse(OpInfo, SDValue());
   3417 
   3418     // If this asm operand is our Value*, and if it isn't an indirect memory
   3419     // operand, we can't fold it!
   3420     if (OpInfo.CallOperandVal == OpVal &&
   3421         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
   3422          !OpInfo.isIndirect))
   3423       return false;
   3424   }
   3425 
   3426   return true;
   3427 }
   3428 
   3429 /// Recursively walk all the uses of I until we find a memory use.
   3430 /// If we find an obviously non-foldable instruction, return true.
   3431 /// Add the ultimately found memory instructions to MemoryUses.
   3432 static bool FindAllMemoryUses(
   3433     Instruction *I,
   3434     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
   3435     SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
   3436   // If we already considered this instruction, we're done.
   3437   if (!ConsideredInsts.insert(I).second)
   3438     return false;
   3439 
   3440   // If this is an obviously unfoldable instruction, bail out.
   3441   if (!MightBeFoldableInst(I))
   3442     return true;
   3443 
   3444   // Loop over all the uses, recursively processing them.
   3445   for (Use &U : I->uses()) {
   3446     Instruction *UserI = cast<Instruction>(U.getUser());
   3447 
   3448     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
   3449       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
   3450       continue;
   3451     }
   3452 
   3453     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
   3454       unsigned opNo = U.getOperandNo();
   3455       if (opNo == 0) return true; // Storing addr, not into addr.
   3456       MemoryUses.push_back(std::make_pair(SI, opNo));
   3457       continue;
   3458     }
   3459 
   3460     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
   3461       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
   3462       if (!IA) return true;
   3463 
   3464       // If this is a memory operand, we're cool, otherwise bail out.
   3465       if (!IsOperandAMemoryOperand(CI, IA, I, TM))
   3466         return true;
   3467       continue;
   3468     }
   3469 
   3470     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
   3471       return true;
   3472   }
   3473 
   3474   return false;
   3475 }
   3476 
   3477 /// Return true if Val is already known to be live at the use site that we're
   3478 /// folding it into. If so, there is no cost to include it in the addressing
   3479 /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
   3480 /// instruction already.
   3481 bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
   3482                                                    Value *KnownLive2) {
   3483   // If Val is either of the known-live values, we know it is live!
   3484   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
   3485     return true;
   3486 
   3487   // All values other than instructions and arguments (e.g. constants) are live.
   3488   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
   3489 
   3490   // If Val is a constant sized alloca in the entry block, it is live, this is
   3491   // true because it is just a reference to the stack/frame pointer, which is
   3492   // live for the whole function.
   3493   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
   3494     if (AI->isStaticAlloca())
   3495       return true;
   3496 
   3497   // Check to see if this value is already used in the memory instruction's
   3498   // block.  If so, it's already live into the block at the very least, so we
   3499   // can reasonably fold it.
   3500   return Val->isUsedInBasicBlock(MemoryInst->getParent());
   3501 }
   3502 
   3503 /// It is possible for the addressing mode of the machine to fold the specified
   3504 /// instruction into a load or store that ultimately uses it.
   3505 /// However, the specified instruction has multiple uses.
   3506 /// Given this, it may actually increase register pressure to fold it
   3507 /// into the load. For example, consider this code:
   3508 ///
   3509 ///     X = ...
   3510 ///     Y = X+1
   3511 ///     use(Y)   -> nonload/store
   3512 ///     Z = Y+1
   3513 ///     load Z
   3514 ///
   3515 /// In this case, Y has multiple uses, and can be folded into the load of Z
   3516 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
   3517 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
   3518 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
   3519 /// number of computations either.
   3520 ///
   3521 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
   3522 /// X was live across 'load Z' for other reasons, we actually *would* want to
   3523 /// fold the addressing mode in the Z case.  This would make Y die earlier.
   3524 bool AddressingModeMatcher::
   3525 isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
   3526                                      ExtAddrMode &AMAfter) {
   3527   if (IgnoreProfitability) return true;
   3528 
   3529   // AMBefore is the addressing mode before this instruction was folded into it,
   3530   // and AMAfter is the addressing mode after the instruction was folded.  Get
   3531   // the set of registers referenced by AMAfter and subtract out those
   3532   // referenced by AMBefore: this is the set of values which folding in this
   3533   // address extends the lifetime of.
   3534   //
   3535   // Note that there are only two potential values being referenced here,
   3536   // BaseReg and ScaleReg (global addresses are always available, as are any
   3537   // folded immediates).
   3538   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
   3539 
   3540   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
   3541   // lifetime wasn't extended by adding this instruction.
   3542   if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
   3543     BaseReg = nullptr;
   3544   if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
   3545     ScaledReg = nullptr;
   3546 
   3547   // If folding this instruction (and it's subexprs) didn't extend any live
   3548   // ranges, we're ok with it.
   3549   if (!BaseReg && !ScaledReg)
   3550     return true;
   3551 
   3552   // If all uses of this instruction are ultimately load/store/inlineasm's,
   3553   // check to see if their addressing modes will include this instruction.  If
   3554   // so, we can fold it into all uses, so it doesn't matter if it has multiple
   3555   // uses.
   3556   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
   3557   SmallPtrSet<Instruction*, 16> ConsideredInsts;
   3558   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
   3559     return false;  // Has a non-memory, non-foldable use!
   3560 
   3561   // Now that we know that all uses of this instruction are part of a chain of
   3562   // computation involving only operations that could theoretically be folded
   3563   // into a memory use, loop over each of these uses and see if they could
   3564   // *actually* fold the instruction.
   3565   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
   3566   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
   3567     Instruction *User = MemoryUses[i].first;
   3568     unsigned OpNo = MemoryUses[i].second;
   3569 
   3570     // Get the access type of this use.  If the use isn't a pointer, we don't
   3571     // know what it accesses.
   3572     Value *Address = User->getOperand(OpNo);
   3573     PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
   3574     if (!AddrTy)
   3575       return false;
   3576     Type *AddressAccessTy = AddrTy->getElementType();
   3577     unsigned AS = AddrTy->getAddressSpace();
   3578 
   3579     // Do a match against the root of this address, ignoring profitability. This
   3580     // will tell us if the addressing mode for the memory operation will
   3581     // *actually* cover the shared instruction.
   3582     ExtAddrMode Result;
   3583     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
   3584         TPT.getRestorationPoint();
   3585     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
   3586                                   MemoryInst, Result, InsertedInsts,
   3587                                   PromotedInsts, TPT);
   3588     Matcher.IgnoreProfitability = true;
   3589     bool Success = Matcher.matchAddr(Address, 0);
   3590     (void)Success; assert(Success && "Couldn't select *anything*?");
   3591 
   3592     // The match was to check the profitability, the changes made are not
   3593     // part of the original matcher. Therefore, they should be dropped
   3594     // otherwise the original matcher will not present the right state.
   3595     TPT.rollback(LastKnownGood);
   3596 
   3597     // If the match didn't cover I, then it won't be shared by it.
   3598     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
   3599                   I) == MatchedAddrModeInsts.end())
   3600       return false;
   3601 
   3602     MatchedAddrModeInsts.clear();
   3603   }
   3604 
   3605   return true;
   3606 }
   3607 
   3608 } // end anonymous namespace
   3609 
   3610 /// Return true if the specified values are defined in a
   3611 /// different basic block than BB.
   3612 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
   3613   if (Instruction *I = dyn_cast<Instruction>(V))
   3614     return I->getParent() != BB;
   3615   return false;
   3616 }
   3617 
   3618 /// Load and Store Instructions often have addressing modes that can do
   3619 /// significant amounts of computation. As such, instruction selection will try
   3620 /// to get the load or store to do as much computation as possible for the
   3621 /// program. The problem is that isel can only see within a single block. As
   3622 /// such, we sink as much legal addressing mode work into the block as possible.
   3623 ///
   3624 /// This method is used to optimize both load/store and inline asms with memory
   3625 /// operands.
   3626 bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
   3627                                         Type *AccessTy, unsigned AddrSpace) {
   3628   Value *Repl = Addr;
   3629 
   3630   // Try to collapse single-value PHI nodes.  This is necessary to undo
   3631   // unprofitable PRE transformations.
   3632   SmallVector<Value*, 8> worklist;
   3633   SmallPtrSet<Value*, 16> Visited;
   3634   worklist.push_back(Addr);
   3635 
   3636   // Use a worklist to iteratively look through PHI nodes, and ensure that
   3637   // the addressing mode obtained from the non-PHI roots of the graph
   3638   // are equivalent.
   3639   Value *Consensus = nullptr;
   3640   unsigned NumUsesConsensus = 0;
   3641   bool IsNumUsesConsensusValid = false;
   3642   SmallVector<Instruction*, 16> AddrModeInsts;
   3643   ExtAddrMode AddrMode;
   3644   TypePromotionTransaction TPT;
   3645   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
   3646       TPT.getRestorationPoint();
   3647   while (!worklist.empty()) {
   3648     Value *V = worklist.back();
   3649     worklist.pop_back();
   3650 
   3651     // Break use-def graph loops.
   3652     if (!Visited.insert(V).second) {
   3653       Consensus = nullptr;
   3654       break;
   3655     }
   3656 
   3657     // For a PHI node, push all of its incoming values.
   3658     if (PHINode *P = dyn_cast<PHINode>(V)) {
   3659       for (Value *IncValue : P->incoming_values())
   3660         worklist.push_back(IncValue);
   3661       continue;
   3662     }
   3663 
   3664     // For non-PHIs, determine the addressing mode being computed.
   3665     SmallVector<Instruction*, 16> NewAddrModeInsts;
   3666     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
   3667       V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
   3668       InsertedInsts, PromotedInsts, TPT);
   3669 
   3670     // This check is broken into two cases with very similar code to avoid using
   3671     // getNumUses() as much as possible. Some values have a lot of uses, so
   3672     // calling getNumUses() unconditionally caused a significant compile-time
   3673     // regression.
   3674     if (!Consensus) {
   3675       Consensus = V;
   3676       AddrMode = NewAddrMode;
   3677       AddrModeInsts = NewAddrModeInsts;
   3678       continue;
   3679     } else if (NewAddrMode == AddrMode) {
   3680       if (!IsNumUsesConsensusValid) {
   3681         NumUsesConsensus = Consensus->getNumUses();
   3682         IsNumUsesConsensusValid = true;
   3683       }
   3684 
   3685       // Ensure that the obtained addressing mode is equivalent to that obtained
   3686       // for all other roots of the PHI traversal.  Also, when choosing one
   3687       // such root as representative, select the one with the most uses in order
   3688       // to keep the cost modeling heuristics in AddressingModeMatcher
   3689       // applicable.
   3690       unsigned NumUses = V->getNumUses();
   3691       if (NumUses > NumUsesConsensus) {
   3692         Consensus = V;
   3693         NumUsesConsensus = NumUses;
   3694         AddrModeInsts = NewAddrModeInsts;
   3695       }
   3696       continue;
   3697     }
   3698 
   3699     Consensus = nullptr;
   3700     break;
   3701   }
   3702 
   3703   // If the addressing mode couldn't be determined, or if multiple different
   3704   // ones were determined, bail out now.
   3705   if (!Consensus) {
   3706     TPT.rollback(LastKnownGood);
   3707     return false;
   3708   }
   3709   TPT.commit();
   3710 
   3711   // Check to see if any of the instructions supersumed by this addr mode are
   3712   // non-local to I's BB.
   3713   bool AnyNonLocal = false;
   3714   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
   3715     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
   3716       AnyNonLocal = true;
   3717       break;
   3718     }
   3719   }
   3720 
   3721   // If all the instructions matched are already in this BB, don't do anything.
   3722   if (!AnyNonLocal) {
   3723     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
   3724     return false;
   3725   }
   3726 
   3727   // Insert this computation right after this user.  Since our caller is
   3728   // scanning from the top of the BB to the bottom, reuse of the expr are
   3729   // guaranteed to happen later.
   3730   IRBuilder<> Builder(MemoryInst);
   3731 
   3732   // Now that we determined the addressing expression we want to use and know
   3733   // that we have to sink it into this block.  Check to see if we have already
   3734   // done this for some other load/store instr in this block.  If so, reuse the
   3735   // computation.
   3736   Value *&SunkAddr = SunkAddrs[Addr];
   3737   if (SunkAddr) {
   3738     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
   3739                  << *MemoryInst << "\n");
   3740     if (SunkAddr->getType() != Addr->getType())
   3741       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
   3742   } else if (AddrSinkUsingGEPs ||
   3743              (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
   3744               TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
   3745                   ->useAA())) {
   3746     // By default, we use the GEP-based method when AA is used later. This
   3747     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
   3748     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
   3749                  << *MemoryInst << "\n");
   3750     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
   3751     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
   3752 
   3753     // First, find the pointer.
   3754     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
   3755       ResultPtr = AddrMode.BaseReg;
   3756       AddrMode.BaseReg = nullptr;
   3757     }
   3758 
   3759     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
   3760       // We can't add more than one pointer together, nor can we scale a
   3761       // pointer (both of which seem meaningless).
   3762       if (ResultPtr || AddrMode.Scale != 1)
   3763         return false;
   3764 
   3765       ResultPtr = AddrMode.ScaledReg;
   3766       AddrMode.Scale = 0;
   3767     }
   3768 
   3769     if (AddrMode.BaseGV) {
   3770       if (ResultPtr)
   3771         return false;
   3772 
   3773       ResultPtr = AddrMode.BaseGV;
   3774     }
   3775 
   3776     // If the real base value actually came from an inttoptr, then the matcher
   3777     // will look through it and provide only the integer value. In that case,
   3778     // use it here.
   3779     if (!ResultPtr && AddrMode.BaseReg) {
   3780       ResultPtr =
   3781         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
   3782       AddrMode.BaseReg = nullptr;
   3783     } else if (!ResultPtr && AddrMode.Scale == 1) {
   3784       ResultPtr =
   3785         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
   3786       AddrMode.Scale = 0;
   3787     }
   3788 
   3789     if (!ResultPtr &&
   3790         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
   3791       SunkAddr = Constant::getNullValue(Addr->getType());
   3792     } else if (!ResultPtr) {
   3793       return false;
   3794     } else {
   3795       Type *I8PtrTy =
   3796           Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
   3797       Type *I8Ty = Builder.getInt8Ty();
   3798 
   3799       // Start with the base register. Do this first so that subsequent address
   3800       // matching finds it last, which will prevent it from trying to match it
   3801       // as the scaled value in case it happens to be a mul. That would be
   3802       // problematic if we've sunk a different mul for the scale, because then
   3803       // we'd end up sinking both muls.
   3804       if (AddrMode.BaseReg) {
   3805         Value *V = AddrMode.BaseReg;
   3806         if (V->getType() != IntPtrTy)
   3807           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
   3808 
   3809         ResultIndex = V;
   3810       }
   3811 
   3812       // Add the scale value.
   3813       if (AddrMode.Scale) {
   3814         Value *V = AddrMode.ScaledReg;
   3815         if (V->getType() == IntPtrTy) {
   3816           // done.
   3817         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
   3818                    cast<IntegerType>(V->getType())->getBitWidth()) {
   3819           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
   3820         } else {
   3821           // It is only safe to sign extend the BaseReg if we know that the math
   3822           // required to create it did not overflow before we extend it. Since
   3823           // the original IR value was tossed in favor of a constant back when
   3824           // the AddrMode was created we need to bail out gracefully if widths
   3825           // do not match instead of extending it.
   3826           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
   3827           if (I && (ResultIndex != AddrMode.BaseReg))
   3828             I->eraseFromParent();
   3829           return false;
   3830         }
   3831 
   3832         if (AddrMode.Scale != 1)
   3833           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
   3834                                 "sunkaddr");
   3835         if (ResultIndex)
   3836           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
   3837         else
   3838           ResultIndex = V;
   3839       }
   3840 
   3841       // Add in the Base Offset if present.
   3842       if (AddrMode.BaseOffs) {
   3843         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
   3844         if (ResultIndex) {
   3845           // We need to add this separately from the scale above to help with
   3846           // SDAG consecutive load/store merging.
   3847           if (ResultPtr->getType() != I8PtrTy)
   3848             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
   3849           ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
   3850         }
   3851 
   3852         ResultIndex = V;
   3853       }
   3854 
   3855       if (!ResultIndex) {
   3856         SunkAddr = ResultPtr;
   3857       } else {
   3858         if (ResultPtr->getType() != I8PtrTy)
   3859           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
   3860         SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
   3861       }
   3862 
   3863       if (SunkAddr->getType() != Addr->getType())
   3864         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
   3865     }
   3866   } else {
   3867     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
   3868                  << *MemoryInst << "\n");
   3869     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
   3870     Value *Result = nullptr;
   3871 
   3872     // Start with the base register. Do this first so that subsequent address
   3873     // matching finds it last, which will prevent it from trying to match it
   3874     // as the scaled value in case it happens to be a mul. That would be
   3875     // problematic if we've sunk a different mul for the scale, because then
   3876     // we'd end up sinking both muls.
   3877     if (AddrMode.BaseReg) {
   3878       Value *V = AddrMode.BaseReg;
   3879       if (V->getType()->isPointerTy())
   3880         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
   3881       if (V->getType() != IntPtrTy)
   3882         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
   3883       Result = V;
   3884     }
   3885 
   3886     // Add the scale value.
   3887     if (AddrMode.Scale) {
   3888       Value *V = AddrMode.ScaledReg;
   3889       if (V->getType() == IntPtrTy) {
   3890         // done.
   3891       } else if (V->getType()->isPointerTy()) {
   3892         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
   3893       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
   3894                  cast<IntegerType>(V->getType())->getBitWidth()) {
   3895         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
   3896       } else {
   3897         // It is only safe to sign extend the BaseReg if we know that the math
   3898         // required to create it did not overflow before we extend it. Since
   3899         // the original IR value was tossed in favor of a constant back when
   3900         // the AddrMode was created we need to bail out gracefully if widths
   3901         // do not match instead of extending it.
   3902         Instruction *I = dyn_cast_or_null<Instruction>(Result);
   3903         if (I && (Result != AddrMode.BaseReg))
   3904           I->eraseFromParent();
   3905         return false;
   3906       }
   3907       if (AddrMode.Scale != 1)
   3908         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
   3909                               "sunkaddr");
   3910       if (Result)
   3911         Result = Builder.CreateAdd(Result, V, "sunkaddr");
   3912       else
   3913         Result = V;
   3914     }
   3915 
   3916     // Add in the BaseGV if present.
   3917     if (AddrMode.BaseGV) {
   3918       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
   3919       if (Result)
   3920         Result = Builder.CreateAdd(Result, V, "sunkaddr");
   3921       else
   3922         Result = V;
   3923     }
   3924 
   3925     // Add in the Base Offset if present.
   3926     if (AddrMode.BaseOffs) {
   3927       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
   3928       if (Result)
   3929         Result = Builder.CreateAdd(Result, V, "sunkaddr");
   3930       else
   3931         Result = V;
   3932     }
   3933 
   3934     if (!Result)
   3935       SunkAddr = Constant::getNullValue(Addr->getType());
   3936     else
   3937       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
   3938   }
   3939 
   3940   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
   3941 
   3942   // If we have no uses, recursively delete the value and all dead instructions
   3943   // using it.
   3944   if (Repl->use_empty()) {
   3945     // This can cause recursive deletion, which can invalidate our iterator.
   3946     // Use a WeakVH to hold onto it in case this happens.
   3947     WeakVH IterHandle(&*CurInstIterator);
   3948     BasicBlock *BB = CurInstIterator->getParent();
   3949 
   3950     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
   3951 
   3952     if (IterHandle != CurInstIterator.getNodePtrUnchecked()) {
   3953       // If the iterator instruction was recursively deleted, start over at the
   3954       // start of the block.
   3955       CurInstIterator = BB->begin();
   3956       SunkAddrs.clear();
   3957     }
   3958   }
   3959   ++NumMemoryInsts;
   3960   return true;
   3961 }
   3962 
   3963 /// If there are any memory operands, use OptimizeMemoryInst to sink their
   3964 /// address computing into the block when possible / profitable.
   3965 bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
   3966   bool MadeChange = false;
   3967 
   3968   const TargetRegisterInfo *TRI =
   3969       TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
   3970   TargetLowering::AsmOperandInfoVector TargetConstraints =
   3971       TLI->ParseConstraints(*DL, TRI, CS);
   3972   unsigned ArgNo = 0;
   3973   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
   3974     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
   3975 
   3976     // Compute the constraint code and ConstraintType to use.
   3977     TLI->ComputeConstraintToUse(OpInfo, SDValue());
   3978 
   3979     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
   3980         OpInfo.isIndirect) {
   3981       Value *OpVal = CS->getArgOperand(ArgNo++);
   3982       MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
   3983     } else if (OpInfo.Type == InlineAsm::isInput)
   3984       ArgNo++;
   3985   }
   3986 
   3987   return MadeChange;
   3988 }
   3989 
   3990 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
   3991 /// sign extensions.
   3992 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
   3993   assert(!Inst->use_empty() && "Input must have at least one use");
   3994   const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
   3995   bool IsSExt = isa<SExtInst>(FirstUser);
   3996   Type *ExtTy = FirstUser->getType();
   3997   for (const User *U : Inst->users()) {
   3998     const Instruction *UI = cast<Instruction>(U);
   3999     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
   4000       return false;
   4001     Type *CurTy = UI->getType();
   4002     // Same input and output types: Same instruction after CSE.
   4003     if (CurTy == ExtTy)
   4004       continue;
   4005 
   4006     // If IsSExt is true, we are in this situation:
   4007     // a = Inst
   4008     // b = sext ty1 a to ty2
   4009     // c = sext ty1 a to ty3
   4010     // Assuming ty2 is shorter than ty3, this could be turned into:
   4011     // a = Inst
   4012     // b = sext ty1 a to ty2
   4013     // c = sext ty2 b to ty3
   4014     // However, the last sext is not free.
   4015     if (IsSExt)
   4016       return false;
   4017 
   4018     // This is a ZExt, maybe this is free to extend from one type to another.
   4019     // In that case, we would not account for a different use.
   4020     Type *NarrowTy;
   4021     Type *LargeTy;
   4022     if (ExtTy->getScalarType()->getIntegerBitWidth() >
   4023         CurTy->getScalarType()->getIntegerBitWidth()) {
   4024       NarrowTy = CurTy;
   4025       LargeTy = ExtTy;
   4026     } else {
   4027       NarrowTy = ExtTy;
   4028       LargeTy = CurTy;
   4029     }
   4030 
   4031     if (!TLI.isZExtFree(NarrowTy, LargeTy))
   4032       return false;
   4033   }
   4034   // All uses are the same or can be derived from one another for free.
   4035   return true;
   4036 }
   4037 
   4038 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
   4039 /// load instruction.
   4040 /// If an ext(load) can be formed, it is returned via \p LI for the load
   4041 /// and \p Inst for the extension.
   4042 /// Otherwise LI == nullptr and Inst == nullptr.
   4043 /// When some promotion happened, \p TPT contains the proper state to
   4044 /// revert them.
   4045 ///
   4046 /// \return true when promoting was necessary to expose the ext(load)
   4047 /// opportunity, false otherwise.
   4048 ///
   4049 /// Example:
   4050 /// \code
   4051 /// %ld = load i32* %addr
   4052 /// %add = add nuw i32 %ld, 4
   4053 /// %zext = zext i32 %add to i64
   4054 /// \endcode
   4055 /// =>
   4056 /// \code
   4057 /// %ld = load i32* %addr
   4058 /// %zext = zext i32 %ld to i64
   4059 /// %add = add nuw i64 %zext, 4
   4060 /// \encode
   4061 /// Thanks to the promotion, we can match zext(load i32*) to i64.
   4062 bool CodeGenPrepare::extLdPromotion(TypePromotionTransaction &TPT,
   4063                                     LoadInst *&LI, Instruction *&Inst,
   4064                                     const SmallVectorImpl<Instruction *> &Exts,
   4065                                     unsigned CreatedInstsCost = 0) {
   4066   // Iterate over all the extensions to see if one form an ext(load).
   4067   for (auto I : Exts) {
   4068     // Check if we directly have ext(load).
   4069     if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
   4070       Inst = I;
   4071       // No promotion happened here.
   4072       return false;
   4073     }
   4074     // Check whether or not we want to do any promotion.
   4075     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
   4076       continue;
   4077     // Get the action to perform the promotion.
   4078     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
   4079         I, InsertedInsts, *TLI, PromotedInsts);
   4080     // Check if we can promote.
   4081     if (!TPH)
   4082       continue;
   4083     // Save the current state.
   4084     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
   4085         TPT.getRestorationPoint();
   4086     SmallVector<Instruction *, 4> NewExts;
   4087     unsigned NewCreatedInstsCost = 0;
   4088     unsigned ExtCost = !TLI->isExtFree(I);
   4089     // Promote.
   4090     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
   4091                              &NewExts, nullptr, *TLI);
   4092     assert(PromotedVal &&
   4093            "TypePromotionHelper should have filtered out those cases");
   4094 
   4095     // We would be able to merge only one extension in a load.
   4096     // Therefore, if we have more than 1 new extension we heuristically
   4097     // cut this search path, because it means we degrade the code quality.
   4098     // With exactly 2, the transformation is neutral, because we will merge
   4099     // one extension but leave one. However, we optimistically keep going,
   4100     // because the new extension may be removed too.
   4101     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
   4102     TotalCreatedInstsCost -= ExtCost;
   4103     if (!StressExtLdPromotion &&
   4104         (TotalCreatedInstsCost > 1 ||
   4105          !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
   4106       // The promotion is not profitable, rollback to the previous state.
   4107       TPT.rollback(LastKnownGood);
   4108       continue;
   4109     }
   4110     // The promotion is profitable.
   4111     // Check if it exposes an ext(load).
   4112     (void)extLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
   4113     if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
   4114                // If we have created a new extension, i.e., now we have two
   4115                // extensions. We must make sure one of them is merged with
   4116                // the load, otherwise we may degrade the code quality.
   4117                (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
   4118       // Promotion happened.
   4119       return true;
   4120     // If this does not help to expose an ext(load) then, rollback.
   4121     TPT.rollback(LastKnownGood);
   4122   }
   4123   // None of the extension can form an ext(load).
   4124   LI = nullptr;
   4125   Inst = nullptr;
   4126   return false;
   4127 }
   4128 
   4129 /// Move a zext or sext fed by a load into the same basic block as the load,
   4130 /// unless conditions are unfavorable. This allows SelectionDAG to fold the
   4131 /// extend into the load.
   4132 /// \p I[in/out] the extension may be modified during the process if some
   4133 /// promotions apply.
   4134 ///
   4135 bool CodeGenPrepare::moveExtToFormExtLoad(Instruction *&I) {
   4136   // Try to promote a chain of computation if it allows to form
   4137   // an extended load.
   4138   TypePromotionTransaction TPT;
   4139   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
   4140     TPT.getRestorationPoint();
   4141   SmallVector<Instruction *, 1> Exts;
   4142   Exts.push_back(I);
   4143   // Look for a load being extended.
   4144   LoadInst *LI = nullptr;
   4145   Instruction *OldExt = I;
   4146   bool HasPromoted = extLdPromotion(TPT, LI, I, Exts);
   4147   if (!LI || !I) {
   4148     assert(!HasPromoted && !LI && "If we did not match any load instruction "
   4149                                   "the code must remain the same");
   4150     I = OldExt;
   4151     return false;
   4152   }
   4153 
   4154   // If they're already in the same block, there's nothing to do.
   4155   // Make the cheap checks first if we did not promote.
   4156   // If we promoted, we need to check if it is indeed profitable.
   4157   if (!HasPromoted && LI->getParent() == I->getParent())
   4158     return false;
   4159 
   4160   EVT VT = TLI->getValueType(*DL, I->getType());
   4161   EVT LoadVT = TLI->getValueType(*DL, LI->getType());
   4162 
   4163   // If the load has other users and the truncate is not free, this probably
   4164   // isn't worthwhile.
   4165   if (!LI->hasOneUse() && TLI &&
   4166       (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
   4167       !TLI->isTruncateFree(I->getType(), LI->getType())) {
   4168     I = OldExt;
   4169     TPT.rollback(LastKnownGood);
   4170     return false;
   4171   }
   4172 
   4173   // Check whether the target supports casts folded into loads.
   4174   unsigned LType;
   4175   if (isa<ZExtInst>(I))
   4176     LType = ISD::ZEXTLOAD;
   4177   else {
   4178     assert(isa<SExtInst>(I) && "Unexpected ext type!");
   4179     LType = ISD::SEXTLOAD;
   4180   }
   4181   if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
   4182     I = OldExt;
   4183     TPT.rollback(LastKnownGood);
   4184     return false;
   4185   }
   4186 
   4187   // Move the extend into the same block as the load, so that SelectionDAG
   4188   // can fold it.
   4189   TPT.commit();
   4190   I->removeFromParent();
   4191   I->insertAfter(LI);
   4192   ++NumExtsMoved;
   4193   return true;
   4194 }
   4195 
   4196 bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
   4197   BasicBlock *DefBB = I->getParent();
   4198 
   4199   // If the result of a {s|z}ext and its source are both live out, rewrite all
   4200   // other uses of the source with result of extension.
   4201   Value *Src = I->getOperand(0);
   4202   if (Src->hasOneUse())
   4203     return false;
   4204 
   4205   // Only do this xform if truncating is free.
   4206   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
   4207     return false;
   4208 
   4209   // Only safe to perform the optimization if the source is also defined in
   4210   // this block.
   4211   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
   4212     return false;
   4213 
   4214   bool DefIsLiveOut = false;
   4215   for (User *U : I->users()) {
   4216     Instruction *UI = cast<Instruction>(U);
   4217 
   4218     // Figure out which BB this ext is used in.
   4219     BasicBlock *UserBB = UI->getParent();
   4220     if (UserBB == DefBB) continue;
   4221     DefIsLiveOut = true;
   4222     break;
   4223   }
   4224   if (!DefIsLiveOut)
   4225     return false;
   4226 
   4227   // Make sure none of the uses are PHI nodes.
   4228   for (User *U : Src->users()) {
   4229     Instruction *UI = cast<Instruction>(U);
   4230     BasicBlock *UserBB = UI->getParent();
   4231     if (UserBB == DefBB) continue;
   4232     // Be conservative. We don't want this xform to end up introducing
   4233     // reloads just before load / store instructions.
   4234     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
   4235       return false;
   4236   }
   4237 
   4238   // InsertedTruncs - Only insert one trunc in each block once.
   4239   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
   4240 
   4241   bool MadeChange = false;
   4242   for (Use &U : Src->uses()) {
   4243     Instruction *User = cast<Instruction>(U.getUser());
   4244 
   4245     // Figure out which BB this ext is used in.
   4246     BasicBlock *UserBB = User->getParent();
   4247     if (UserBB == DefBB) continue;
   4248 
   4249     // Both src and def are live in this block. Rewrite the use.
   4250     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
   4251 
   4252     if (!InsertedTrunc) {
   4253       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
   4254       assert(InsertPt != UserBB->end());
   4255       InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
   4256       InsertedInsts.insert(InsertedTrunc);
   4257     }
   4258 
   4259     // Replace a use of the {s|z}ext source with a use of the result.
   4260     U = InsertedTrunc;
   4261     ++NumExtUses;
   4262     MadeChange = true;
   4263   }
   4264 
   4265   return MadeChange;
   4266 }
   4267 
   4268 // Find loads whose uses only use some of the loaded value's bits.  Add an "and"
   4269 // just after the load if the target can fold this into one extload instruction,
   4270 // with the hope of eliminating some of the other later "and" instructions using
   4271 // the loaded value.  "and"s that are made trivially redundant by the insertion
   4272 // of the new "and" are removed by this function, while others (e.g. those whose
   4273 // path from the load goes through a phi) are left for isel to potentially
   4274 // remove.
   4275 //
   4276 // For example:
   4277 //
   4278 // b0:
   4279 //   x = load i32
   4280 //   ...
   4281 // b1:
   4282 //   y = and x, 0xff
   4283 //   z = use y
   4284 //
   4285 // becomes:
   4286 //
   4287 // b0:
   4288 //   x = load i32
   4289 //   x' = and x, 0xff
   4290 //   ...
   4291 // b1:
   4292 //   z = use x'
   4293 //
   4294 // whereas:
   4295 //
   4296 // b0:
   4297 //   x1 = load i32
   4298 //   ...
   4299 // b1:
   4300 //   x2 = load i32
   4301 //   ...
   4302 // b2:
   4303 //   x = phi x1, x2
   4304 //   y = and x, 0xff
   4305 //
   4306 // becomes (after a call to optimizeLoadExt for each load):
   4307 //
   4308 // b0:
   4309 //   x1 = load i32
   4310 //   x1' = and x1, 0xff
   4311 //   ...
   4312 // b1:
   4313 //   x2 = load i32
   4314 //   x2' = and x2, 0xff
   4315 //   ...
   4316 // b2:
   4317 //   x = phi x1', x2'
   4318 //   y = and x, 0xff
   4319 //
   4320 
   4321 bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
   4322 
   4323   if (!Load->isSimple() ||
   4324       !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
   4325     return false;
   4326 
   4327   // Skip loads we've already transformed or have no reason to transform.
   4328   if (Load->hasOneUse()) {
   4329     User *LoadUser = *Load->user_begin();
   4330     if (cast<Instruction>(LoadUser)->getParent() == Load->getParent() &&
   4331         !dyn_cast<PHINode>(LoadUser))
   4332       return false;
   4333   }
   4334 
   4335   // Look at all uses of Load, looking through phis, to determine how many bits
   4336   // of the loaded value are needed.
   4337   SmallVector<Instruction *, 8> WorkList;
   4338   SmallPtrSet<Instruction *, 16> Visited;
   4339   SmallVector<Instruction *, 8> AndsToMaybeRemove;
   4340   for (auto *U : Load->users())
   4341     WorkList.push_back(cast<Instruction>(U));
   4342 
   4343   EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
   4344   unsigned BitWidth = LoadResultVT.getSizeInBits();
   4345   APInt DemandBits(BitWidth, 0);
   4346   APInt WidestAndBits(BitWidth, 0);
   4347 
   4348   while (!WorkList.empty()) {
   4349     Instruction *I = WorkList.back();
   4350     WorkList.pop_back();
   4351 
   4352     // Break use-def graph loops.
   4353     if (!Visited.insert(I).second)
   4354       continue;
   4355 
   4356     // For a PHI node, push all of its users.
   4357     if (auto *Phi = dyn_cast<PHINode>(I)) {
   4358       for (auto *U : Phi->users())
   4359         WorkList.push_back(cast<Instruction>(U));
   4360       continue;
   4361     }
   4362 
   4363     switch (I->getOpcode()) {
   4364     case llvm::Instruction::And: {
   4365       auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
   4366       if (!AndC)
   4367         return false;
   4368       APInt AndBits = AndC->getValue();
   4369       DemandBits |= AndBits;
   4370       // Keep track of the widest and mask we see.
   4371       if (AndBits.ugt(WidestAndBits))
   4372         WidestAndBits = AndBits;
   4373       if (AndBits == WidestAndBits && I->getOperand(0) == Load)
   4374         AndsToMaybeRemove.push_back(I);
   4375       break;
   4376     }
   4377 
   4378     case llvm::Instruction::Shl: {
   4379       auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
   4380       if (!ShlC)
   4381         return false;
   4382       uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
   4383       auto ShlDemandBits = APInt::getAllOnesValue(BitWidth).lshr(ShiftAmt);
   4384       DemandBits |= ShlDemandBits;
   4385       break;
   4386     }
   4387 
   4388     case llvm::Instruction::Trunc: {
   4389       EVT TruncVT = TLI->getValueType(*DL, I->getType());
   4390       unsigned TruncBitWidth = TruncVT.getSizeInBits();
   4391       auto TruncBits = APInt::getAllOnesValue(TruncBitWidth).zext(BitWidth);
   4392       DemandBits |= TruncBits;
   4393       break;
   4394     }
   4395 
   4396     default:
   4397       return false;
   4398     }
   4399   }
   4400 
   4401   uint32_t ActiveBits = DemandBits.getActiveBits();
   4402   // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
   4403   // target even if isLoadExtLegal says an i1 EXTLOAD is valid.  For example,
   4404   // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
   4405   // (and (load x) 1) is not matched as a single instruction, rather as a LDR
   4406   // followed by an AND.
   4407   // TODO: Look into removing this restriction by fixing backends to either
   4408   // return false for isLoadExtLegal for i1 or have them select this pattern to
   4409   // a single instruction.
   4410   //
   4411   // Also avoid hoisting if we didn't see any ands with the exact DemandBits
   4412   // mask, since these are the only ands that will be removed by isel.
   4413   if (ActiveBits <= 1 || !APIntOps::isMask(ActiveBits, DemandBits) ||
   4414       WidestAndBits != DemandBits)
   4415     return false;
   4416 
   4417   LLVMContext &Ctx = Load->getType()->getContext();
   4418   Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
   4419   EVT TruncVT = TLI->getValueType(*DL, TruncTy);
   4420 
   4421   // Reject cases that won't be matched as extloads.
   4422   if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
   4423       !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
   4424     return false;
   4425 
   4426   IRBuilder<> Builder(Load->getNextNode());
   4427   auto *NewAnd = dyn_cast<Instruction>(
   4428       Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
   4429 
   4430   // Replace all uses of load with new and (except for the use of load in the
   4431   // new and itself).
   4432   Load->replaceAllUsesWith(NewAnd);
   4433   NewAnd->setOperand(0, Load);
   4434 
   4435   // Remove any and instructions that are now redundant.
   4436   for (auto *And : AndsToMaybeRemove)
   4437     // Check that the and mask is the same as the one we decided to put on the
   4438     // new and.
   4439     if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
   4440       And->replaceAllUsesWith(NewAnd);
   4441       if (&*CurInstIterator == And)
   4442         CurInstIterator = std::next(And->getIterator());
   4443       And->eraseFromParent();
   4444       ++NumAndUses;
   4445     }
   4446 
   4447   ++NumAndsAdded;
   4448   return true;
   4449 }
   4450 
   4451 /// Check if V (an operand of a select instruction) is an expensive instruction
   4452 /// that is only used once.
   4453 static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
   4454   auto *I = dyn_cast<Instruction>(V);
   4455   // If it's safe to speculatively execute, then it should not have side
   4456   // effects; therefore, it's safe to sink and possibly *not* execute.
   4457   return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
   4458          TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
   4459 }
   4460 
   4461 /// Returns true if a SelectInst should be turned into an explicit branch.
   4462 static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
   4463                                                 SelectInst *SI) {
   4464   // FIXME: This should use the same heuristics as IfConversion to determine
   4465   // whether a select is better represented as a branch.  This requires that
   4466   // branch probability metadata is preserved for the select, which is not the
   4467   // case currently.
   4468 
   4469   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
   4470 
   4471   // If a branch is predictable, an out-of-order CPU can avoid blocking on its
   4472   // comparison condition. If the compare has more than one use, there's
   4473   // probably another cmov or setcc around, so it's not worth emitting a branch.
   4474   if (!Cmp || !Cmp->hasOneUse())
   4475     return false;
   4476 
   4477   Value *CmpOp0 = Cmp->getOperand(0);
   4478   Value *CmpOp1 = Cmp->getOperand(1);
   4479 
   4480   // Emit "cmov on compare with a memory operand" as a branch to avoid stalls
   4481   // on a load from memory. But if the load is used more than once, do not
   4482   // change the select to a branch because the load is probably needed
   4483   // regardless of whether the branch is taken or not.
   4484   if ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
   4485       (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()))
   4486     return true;
   4487 
   4488   // If either operand of the select is expensive and only needed on one side
   4489   // of the select, we should form a branch.
   4490   if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
   4491       sinkSelectOperand(TTI, SI->getFalseValue()))
   4492     return true;
   4493 
   4494   return false;
   4495 }
   4496 
   4497 
   4498 /// If we have a SelectInst that will likely profit from branch prediction,
   4499 /// turn it into a branch.
   4500 bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
   4501   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
   4502 
   4503   // Can we convert the 'select' to CF ?
   4504   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
   4505     return false;
   4506 
   4507   TargetLowering::SelectSupportKind SelectKind;
   4508   if (VectorCond)
   4509     SelectKind = TargetLowering::VectorMaskSelect;
   4510   else if (SI->getType()->isVectorTy())
   4511     SelectKind = TargetLowering::ScalarCondVectorVal;
   4512   else
   4513     SelectKind = TargetLowering::ScalarValSelect;
   4514 
   4515   // Do we have efficient codegen support for this kind of 'selects' ?
   4516   if (TLI->isSelectSupported(SelectKind)) {
   4517     // We have efficient codegen support for the select instruction.
   4518     // Check if it is profitable to keep this 'select'.
   4519     if (!TLI->isPredictableSelectExpensive() ||
   4520         !isFormingBranchFromSelectProfitable(TTI, SI))
   4521       return false;
   4522   }
   4523 
   4524   ModifiedDT = true;
   4525 
   4526   // Transform a sequence like this:
   4527   //    start:
   4528   //       %cmp = cmp uge i32 %a, %b
   4529   //       %sel = select i1 %cmp, i32 %c, i32 %d
   4530   //
   4531   // Into:
   4532   //    start:
   4533   //       %cmp = cmp uge i32 %a, %b
   4534   //       br i1 %cmp, label %select.true, label %select.false
   4535   //    select.true:
   4536   //       br label %select.end
   4537   //    select.false:
   4538   //       br label %select.end
   4539   //    select.end:
   4540   //       %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
   4541   //
   4542   // In addition, we may sink instructions that produce %c or %d from
   4543   // the entry block into the destination(s) of the new branch.
   4544   // If the true or false blocks do not contain a sunken instruction, that
   4545   // block and its branch may be optimized away. In that case, one side of the
   4546   // first branch will point directly to select.end, and the corresponding PHI
   4547   // predecessor block will be the start block.
   4548 
   4549   // First, we split the block containing the select into 2 blocks.
   4550   BasicBlock *StartBlock = SI->getParent();
   4551   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
   4552   BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
   4553 
   4554   // Delete the unconditional branch that was just created by the split.
   4555   StartBlock->getTerminator()->eraseFromParent();
   4556 
   4557   // These are the new basic blocks for the conditional branch.
   4558   // At least one will become an actual new basic block.
   4559   BasicBlock *TrueBlock = nullptr;
   4560   BasicBlock *FalseBlock = nullptr;
   4561 
   4562   // Sink expensive instructions into the conditional blocks to avoid executing
   4563   // them speculatively.
   4564   if (sinkSelectOperand(TTI, SI->getTrueValue())) {
   4565     TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
   4566                                    EndBlock->getParent(), EndBlock);
   4567     auto *TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
   4568     auto *TrueInst = cast<Instruction>(SI->getTrueValue());
   4569     TrueInst->moveBefore(TrueBranch);
   4570   }
   4571   if (sinkSelectOperand(TTI, SI->getFalseValue())) {
   4572     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
   4573                                     EndBlock->getParent(), EndBlock);
   4574     auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
   4575     auto *FalseInst = cast<Instruction>(SI->getFalseValue());
   4576     FalseInst->moveBefore(FalseBranch);
   4577   }
   4578 
   4579   // If there was nothing to sink, then arbitrarily choose the 'false' side
   4580   // for a new input value to the PHI.
   4581   if (TrueBlock == FalseBlock) {
   4582     assert(TrueBlock == nullptr &&
   4583            "Unexpected basic block transform while optimizing select");
   4584 
   4585     FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
   4586                                     EndBlock->getParent(), EndBlock);
   4587     BranchInst::Create(EndBlock, FalseBlock);
   4588   }
   4589 
   4590   // Insert the real conditional branch based on the original condition.
   4591   // If we did not create a new block for one of the 'true' or 'false' paths
   4592   // of the condition, it means that side of the branch goes to the end block
   4593   // directly and the path originates from the start block from the point of
   4594   // view of the new PHI.
   4595   if (TrueBlock == nullptr) {
   4596     BranchInst::Create(EndBlock, FalseBlock, SI->getCondition(), SI);
   4597     TrueBlock = StartBlock;
   4598   } else if (FalseBlock == nullptr) {
   4599     BranchInst::Create(TrueBlock, EndBlock, SI->getCondition(), SI);
   4600     FalseBlock = StartBlock;
   4601   } else {
   4602     BranchInst::Create(TrueBlock, FalseBlock, SI->getCondition(), SI);
   4603   }
   4604 
   4605   // The select itself is replaced with a PHI Node.
   4606   PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
   4607   PN->takeName(SI);
   4608   PN->addIncoming(SI->getTrueValue(), TrueBlock);
   4609   PN->addIncoming(SI->getFalseValue(), FalseBlock);
   4610 
   4611   SI->replaceAllUsesWith(PN);
   4612   SI->eraseFromParent();
   4613 
   4614   // Instruct OptimizeBlock to skip to the next block.
   4615   CurInstIterator = StartBlock->end();
   4616   ++NumSelectsExpanded;
   4617   return true;
   4618 }
   4619 
   4620 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
   4621   SmallVector<int, 16> Mask(SVI->getShuffleMask());
   4622   int SplatElem = -1;
   4623   for (unsigned i = 0; i < Mask.size(); ++i) {
   4624     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
   4625       return false;
   4626     SplatElem = Mask[i];
   4627   }
   4628 
   4629   return true;
   4630 }
   4631 
   4632 /// Some targets have expensive vector shifts if the lanes aren't all the same
   4633 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
   4634 /// it's often worth sinking a shufflevector splat down to its use so that
   4635 /// codegen can spot all lanes are identical.
   4636 bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
   4637   BasicBlock *DefBB = SVI->getParent();
   4638 
   4639   // Only do this xform if variable vector shifts are particularly expensive.
   4640   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
   4641     return false;
   4642 
   4643   // We only expect better codegen by sinking a shuffle if we can recognise a
   4644   // constant splat.
   4645   if (!isBroadcastShuffle(SVI))
   4646     return false;
   4647 
   4648   // InsertedShuffles - Only insert a shuffle in each block once.
   4649   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
   4650 
   4651   bool MadeChange = false;
   4652   for (User *U : SVI->users()) {
   4653     Instruction *UI = cast<Instruction>(U);
   4654 
   4655     // Figure out which BB this ext is used in.
   4656     BasicBlock *UserBB = UI->getParent();
   4657     if (UserBB == DefBB) continue;
   4658 
   4659     // For now only apply this when the splat is used by a shift instruction.
   4660     if (!UI->isShift()) continue;
   4661 
   4662     // Everything checks out, sink the shuffle if the user's block doesn't
   4663     // already have a copy.
   4664     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
   4665 
   4666     if (!InsertedShuffle) {
   4667       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
   4668       assert(InsertPt != UserBB->end());
   4669       InsertedShuffle =
   4670           new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
   4671                                 SVI->getOperand(2), "", &*InsertPt);
   4672     }
   4673 
   4674     UI->replaceUsesOfWith(SVI, InsertedShuffle);
   4675     MadeChange = true;
   4676   }
   4677 
   4678   // If we removed all uses, nuke the shuffle.
   4679   if (SVI->use_empty()) {
   4680     SVI->eraseFromParent();
   4681     MadeChange = true;
   4682   }
   4683 
   4684   return MadeChange;
   4685 }
   4686 
   4687 bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
   4688   if (!TLI || !DL)
   4689     return false;
   4690 
   4691   Value *Cond = SI->getCondition();
   4692   Type *OldType = Cond->getType();
   4693   LLVMContext &Context = Cond->getContext();
   4694   MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
   4695   unsigned RegWidth = RegType.getSizeInBits();
   4696 
   4697   if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
   4698     return false;
   4699 
   4700   // If the register width is greater than the type width, expand the condition
   4701   // of the switch instruction and each case constant to the width of the
   4702   // register. By widening the type of the switch condition, subsequent
   4703   // comparisons (for case comparisons) will not need to be extended to the
   4704   // preferred register width, so we will potentially eliminate N-1 extends,
   4705   // where N is the number of cases in the switch.
   4706   auto *NewType = Type::getIntNTy(Context, RegWidth);
   4707 
   4708   // Zero-extend the switch condition and case constants unless the switch
   4709   // condition is a function argument that is already being sign-extended.
   4710   // In that case, we can avoid an unnecessary mask/extension by sign-extending
   4711   // everything instead.
   4712   Instruction::CastOps ExtType = Instruction::ZExt;
   4713   if (auto *Arg = dyn_cast<Argument>(Cond))
   4714     if (Arg->hasSExtAttr())
   4715       ExtType = Instruction::SExt;
   4716 
   4717   auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
   4718   ExtInst->insertBefore(SI);
   4719   SI->setCondition(ExtInst);
   4720   for (SwitchInst::CaseIt Case : SI->cases()) {
   4721     APInt NarrowConst = Case.getCaseValue()->getValue();
   4722     APInt WideConst = (ExtType == Instruction::ZExt) ?
   4723                       NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
   4724     Case.setValue(ConstantInt::get(Context, WideConst));
   4725   }
   4726 
   4727   return true;
   4728 }
   4729 
   4730 namespace {
   4731 /// \brief Helper class to promote a scalar operation to a vector one.
   4732 /// This class is used to move downward extractelement transition.
   4733 /// E.g.,
   4734 /// a = vector_op <2 x i32>
   4735 /// b = extractelement <2 x i32> a, i32 0
   4736 /// c = scalar_op b
   4737 /// store c
   4738 ///
   4739 /// =>
   4740 /// a = vector_op <2 x i32>
   4741 /// c = vector_op a (equivalent to scalar_op on the related lane)
   4742 /// * d = extractelement <2 x i32> c, i32 0
   4743 /// * store d
   4744 /// Assuming both extractelement and store can be combine, we get rid of the
   4745 /// transition.
   4746 class VectorPromoteHelper {
   4747   /// DataLayout associated with the current module.
   4748   const DataLayout &DL;
   4749 
   4750   /// Used to perform some checks on the legality of vector operations.
   4751   const TargetLowering &TLI;
   4752 
   4753   /// Used to estimated the cost of the promoted chain.
   4754   const TargetTransformInfo &TTI;
   4755 
   4756   /// The transition being moved downwards.
   4757   Instruction *Transition;
   4758   /// The sequence of instructions to be promoted.
   4759   SmallVector<Instruction *, 4> InstsToBePromoted;
   4760   /// Cost of combining a store and an extract.
   4761   unsigned StoreExtractCombineCost;
   4762   /// Instruction that will be combined with the transition.
   4763   Instruction *CombineInst;
   4764 
   4765   /// \brief The instruction that represents the current end of the transition.
   4766   /// Since we are faking the promotion until we reach the end of the chain
   4767   /// of computation, we need a way to get the current end of the transition.
   4768   Instruction *getEndOfTransition() const {
   4769     if (InstsToBePromoted.empty())
   4770       return Transition;
   4771     return InstsToBePromoted.back();
   4772   }
   4773 
   4774   /// \brief Return the index of the original value in the transition.
   4775   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
   4776   /// c, is at index 0.
   4777   unsigned getTransitionOriginalValueIdx() const {
   4778     assert(isa<ExtractElementInst>(Transition) &&
   4779            "Other kind of transitions are not supported yet");
   4780     return 0;
   4781   }
   4782 
   4783   /// \brief Return the index of the index in the transition.
   4784   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
   4785   /// is at index 1.
   4786   unsigned getTransitionIdx() const {
   4787     assert(isa<ExtractElementInst>(Transition) &&
   4788            "Other kind of transitions are not supported yet");
   4789     return 1;
   4790   }
   4791 
   4792   /// \brief Get the type of the transition.
   4793   /// This is the type of the original value.
   4794   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
   4795   /// transition is <2 x i32>.
   4796   Type *getTransitionType() const {
   4797     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
   4798   }
   4799 
   4800   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
   4801   /// I.e., we have the following sequence:
   4802   /// Def = Transition <ty1> a to <ty2>
   4803   /// b = ToBePromoted <ty2> Def, ...
   4804   /// =>
   4805   /// b = ToBePromoted <ty1> a, ...
   4806   /// Def = Transition <ty1> ToBePromoted to <ty2>
   4807   void promoteImpl(Instruction *ToBePromoted);
   4808 
   4809   /// \brief Check whether or not it is profitable to promote all the
   4810   /// instructions enqueued to be promoted.
   4811   bool isProfitableToPromote() {
   4812     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
   4813     unsigned Index = isa<ConstantInt>(ValIdx)
   4814                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
   4815                          : -1;
   4816     Type *PromotedType = getTransitionType();
   4817 
   4818     StoreInst *ST = cast<StoreInst>(CombineInst);
   4819     unsigned AS = ST->getPointerAddressSpace();
   4820     unsigned Align = ST->getAlignment();
   4821     // Check if this store is supported.
   4822     if (!TLI.allowsMisalignedMemoryAccesses(
   4823             TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
   4824             Align)) {
   4825       // If this is not supported, there is no way we can combine
   4826       // the extract with the store.
   4827       return false;
   4828     }
   4829 
   4830     // The scalar chain of computation has to pay for the transition
   4831     // scalar to vector.
   4832     // The vector chain has to account for the combining cost.
   4833     uint64_t ScalarCost =
   4834         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
   4835     uint64_t VectorCost = StoreExtractCombineCost;
   4836     for (const auto &Inst : InstsToBePromoted) {
   4837       // Compute the cost.
   4838       // By construction, all instructions being promoted are arithmetic ones.
   4839       // Moreover, one argument is a constant that can be viewed as a splat
   4840       // constant.
   4841       Value *Arg0 = Inst->getOperand(0);
   4842       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
   4843                             isa<ConstantFP>(Arg0);
   4844       TargetTransformInfo::OperandValueKind Arg0OVK =
   4845           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
   4846                          : TargetTransformInfo::OK_AnyValue;
   4847       TargetTransformInfo::OperandValueKind Arg1OVK =
   4848           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
   4849                           : TargetTransformInfo::OK_AnyValue;
   4850       ScalarCost += TTI.getArithmeticInstrCost(
   4851           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
   4852       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
   4853                                                Arg0OVK, Arg1OVK);
   4854     }
   4855     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
   4856                  << ScalarCost << "\nVector: " << VectorCost << '\n');
   4857     return ScalarCost > VectorCost;
   4858   }
   4859 
   4860   /// \brief Generate a constant vector with \p Val with the same
   4861   /// number of elements as the transition.
   4862   /// \p UseSplat defines whether or not \p Val should be replicated
   4863   /// across the whole vector.
   4864   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
   4865   /// otherwise we generate a vector with as many undef as possible:
   4866   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
   4867   /// used at the index of the extract.
   4868   Value *getConstantVector(Constant *Val, bool UseSplat) const {
   4869     unsigned ExtractIdx = UINT_MAX;
   4870     if (!UseSplat) {
   4871       // If we cannot determine where the constant must be, we have to
   4872       // use a splat constant.
   4873       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
   4874       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
   4875         ExtractIdx = CstVal->getSExtValue();
   4876       else
   4877         UseSplat = true;
   4878     }
   4879 
   4880     unsigned End = getTransitionType()->getVectorNumElements();
   4881     if (UseSplat)
   4882       return ConstantVector::getSplat(End, Val);
   4883 
   4884     SmallVector<Constant *, 4> ConstVec;
   4885     UndefValue *UndefVal = UndefValue::get(Val->getType());
   4886     for (unsigned Idx = 0; Idx != End; ++Idx) {
   4887       if (Idx == ExtractIdx)
   4888         ConstVec.push_back(Val);
   4889       else
   4890         ConstVec.push_back(UndefVal);
   4891     }
   4892     return ConstantVector::get(ConstVec);
   4893   }
   4894 
   4895   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
   4896   /// in \p Use can trigger undefined behavior.
   4897   static bool canCauseUndefinedBehavior(const Instruction *Use,
   4898                                         unsigned OperandIdx) {
   4899     // This is not safe to introduce undef when the operand is on
   4900     // the right hand side of a division-like instruction.
   4901     if (OperandIdx != 1)
   4902       return false;
   4903     switch (Use->getOpcode()) {
   4904     default:
   4905       return false;
   4906     case Instruction::SDiv:
   4907     case Instruction::UDiv:
   4908     case Instruction::SRem:
   4909     case Instruction::URem:
   4910       return true;
   4911     case Instruction::FDiv:
   4912     case Instruction::FRem:
   4913       return !Use->hasNoNaNs();
   4914     }
   4915     llvm_unreachable(nullptr);
   4916   }
   4917 
   4918 public:
   4919   VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
   4920                       const TargetTransformInfo &TTI, Instruction *Transition,
   4921                       unsigned CombineCost)
   4922       : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
   4923         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
   4924     assert(Transition && "Do not know how to promote null");
   4925   }
   4926 
   4927   /// \brief Check if we can promote \p ToBePromoted to \p Type.
   4928   bool canPromote(const Instruction *ToBePromoted) const {
   4929     // We could support CastInst too.
   4930     return isa<BinaryOperator>(ToBePromoted);
   4931   }
   4932 
   4933   /// \brief Check if it is profitable to promote \p ToBePromoted
   4934   /// by moving downward the transition through.
   4935   bool shouldPromote(const Instruction *ToBePromoted) const {
   4936     // Promote only if all the operands can be statically expanded.
   4937     // Indeed, we do not want to introduce any new kind of transitions.
   4938     for (const Use &U : ToBePromoted->operands()) {
   4939       const Value *Val = U.get();
   4940       if (Val == getEndOfTransition()) {
   4941         // If the use is a division and the transition is on the rhs,
   4942         // we cannot promote the operation, otherwise we may create a
   4943         // division by zero.
   4944         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
   4945           return false;
   4946         continue;
   4947       }
   4948       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
   4949           !isa<ConstantFP>(Val))
   4950         return false;
   4951     }
   4952     // Check that the resulting operation is legal.
   4953     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
   4954     if (!ISDOpcode)
   4955       return false;
   4956     return StressStoreExtract ||
   4957            TLI.isOperationLegalOrCustom(
   4958                ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
   4959   }
   4960 
   4961   /// \brief Check whether or not \p Use can be combined
   4962   /// with the transition.
   4963   /// I.e., is it possible to do Use(Transition) => AnotherUse?
   4964   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
   4965 
   4966   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
   4967   void enqueueForPromotion(Instruction *ToBePromoted) {
   4968     InstsToBePromoted.push_back(ToBePromoted);
   4969   }
   4970 
   4971   /// \brief Set the instruction that will be combined with the transition.
   4972   void recordCombineInstruction(Instruction *ToBeCombined) {
   4973     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
   4974     CombineInst = ToBeCombined;
   4975   }
   4976 
   4977   /// \brief Promote all the instructions enqueued for promotion if it is
   4978   /// is profitable.
   4979   /// \return True if the promotion happened, false otherwise.
   4980   bool promote() {
   4981     // Check if there is something to promote.
   4982     // Right now, if we do not have anything to combine with,
   4983     // we assume the promotion is not profitable.
   4984     if (InstsToBePromoted.empty() || !CombineInst)
   4985       return false;
   4986 
   4987     // Check cost.
   4988     if (!StressStoreExtract && !isProfitableToPromote())
   4989       return false;
   4990 
   4991     // Promote.
   4992     for (auto &ToBePromoted : InstsToBePromoted)
   4993       promoteImpl(ToBePromoted);
   4994     InstsToBePromoted.clear();
   4995     return true;
   4996   }
   4997 };
   4998 } // End of anonymous namespace.
   4999 
   5000 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
   5001   // At this point, we know that all the operands of ToBePromoted but Def
   5002   // can be statically promoted.
   5003   // For Def, we need to use its parameter in ToBePromoted:
   5004   // b = ToBePromoted ty1 a
   5005   // Def = Transition ty1 b to ty2
   5006   // Move the transition down.
   5007   // 1. Replace all uses of the promoted operation by the transition.
   5008   // = ... b => = ... Def.
   5009   assert(ToBePromoted->getType() == Transition->getType() &&
   5010          "The type of the result of the transition does not match "
   5011          "the final type");
   5012   ToBePromoted->replaceAllUsesWith(Transition);
   5013   // 2. Update the type of the uses.
   5014   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
   5015   Type *TransitionTy = getTransitionType();
   5016   ToBePromoted->mutateType(TransitionTy);
   5017   // 3. Update all the operands of the promoted operation with promoted
   5018   // operands.
   5019   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
   5020   for (Use &U : ToBePromoted->operands()) {
   5021     Value *Val = U.get();
   5022     Value *NewVal = nullptr;
   5023     if (Val == Transition)
   5024       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
   5025     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
   5026              isa<ConstantFP>(Val)) {
   5027       // Use a splat constant if it is not safe to use undef.
   5028       NewVal = getConstantVector(
   5029           cast<Constant>(Val),
   5030           isa<UndefValue>(Val) ||
   5031               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
   5032     } else
   5033       llvm_unreachable("Did you modified shouldPromote and forgot to update "
   5034                        "this?");
   5035     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
   5036   }
   5037   Transition->removeFromParent();
   5038   Transition->insertAfter(ToBePromoted);
   5039   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
   5040 }
   5041 
   5042 /// Some targets can do store(extractelement) with one instruction.
   5043 /// Try to push the extractelement towards the stores when the target
   5044 /// has this feature and this is profitable.
   5045 bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
   5046   unsigned CombineCost = UINT_MAX;
   5047   if (DisableStoreExtract || !TLI ||
   5048       (!StressStoreExtract &&
   5049        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
   5050                                        Inst->getOperand(1), CombineCost)))
   5051     return false;
   5052 
   5053   // At this point we know that Inst is a vector to scalar transition.
   5054   // Try to move it down the def-use chain, until:
   5055   // - We can combine the transition with its single use
   5056   //   => we got rid of the transition.
   5057   // - We escape the current basic block
   5058   //   => we would need to check that we are moving it at a cheaper place and
   5059   //      we do not do that for now.
   5060   BasicBlock *Parent = Inst->getParent();
   5061   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
   5062   VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
   5063   // If the transition has more than one use, assume this is not going to be
   5064   // beneficial.
   5065   while (Inst->hasOneUse()) {
   5066     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
   5067     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
   5068 
   5069     if (ToBePromoted->getParent() != Parent) {
   5070       DEBUG(dbgs() << "Instruction to promote is in a different block ("
   5071                    << ToBePromoted->getParent()->getName()
   5072                    << ") than the transition (" << Parent->getName() << ").\n");
   5073       return false;
   5074     }
   5075 
   5076     if (VPH.canCombine(ToBePromoted)) {
   5077       DEBUG(dbgs() << "Assume " << *Inst << '\n'
   5078                    << "will be combined with: " << *ToBePromoted << '\n');
   5079       VPH.recordCombineInstruction(ToBePromoted);
   5080       bool Changed = VPH.promote();
   5081       NumStoreExtractExposed += Changed;
   5082       return Changed;
   5083     }
   5084 
   5085     DEBUG(dbgs() << "Try promoting.\n");
   5086     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
   5087       return false;
   5088 
   5089     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
   5090 
   5091     VPH.enqueueForPromotion(ToBePromoted);
   5092     Inst = ToBePromoted;
   5093   }
   5094   return false;
   5095 }
   5096 
   5097 bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
   5098   // Bail out if we inserted the instruction to prevent optimizations from
   5099   // stepping on each other's toes.
   5100   if (InsertedInsts.count(I))
   5101     return false;
   5102 
   5103   if (PHINode *P = dyn_cast<PHINode>(I)) {
   5104     // It is possible for very late stage optimizations (such as SimplifyCFG)
   5105     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
   5106     // trivial PHI, go ahead and zap it here.
   5107     if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
   5108       P->replaceAllUsesWith(V);
   5109       P->eraseFromParent();
   5110       ++NumPHIsElim;
   5111       return true;
   5112     }
   5113     return false;
   5114   }
   5115 
   5116   if (CastInst *CI = dyn_cast<CastInst>(I)) {
   5117     // If the source of the cast is a constant, then this should have
   5118     // already been constant folded.  The only reason NOT to constant fold
   5119     // it is if something (e.g. LSR) was careful to place the constant
   5120     // evaluation in a block other than then one that uses it (e.g. to hoist
   5121     // the address of globals out of a loop).  If this is the case, we don't
   5122     // want to forward-subst the cast.
   5123     if (isa<Constant>(CI->getOperand(0)))
   5124       return false;
   5125 
   5126     if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
   5127       return true;
   5128 
   5129     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
   5130       /// Sink a zext or sext into its user blocks if the target type doesn't
   5131       /// fit in one register
   5132       if (TLI &&
   5133           TLI->getTypeAction(CI->getContext(),
   5134                              TLI->getValueType(*DL, CI->getType())) ==
   5135               TargetLowering::TypeExpandInteger) {
   5136         return SinkCast(CI);
   5137       } else {
   5138         bool MadeChange = moveExtToFormExtLoad(I);
   5139         return MadeChange | optimizeExtUses(I);
   5140       }
   5141     }
   5142     return false;
   5143   }
   5144 
   5145   if (CmpInst *CI = dyn_cast<CmpInst>(I))
   5146     if (!TLI || !TLI->hasMultipleConditionRegisters())
   5147       return OptimizeCmpExpression(CI);
   5148 
   5149   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
   5150     stripInvariantGroupMetadata(*LI);
   5151     if (TLI) {
   5152       bool Modified = optimizeLoadExt(LI);
   5153       unsigned AS = LI->getPointerAddressSpace();
   5154       Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
   5155       return Modified;
   5156     }
   5157     return false;
   5158   }
   5159 
   5160   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
   5161     stripInvariantGroupMetadata(*SI);
   5162     if (TLI) {
   5163       unsigned AS = SI->getPointerAddressSpace();
   5164       return optimizeMemoryInst(I, SI->getOperand(1),
   5165                                 SI->getOperand(0)->getType(), AS);
   5166     }
   5167     return false;
   5168   }
   5169 
   5170   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
   5171 
   5172   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
   5173                 BinOp->getOpcode() == Instruction::LShr)) {
   5174     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
   5175     if (TLI && CI && TLI->hasExtractBitsInsn())
   5176       return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
   5177 
   5178     return false;
   5179   }
   5180 
   5181   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
   5182     if (GEPI->hasAllZeroIndices()) {
   5183       /// The GEP operand must be a pointer, so must its result -> BitCast
   5184       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
   5185                                         GEPI->getName(), GEPI);
   5186       GEPI->replaceAllUsesWith(NC);
   5187       GEPI->eraseFromParent();
   5188       ++NumGEPsElim;
   5189       optimizeInst(NC, ModifiedDT);
   5190       return true;
   5191     }
   5192     return false;
   5193   }
   5194 
   5195   if (CallInst *CI = dyn_cast<CallInst>(I))
   5196     return optimizeCallInst(CI, ModifiedDT);
   5197 
   5198   if (SelectInst *SI = dyn_cast<SelectInst>(I))
   5199     return optimizeSelectInst(SI);
   5200 
   5201   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
   5202     return optimizeShuffleVectorInst(SVI);
   5203 
   5204   if (auto *Switch = dyn_cast<SwitchInst>(I))
   5205     return optimizeSwitchInst(Switch);
   5206 
   5207   if (isa<ExtractElementInst>(I))
   5208     return optimizeExtractElementInst(I);
   5209 
   5210   return false;
   5211 }
   5212 
   5213 // In this pass we look for GEP and cast instructions that are used
   5214 // across basic blocks and rewrite them to improve basic-block-at-a-time
   5215 // selection.
   5216 bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
   5217   SunkAddrs.clear();
   5218   bool MadeChange = false;
   5219 
   5220   CurInstIterator = BB.begin();
   5221   while (CurInstIterator != BB.end()) {
   5222     MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
   5223     if (ModifiedDT)
   5224       return true;
   5225   }
   5226   MadeChange |= dupRetToEnableTailCallOpts(&BB);
   5227 
   5228   return MadeChange;
   5229 }
   5230 
   5231 // llvm.dbg.value is far away from the value then iSel may not be able
   5232 // handle it properly. iSel will drop llvm.dbg.value if it can not
   5233 // find a node corresponding to the value.
   5234 bool CodeGenPrepare::placeDbgValues(Function &F) {
   5235   bool MadeChange = false;
   5236   for (BasicBlock &BB : F) {
   5237     Instruction *PrevNonDbgInst = nullptr;
   5238     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
   5239       Instruction *Insn = &*BI++;
   5240       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
   5241       // Leave dbg.values that refer to an alloca alone. These
   5242       // instrinsics describe the address of a variable (= the alloca)
   5243       // being taken.  They should not be moved next to the alloca
   5244       // (and to the beginning of the scope), but rather stay close to
   5245       // where said address is used.
   5246       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
   5247         PrevNonDbgInst = Insn;
   5248         continue;
   5249       }
   5250 
   5251       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
   5252       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
   5253         // If VI is a phi in a block with an EHPad terminator, we can't insert
   5254         // after it.
   5255         if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
   5256           continue;
   5257         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
   5258         DVI->removeFromParent();
   5259         if (isa<PHINode>(VI))
   5260           DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
   5261         else
   5262           DVI->insertAfter(VI);
   5263         MadeChange = true;
   5264         ++NumDbgValueMoved;
   5265       }
   5266     }
   5267   }
   5268   return MadeChange;
   5269 }
   5270 
   5271 // If there is a sequence that branches based on comparing a single bit
   5272 // against zero that can be combined into a single instruction, and the
   5273 // target supports folding these into a single instruction, sink the
   5274 // mask and compare into the branch uses. Do this before OptimizeBlock ->
   5275 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
   5276 // searched for.
   5277 bool CodeGenPrepare::sinkAndCmp(Function &F) {
   5278   if (!EnableAndCmpSinking)
   5279     return false;
   5280   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
   5281     return false;
   5282   bool MadeChange = false;
   5283   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
   5284     BasicBlock *BB = &*I++;
   5285 
   5286     // Does this BB end with the following?
   5287     //   %andVal = and %val, #single-bit-set
   5288     //   %icmpVal = icmp %andResult, 0
   5289     //   br i1 %cmpVal label %dest1, label %dest2"
   5290     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
   5291     if (!Brcc || !Brcc->isConditional())
   5292       continue;
   5293     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
   5294     if (!Cmp || Cmp->getParent() != BB)
   5295       continue;
   5296     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
   5297     if (!Zero || !Zero->isZero())
   5298       continue;
   5299     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
   5300     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
   5301       continue;
   5302     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
   5303     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
   5304       continue;
   5305     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
   5306 
   5307     // Push the "and; icmp" for any users that are conditional branches.
   5308     // Since there can only be one branch use per BB, we don't need to keep
   5309     // track of which BBs we insert into.
   5310     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
   5311          UI != E; ) {
   5312       Use &TheUse = *UI;
   5313       // Find brcc use.
   5314       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
   5315       ++UI;
   5316       if (!BrccUser || !BrccUser->isConditional())
   5317         continue;
   5318       BasicBlock *UserBB = BrccUser->getParent();
   5319       if (UserBB == BB) continue;
   5320       DEBUG(dbgs() << "found Brcc use\n");
   5321 
   5322       // Sink the "and; icmp" to use.
   5323       MadeChange = true;
   5324       BinaryOperator *NewAnd =
   5325         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
   5326                                   BrccUser);
   5327       CmpInst *NewCmp =
   5328         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
   5329                         "", BrccUser);
   5330       TheUse = NewCmp;
   5331       ++NumAndCmpsMoved;
   5332       DEBUG(BrccUser->getParent()->dump());
   5333     }
   5334   }
   5335   return MadeChange;
   5336 }
   5337 
   5338 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
   5339 /// success, or returns false if no or invalid metadata was found.
   5340 static bool extractBranchMetadata(BranchInst *BI,
   5341                                   uint64_t &ProbTrue, uint64_t &ProbFalse) {
   5342   assert(BI->isConditional() &&
   5343          "Looking for probabilities on unconditional branch?");
   5344   auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
   5345   if (!ProfileData || ProfileData->getNumOperands() != 3)
   5346     return false;
   5347 
   5348   const auto *CITrue =
   5349       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
   5350   const auto *CIFalse =
   5351       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
   5352   if (!CITrue || !CIFalse)
   5353     return false;
   5354 
   5355   ProbTrue = CITrue->getValue().getZExtValue();
   5356   ProbFalse = CIFalse->getValue().getZExtValue();
   5357 
   5358   return true;
   5359 }
   5360 
   5361 /// \brief Scale down both weights to fit into uint32_t.
   5362 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
   5363   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
   5364   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
   5365   NewTrue = NewTrue / Scale;
   5366   NewFalse = NewFalse / Scale;
   5367 }
   5368 
   5369 /// \brief Some targets prefer to split a conditional branch like:
   5370 /// \code
   5371 ///   %0 = icmp ne i32 %a, 0
   5372 ///   %1 = icmp ne i32 %b, 0
   5373 ///   %or.cond = or i1 %0, %1
   5374 ///   br i1 %or.cond, label %TrueBB, label %FalseBB
   5375 /// \endcode
   5376 /// into multiple branch instructions like:
   5377 /// \code
   5378 ///   bb1:
   5379 ///     %0 = icmp ne i32 %a, 0
   5380 ///     br i1 %0, label %TrueBB, label %bb2
   5381 ///   bb2:
   5382 ///     %1 = icmp ne i32 %b, 0
   5383 ///     br i1 %1, label %TrueBB, label %FalseBB
   5384 /// \endcode
   5385 /// This usually allows instruction selection to do even further optimizations
   5386 /// and combine the compare with the branch instruction. Currently this is
   5387 /// applied for targets which have "cheap" jump instructions.
   5388 ///
   5389 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
   5390 ///
   5391 bool CodeGenPrepare::splitBranchCondition(Function &F) {
   5392   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
   5393     return false;
   5394 
   5395   bool MadeChange = false;
   5396   for (auto &BB : F) {
   5397     // Does this BB end with the following?
   5398     //   %cond1 = icmp|fcmp|binary instruction ...
   5399     //   %cond2 = icmp|fcmp|binary instruction ...
   5400     //   %cond.or = or|and i1 %cond1, cond2
   5401     //   br i1 %cond.or label %dest1, label %dest2"
   5402     BinaryOperator *LogicOp;
   5403     BasicBlock *TBB, *FBB;
   5404     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
   5405       continue;
   5406 
   5407     auto *Br1 = cast<BranchInst>(BB.getTerminator());
   5408     if (Br1->getMetadata(LLVMContext::MD_unpredictable))
   5409       continue;
   5410 
   5411     unsigned Opc;
   5412     Value *Cond1, *Cond2;
   5413     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
   5414                              m_OneUse(m_Value(Cond2)))))
   5415       Opc = Instruction::And;
   5416     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
   5417                                  m_OneUse(m_Value(Cond2)))))
   5418       Opc = Instruction::Or;
   5419     else
   5420       continue;
   5421 
   5422     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
   5423         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
   5424       continue;
   5425 
   5426     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
   5427 
   5428     // Create a new BB.
   5429     auto *InsertBefore = std::next(Function::iterator(BB))
   5430         .getNodePtrUnchecked();
   5431     auto TmpBB = BasicBlock::Create(BB.getContext(),
   5432                                     BB.getName() + ".cond.split",
   5433                                     BB.getParent(), InsertBefore);
   5434 
   5435     // Update original basic block by using the first condition directly by the
   5436     // branch instruction and removing the no longer needed and/or instruction.
   5437     Br1->setCondition(Cond1);
   5438     LogicOp->eraseFromParent();
   5439 
   5440     // Depending on the conditon we have to either replace the true or the false
   5441     // successor of the original branch instruction.
   5442     if (Opc == Instruction::And)
   5443       Br1->setSuccessor(0, TmpBB);
   5444     else
   5445       Br1->setSuccessor(1, TmpBB);
   5446 
   5447     // Fill in the new basic block.
   5448     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
   5449     if (auto *I = dyn_cast<Instruction>(Cond2)) {
   5450       I->removeFromParent();
   5451       I->insertBefore(Br2);
   5452     }
   5453 
   5454     // Update PHI nodes in both successors. The original BB needs to be
   5455     // replaced in one succesor's PHI nodes, because the branch comes now from
   5456     // the newly generated BB (NewBB). In the other successor we need to add one
   5457     // incoming edge to the PHI nodes, because both branch instructions target
   5458     // now the same successor. Depending on the original branch condition
   5459     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
   5460     // we perfrom the correct update for the PHI nodes.
   5461     // This doesn't change the successor order of the just created branch
   5462     // instruction (or any other instruction).
   5463     if (Opc == Instruction::Or)
   5464       std::swap(TBB, FBB);
   5465 
   5466     // Replace the old BB with the new BB.
   5467     for (auto &I : *TBB) {
   5468       PHINode *PN = dyn_cast<PHINode>(&I);
   5469       if (!PN)
   5470         break;
   5471       int i;
   5472       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
   5473         PN->setIncomingBlock(i, TmpBB);
   5474     }
   5475 
   5476     // Add another incoming edge form the new BB.
   5477     for (auto &I : *FBB) {
   5478       PHINode *PN = dyn_cast<PHINode>(&I);
   5479       if (!PN)
   5480         break;
   5481       auto *Val = PN->getIncomingValueForBlock(&BB);
   5482       PN->addIncoming(Val, TmpBB);
   5483     }
   5484 
   5485     // Update the branch weights (from SelectionDAGBuilder::
   5486     // FindMergedConditions).
   5487     if (Opc == Instruction::Or) {
   5488       // Codegen X | Y as:
   5489       // BB1:
   5490       //   jmp_if_X TBB
   5491       //   jmp TmpBB
   5492       // TmpBB:
   5493       //   jmp_if_Y TBB
   5494       //   jmp FBB
   5495       //
   5496 
   5497       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
   5498       // The requirement is that
   5499       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
   5500       //     = TrueProb for orignal BB.
   5501       // Assuming the orignal weights are A and B, one choice is to set BB1's
   5502       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
   5503       // assumes that
   5504       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
   5505       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
   5506       // TmpBB, but the math is more complicated.
   5507       uint64_t TrueWeight, FalseWeight;
   5508       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
   5509         uint64_t NewTrueWeight = TrueWeight;
   5510         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
   5511         scaleWeights(NewTrueWeight, NewFalseWeight);
   5512         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
   5513                          .createBranchWeights(TrueWeight, FalseWeight));
   5514 
   5515         NewTrueWeight = TrueWeight;
   5516         NewFalseWeight = 2 * FalseWeight;
   5517         scaleWeights(NewTrueWeight, NewFalseWeight);
   5518         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
   5519                          .createBranchWeights(TrueWeight, FalseWeight));
   5520       }
   5521     } else {
   5522       // Codegen X & Y as:
   5523       // BB1:
   5524       //   jmp_if_X TmpBB
   5525       //   jmp FBB
   5526       // TmpBB:
   5527       //   jmp_if_Y TBB
   5528       //   jmp FBB
   5529       //
   5530       //  This requires creation of TmpBB after CurBB.
   5531 
   5532       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
   5533       // The requirement is that
   5534       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
   5535       //     = FalseProb for orignal BB.
   5536       // Assuming the orignal weights are A and B, one choice is to set BB1's
   5537       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
   5538       // assumes that
   5539       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
   5540       uint64_t TrueWeight, FalseWeight;
   5541       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
   5542         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
   5543         uint64_t NewFalseWeight = FalseWeight;
   5544         scaleWeights(NewTrueWeight, NewFalseWeight);
   5545         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
   5546                          .createBranchWeights(TrueWeight, FalseWeight));
   5547 
   5548         NewTrueWeight = 2 * TrueWeight;
   5549         NewFalseWeight = FalseWeight;
   5550         scaleWeights(NewTrueWeight, NewFalseWeight);
   5551         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
   5552                          .createBranchWeights(TrueWeight, FalseWeight));
   5553       }
   5554     }
   5555 
   5556     // Note: No point in getting fancy here, since the DT info is never
   5557     // available to CodeGenPrepare.
   5558     ModifiedDT = true;
   5559 
   5560     MadeChange = true;
   5561 
   5562     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
   5563           TmpBB->dump());
   5564   }
   5565   return MadeChange;
   5566 }
   5567 
   5568 void CodeGenPrepare::stripInvariantGroupMetadata(Instruction &I) {
   5569   if (auto *InvariantMD = I.getMetadata(LLVMContext::MD_invariant_group))
   5570     I.dropUnknownNonDebugMetadata(InvariantMD->getMetadataID());
   5571 }
   5572