LLVM API Documentation

CodeGenPrepare.cpp
Go to the documentation of this file.
00001 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass munges the code in the input function to better prepare it for
00011 // SelectionDAG-based code generation. This works around limitations in it's
00012 // basic-block-at-a-time approach. It should eventually be removed.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/CodeGen/Passes.h"
00017 #include "llvm/ADT/DenseMap.h"
00018 #include "llvm/ADT/SmallSet.h"
00019 #include "llvm/ADT/Statistic.h"
00020 #include "llvm/Analysis/InstructionSimplify.h"
00021 #include "llvm/Analysis/TargetTransformInfo.h"
00022 #include "llvm/IR/CallSite.h"
00023 #include "llvm/IR/Constants.h"
00024 #include "llvm/IR/DataLayout.h"
00025 #include "llvm/IR/DerivedTypes.h"
00026 #include "llvm/IR/Dominators.h"
00027 #include "llvm/IR/Function.h"
00028 #include "llvm/IR/GetElementPtrTypeIterator.h"
00029 #include "llvm/IR/IRBuilder.h"
00030 #include "llvm/IR/InlineAsm.h"
00031 #include "llvm/IR/Instructions.h"
00032 #include "llvm/IR/IntrinsicInst.h"
00033 #include "llvm/IR/PatternMatch.h"
00034 #include "llvm/IR/ValueHandle.h"
00035 #include "llvm/IR/ValueMap.h"
00036 #include "llvm/Pass.h"
00037 #include "llvm/Support/CommandLine.h"
00038 #include "llvm/Support/Debug.h"
00039 #include "llvm/Support/raw_ostream.h"
00040 #include "llvm/Target/TargetLibraryInfo.h"
00041 #include "llvm/Target/TargetLowering.h"
00042 #include "llvm/Target/TargetSubtargetInfo.h"
00043 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00044 #include "llvm/Transforms/Utils/BuildLibCalls.h"
00045 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
00046 #include "llvm/Transforms/Utils/Local.h"
00047 using namespace llvm;
00048 using namespace llvm::PatternMatch;
00049 
00050 #define DEBUG_TYPE "codegenprepare"
00051 
00052 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
00053 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
00054 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
00055 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
00056                       "sunken Cmps");
00057 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
00058                        "of sunken Casts");
00059 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
00060                           "computations were sunk");
00061 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
00062 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
00063 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
00064 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
00065 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
00066 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
00067 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
00068 
00069 static cl::opt<bool> DisableBranchOpts(
00070   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
00071   cl::desc("Disable branch optimizations in CodeGenPrepare"));
00072 
00073 static cl::opt<bool> DisableSelectToBranch(
00074   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
00075   cl::desc("Disable select to branch conversion."));
00076 
00077 static cl::opt<bool> AddrSinkUsingGEPs(
00078   "addr-sink-using-gep", cl::Hidden, cl::init(false),
00079   cl::desc("Address sinking in CGP using GEPs."));
00080 
00081 static cl::opt<bool> EnableAndCmpSinking(
00082    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
00083    cl::desc("Enable sinkinig and/cmp into branches."));
00084 
00085 static cl::opt<bool> DisableStoreExtract(
00086     "disable-cgp-store-extract", cl::Hidden, cl::init(false),
00087     cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
00088 
00089 static cl::opt<bool> StressStoreExtract(
00090     "stress-cgp-store-extract", cl::Hidden, cl::init(false),
00091     cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
00092 
00093 namespace {
00094 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
00095 struct TypeIsSExt {
00096   Type *Ty;
00097   bool IsSExt;
00098   TypeIsSExt(Type *Ty, bool IsSExt) : Ty(Ty), IsSExt(IsSExt) {}
00099 };
00100 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
00101 
00102   class CodeGenPrepare : public FunctionPass {
00103     /// TLI - Keep a pointer of a TargetLowering to consult for determining
00104     /// transformation profitability.
00105     const TargetMachine *TM;
00106     const TargetLowering *TLI;
00107     const TargetTransformInfo *TTI;
00108     const TargetLibraryInfo *TLInfo;
00109     DominatorTree *DT;
00110 
00111     /// CurInstIterator - As we scan instructions optimizing them, this is the
00112     /// next instruction to optimize.  Xforms that can invalidate this should
00113     /// update it.
00114     BasicBlock::iterator CurInstIterator;
00115 
00116     /// Keeps track of non-local addresses that have been sunk into a block.
00117     /// This allows us to avoid inserting duplicate code for blocks with
00118     /// multiple load/stores of the same address.
00119     ValueMap<Value*, Value*> SunkAddrs;
00120 
00121     /// Keeps track of all truncates inserted for the current function.
00122     SetOfInstrs InsertedTruncsSet;
00123     /// Keeps track of the type of the related instruction before their
00124     /// promotion for the current function.
00125     InstrToOrigTy PromotedInsts;
00126 
00127     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
00128     /// be updated.
00129     bool ModifiedDT;
00130 
00131     /// OptSize - True if optimizing for size.
00132     bool OptSize;
00133 
00134   public:
00135     static char ID; // Pass identification, replacement for typeid
00136     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
00137         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
00138         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
00139       }
00140     bool runOnFunction(Function &F) override;
00141 
00142     const char *getPassName() const override { return "CodeGen Prepare"; }
00143 
00144     void getAnalysisUsage(AnalysisUsage &AU) const override {
00145       AU.addPreserved<DominatorTreeWrapperPass>();
00146       AU.addRequired<TargetLibraryInfo>();
00147       AU.addRequired<TargetTransformInfo>();
00148     }
00149 
00150   private:
00151     bool EliminateFallThrough(Function &F);
00152     bool EliminateMostlyEmptyBlocks(Function &F);
00153     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
00154     void EliminateMostlyEmptyBlock(BasicBlock *BB);
00155     bool OptimizeBlock(BasicBlock &BB);
00156     bool OptimizeInst(Instruction *I);
00157     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
00158     bool OptimizeInlineAsmInst(CallInst *CS);
00159     bool OptimizeCallInst(CallInst *CI);
00160     bool MoveExtToFormExtLoad(Instruction *I);
00161     bool OptimizeExtUses(Instruction *I);
00162     bool OptimizeSelectInst(SelectInst *SI);
00163     bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
00164     bool OptimizeExtractElementInst(Instruction *Inst);
00165     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
00166     bool PlaceDbgValues(Function &F);
00167     bool sinkAndCmp(Function &F);
00168   };
00169 }
00170 
00171 char CodeGenPrepare::ID = 0;
00172 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
00173                    "Optimize for code generation", false, false)
00174 
00175 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
00176   return new CodeGenPrepare(TM);
00177 }
00178 
00179 bool CodeGenPrepare::runOnFunction(Function &F) {
00180   if (skipOptnoneFunction(F))
00181     return false;
00182 
00183   bool EverMadeChange = false;
00184   // Clear per function information.
00185   InsertedTruncsSet.clear();
00186   PromotedInsts.clear();
00187 
00188   ModifiedDT = false;
00189   if (TM)
00190     TLI = TM->getSubtargetImpl()->getTargetLowering();
00191   TLInfo = &getAnalysis<TargetLibraryInfo>();
00192   TTI = &getAnalysis<TargetTransformInfo>();
00193   DominatorTreeWrapperPass *DTWP =
00194       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
00195   DT = DTWP ? &DTWP->getDomTree() : nullptr;
00196   OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
00197                                            Attribute::OptimizeForSize);
00198 
00199   /// This optimization identifies DIV instructions that can be
00200   /// profitably bypassed and carried out with a shorter, faster divide.
00201   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
00202     const DenseMap<unsigned int, unsigned int> &BypassWidths =
00203        TLI->getBypassSlowDivWidths();
00204     for (Function::iterator I = F.begin(); I != F.end(); I++)
00205       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
00206   }
00207 
00208   // Eliminate blocks that contain only PHI nodes and an
00209   // unconditional branch.
00210   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
00211 
00212   // llvm.dbg.value is far away from the value then iSel may not be able
00213   // handle it properly. iSel will drop llvm.dbg.value if it can not
00214   // find a node corresponding to the value.
00215   EverMadeChange |= PlaceDbgValues(F);
00216 
00217   // If there is a mask, compare against zero, and branch that can be combined
00218   // into a single target instruction, push the mask and compare into branch
00219   // users. Do this before OptimizeBlock -> OptimizeInst ->
00220   // OptimizeCmpExpression, which perturbs the pattern being searched for.
00221   if (!DisableBranchOpts)
00222     EverMadeChange |= sinkAndCmp(F);
00223 
00224   bool MadeChange = true;
00225   while (MadeChange) {
00226     MadeChange = false;
00227     for (Function::iterator I = F.begin(); I != F.end(); ) {
00228       BasicBlock *BB = I++;
00229       MadeChange |= OptimizeBlock(*BB);
00230     }
00231     EverMadeChange |= MadeChange;
00232   }
00233 
00234   SunkAddrs.clear();
00235 
00236   if (!DisableBranchOpts) {
00237     MadeChange = false;
00238     SmallPtrSet<BasicBlock*, 8> WorkList;
00239     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00240       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
00241       MadeChange |= ConstantFoldTerminator(BB, true);
00242       if (!MadeChange) continue;
00243 
00244       for (SmallVectorImpl<BasicBlock*>::iterator
00245              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
00246         if (pred_begin(*II) == pred_end(*II))
00247           WorkList.insert(*II);
00248     }
00249 
00250     // Delete the dead blocks and any of their dead successors.
00251     MadeChange |= !WorkList.empty();
00252     while (!WorkList.empty()) {
00253       BasicBlock *BB = *WorkList.begin();
00254       WorkList.erase(BB);
00255       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
00256 
00257       DeleteDeadBlock(BB);
00258 
00259       for (SmallVectorImpl<BasicBlock*>::iterator
00260              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
00261         if (pred_begin(*II) == pred_end(*II))
00262           WorkList.insert(*II);
00263     }
00264 
00265     // Merge pairs of basic blocks with unconditional branches, connected by
00266     // a single edge.
00267     if (EverMadeChange || MadeChange)
00268       MadeChange |= EliminateFallThrough(F);
00269 
00270     if (MadeChange)
00271       ModifiedDT = true;
00272     EverMadeChange |= MadeChange;
00273   }
00274 
00275   if (ModifiedDT && DT)
00276     DT->recalculate(F);
00277 
00278   return EverMadeChange;
00279 }
00280 
00281 /// EliminateFallThrough - Merge basic blocks which are connected
00282 /// by a single edge, where one of the basic blocks has a single successor
00283 /// pointing to the other basic block, which has a single predecessor.
00284 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
00285   bool Changed = false;
00286   // Scan all of the blocks in the function, except for the entry block.
00287   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
00288     BasicBlock *BB = I++;
00289     // If the destination block has a single pred, then this is a trivial
00290     // edge, just collapse it.
00291     BasicBlock *SinglePred = BB->getSinglePredecessor();
00292 
00293     // Don't merge if BB's address is taken.
00294     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
00295 
00296     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
00297     if (Term && !Term->isConditional()) {
00298       Changed = true;
00299       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
00300       // Remember if SinglePred was the entry block of the function.
00301       // If so, we will need to move BB back to the entry position.
00302       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
00303       MergeBasicBlockIntoOnlyPred(BB, this);
00304 
00305       if (isEntry && BB != &BB->getParent()->getEntryBlock())
00306         BB->moveBefore(&BB->getParent()->getEntryBlock());
00307 
00308       // We have erased a block. Update the iterator.
00309       I = BB;
00310     }
00311   }
00312   return Changed;
00313 }
00314 
00315 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
00316 /// debug info directives, and an unconditional branch.  Passes before isel
00317 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
00318 /// isel.  Start by eliminating these blocks so we can split them the way we
00319 /// want them.
00320 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
00321   bool MadeChange = false;
00322   // Note that this intentionally skips the entry block.
00323   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
00324     BasicBlock *BB = I++;
00325 
00326     // If this block doesn't end with an uncond branch, ignore it.
00327     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
00328     if (!BI || !BI->isUnconditional())
00329       continue;
00330 
00331     // If the instruction before the branch (skipping debug info) isn't a phi
00332     // node, then other stuff is happening here.
00333     BasicBlock::iterator BBI = BI;
00334     if (BBI != BB->begin()) {
00335       --BBI;
00336       while (isa<DbgInfoIntrinsic>(BBI)) {
00337         if (BBI == BB->begin())
00338           break;
00339         --BBI;
00340       }
00341       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
00342         continue;
00343     }
00344 
00345     // Do not break infinite loops.
00346     BasicBlock *DestBB = BI->getSuccessor(0);
00347     if (DestBB == BB)
00348       continue;
00349 
00350     if (!CanMergeBlocks(BB, DestBB))
00351       continue;
00352 
00353     EliminateMostlyEmptyBlock(BB);
00354     MadeChange = true;
00355   }
00356   return MadeChange;
00357 }
00358 
00359 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
00360 /// single uncond branch between them, and BB contains no other non-phi
00361 /// instructions.
00362 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
00363                                     const BasicBlock *DestBB) const {
00364   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
00365   // the successor.  If there are more complex condition (e.g. preheaders),
00366   // don't mess around with them.
00367   BasicBlock::const_iterator BBI = BB->begin();
00368   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
00369     for (const User *U : PN->users()) {
00370       const Instruction *UI = cast<Instruction>(U);
00371       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
00372         return false;
00373       // If User is inside DestBB block and it is a PHINode then check
00374       // incoming value. If incoming value is not from BB then this is
00375       // a complex condition (e.g. preheaders) we want to avoid here.
00376       if (UI->getParent() == DestBB) {
00377         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
00378           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
00379             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
00380             if (Insn && Insn->getParent() == BB &&
00381                 Insn->getParent() != UPN->getIncomingBlock(I))
00382               return false;
00383           }
00384       }
00385     }
00386   }
00387 
00388   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
00389   // and DestBB may have conflicting incoming values for the block.  If so, we
00390   // can't merge the block.
00391   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
00392   if (!DestBBPN) return true;  // no conflict.
00393 
00394   // Collect the preds of BB.
00395   SmallPtrSet<const BasicBlock*, 16> BBPreds;
00396   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
00397     // It is faster to get preds from a PHI than with pred_iterator.
00398     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
00399       BBPreds.insert(BBPN->getIncomingBlock(i));
00400   } else {
00401     BBPreds.insert(pred_begin(BB), pred_end(BB));
00402   }
00403 
00404   // Walk the preds of DestBB.
00405   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
00406     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
00407     if (BBPreds.count(Pred)) {   // Common predecessor?
00408       BBI = DestBB->begin();
00409       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
00410         const Value *V1 = PN->getIncomingValueForBlock(Pred);
00411         const Value *V2 = PN->getIncomingValueForBlock(BB);
00412 
00413         // If V2 is a phi node in BB, look up what the mapped value will be.
00414         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
00415           if (V2PN->getParent() == BB)
00416             V2 = V2PN->getIncomingValueForBlock(Pred);
00417 
00418         // If there is a conflict, bail out.
00419         if (V1 != V2) return false;
00420       }
00421     }
00422   }
00423 
00424   return true;
00425 }
00426 
00427 
00428 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
00429 /// an unconditional branch in it.
00430 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
00431   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
00432   BasicBlock *DestBB = BI->getSuccessor(0);
00433 
00434   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
00435 
00436   // If the destination block has a single pred, then this is a trivial edge,
00437   // just collapse it.
00438   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
00439     if (SinglePred != DestBB) {
00440       // Remember if SinglePred was the entry block of the function.  If so, we
00441       // will need to move BB back to the entry position.
00442       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
00443       MergeBasicBlockIntoOnlyPred(DestBB, this);
00444 
00445       if (isEntry && BB != &BB->getParent()->getEntryBlock())
00446         BB->moveBefore(&BB->getParent()->getEntryBlock());
00447 
00448       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
00449       return;
00450     }
00451   }
00452 
00453   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
00454   // to handle the new incoming edges it is about to have.
00455   PHINode *PN;
00456   for (BasicBlock::iterator BBI = DestBB->begin();
00457        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
00458     // Remove the incoming value for BB, and remember it.
00459     Value *InVal = PN->removeIncomingValue(BB, false);
00460 
00461     // Two options: either the InVal is a phi node defined in BB or it is some
00462     // value that dominates BB.
00463     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
00464     if (InValPhi && InValPhi->getParent() == BB) {
00465       // Add all of the input values of the input PHI as inputs of this phi.
00466       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
00467         PN->addIncoming(InValPhi->getIncomingValue(i),
00468                         InValPhi->getIncomingBlock(i));
00469     } else {
00470       // Otherwise, add one instance of the dominating value for each edge that
00471       // we will be adding.
00472       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
00473         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
00474           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
00475       } else {
00476         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00477           PN->addIncoming(InVal, *PI);
00478       }
00479     }
00480   }
00481 
00482   // The PHIs are now updated, change everything that refers to BB to use
00483   // DestBB and remove BB.
00484   BB->replaceAllUsesWith(DestBB);
00485   if (DT && !ModifiedDT) {
00486     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
00487     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
00488     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
00489     DT->changeImmediateDominator(DestBB, NewIDom);
00490     DT->eraseNode(BB);
00491   }
00492   BB->eraseFromParent();
00493   ++NumBlocksElim;
00494 
00495   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
00496 }
00497 
00498 /// SinkCast - Sink the specified cast instruction into its user blocks
00499 static bool SinkCast(CastInst *CI) {
00500   BasicBlock *DefBB = CI->getParent();
00501 
00502   /// InsertedCasts - Only insert a cast in each block once.
00503   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
00504 
00505   bool MadeChange = false;
00506   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
00507        UI != E; ) {
00508     Use &TheUse = UI.getUse();
00509     Instruction *User = cast<Instruction>(*UI);
00510 
00511     // Figure out which BB this cast is used in.  For PHI's this is the
00512     // appropriate predecessor block.
00513     BasicBlock *UserBB = User->getParent();
00514     if (PHINode *PN = dyn_cast<PHINode>(User)) {
00515       UserBB = PN->getIncomingBlock(TheUse);
00516     }
00517 
00518     // Preincrement use iterator so we don't invalidate it.
00519     ++UI;
00520 
00521     // If this user is in the same block as the cast, don't change the cast.
00522     if (UserBB == DefBB) continue;
00523 
00524     // If we have already inserted a cast into this block, use it.
00525     CastInst *&InsertedCast = InsertedCasts[UserBB];
00526 
00527     if (!InsertedCast) {
00528       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
00529       InsertedCast =
00530         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
00531                          InsertPt);
00532       MadeChange = true;
00533     }
00534 
00535     // Replace a use of the cast with a use of the new cast.
00536     TheUse = InsertedCast;
00537     ++NumCastUses;
00538   }
00539 
00540   // If we removed all uses, nuke the cast.
00541   if (CI->use_empty()) {
00542     CI->eraseFromParent();
00543     MadeChange = true;
00544   }
00545 
00546   return MadeChange;
00547 }
00548 
00549 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
00550 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
00551 /// sink it into user blocks to reduce the number of virtual
00552 /// registers that must be created and coalesced.
00553 ///
00554 /// Return true if any changes are made.
00555 ///
00556 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
00557   // If this is a noop copy,
00558   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
00559   EVT DstVT = TLI.getValueType(CI->getType());
00560 
00561   // This is an fp<->int conversion?
00562   if (SrcVT.isInteger() != DstVT.isInteger())
00563     return false;
00564 
00565   // If this is an extension, it will be a zero or sign extension, which
00566   // isn't a noop.
00567   if (SrcVT.bitsLT(DstVT)) return false;
00568 
00569   // If these values will be promoted, find out what they will be promoted
00570   // to.  This helps us consider truncates on PPC as noop copies when they
00571   // are.
00572   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
00573       TargetLowering::TypePromoteInteger)
00574     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
00575   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
00576       TargetLowering::TypePromoteInteger)
00577     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
00578 
00579   // If, after promotion, these are the same types, this is a noop copy.
00580   if (SrcVT != DstVT)
00581     return false;
00582 
00583   return SinkCast(CI);
00584 }
00585 
00586 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
00587 /// the number of virtual registers that must be created and coalesced.  This is
00588 /// a clear win except on targets with multiple condition code registers
00589 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
00590 ///
00591 /// Return true if any changes are made.
00592 static bool OptimizeCmpExpression(CmpInst *CI) {
00593   BasicBlock *DefBB = CI->getParent();
00594 
00595   /// InsertedCmp - Only insert a cmp in each block once.
00596   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
00597 
00598   bool MadeChange = false;
00599   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
00600        UI != E; ) {
00601     Use &TheUse = UI.getUse();
00602     Instruction *User = cast<Instruction>(*UI);
00603 
00604     // Preincrement use iterator so we don't invalidate it.
00605     ++UI;
00606 
00607     // Don't bother for PHI nodes.
00608     if (isa<PHINode>(User))
00609       continue;
00610 
00611     // Figure out which BB this cmp is used in.
00612     BasicBlock *UserBB = User->getParent();
00613 
00614     // If this user is in the same block as the cmp, don't change the cmp.
00615     if (UserBB == DefBB) continue;
00616 
00617     // If we have already inserted a cmp into this block, use it.
00618     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
00619 
00620     if (!InsertedCmp) {
00621       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
00622       InsertedCmp =
00623         CmpInst::Create(CI->getOpcode(),
00624                         CI->getPredicate(),  CI->getOperand(0),
00625                         CI->getOperand(1), "", InsertPt);
00626       MadeChange = true;
00627     }
00628 
00629     // Replace a use of the cmp with a use of the new cmp.
00630     TheUse = InsertedCmp;
00631     ++NumCmpUses;
00632   }
00633 
00634   // If we removed all uses, nuke the cmp.
00635   if (CI->use_empty())
00636     CI->eraseFromParent();
00637 
00638   return MadeChange;
00639 }
00640 
00641 /// isExtractBitsCandidateUse - Check if the candidates could
00642 /// be combined with shift instruction, which includes:
00643 /// 1. Truncate instruction
00644 /// 2. And instruction and the imm is a mask of the low bits:
00645 /// imm & (imm+1) == 0
00646 static bool isExtractBitsCandidateUse(Instruction *User) {
00647   if (!isa<TruncInst>(User)) {
00648     if (User->getOpcode() != Instruction::And ||
00649         !isa<ConstantInt>(User->getOperand(1)))
00650       return false;
00651 
00652     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
00653 
00654     if ((Cimm & (Cimm + 1)).getBoolValue())
00655       return false;
00656   }
00657   return true;
00658 }
00659 
00660 /// SinkShiftAndTruncate - sink both shift and truncate instruction
00661 /// to the use of truncate's BB.
00662 static bool
00663 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
00664                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
00665                      const TargetLowering &TLI) {
00666   BasicBlock *UserBB = User->getParent();
00667   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
00668   TruncInst *TruncI = dyn_cast<TruncInst>(User);
00669   bool MadeChange = false;
00670 
00671   for (Value::user_iterator TruncUI = TruncI->user_begin(),
00672                             TruncE = TruncI->user_end();
00673        TruncUI != TruncE;) {
00674 
00675     Use &TruncTheUse = TruncUI.getUse();
00676     Instruction *TruncUser = cast<Instruction>(*TruncUI);
00677     // Preincrement use iterator so we don't invalidate it.
00678 
00679     ++TruncUI;
00680 
00681     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
00682     if (!ISDOpcode)
00683       continue;
00684 
00685     // If the use is actually a legal node, there will not be an
00686     // implicit truncate.
00687     // FIXME: always querying the result type is just an
00688     // approximation; some nodes' legality is determined by the
00689     // operand or other means. There's no good way to find out though.
00690     if (TLI.isOperationLegalOrCustom(
00691             ISDOpcode, TLI.getValueType(TruncUser->getType(), true)))
00692       continue;
00693 
00694     // Don't bother for PHI nodes.
00695     if (isa<PHINode>(TruncUser))
00696       continue;
00697 
00698     BasicBlock *TruncUserBB = TruncUser->getParent();
00699 
00700     if (UserBB == TruncUserBB)
00701       continue;
00702 
00703     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
00704     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
00705 
00706     if (!InsertedShift && !InsertedTrunc) {
00707       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
00708       // Sink the shift
00709       if (ShiftI->getOpcode() == Instruction::AShr)
00710         InsertedShift =
00711             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
00712       else
00713         InsertedShift =
00714             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
00715 
00716       // Sink the trunc
00717       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
00718       TruncInsertPt++;
00719 
00720       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
00721                                        TruncI->getType(), "", TruncInsertPt);
00722 
00723       MadeChange = true;
00724 
00725       TruncTheUse = InsertedTrunc;
00726     }
00727   }
00728   return MadeChange;
00729 }
00730 
00731 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
00732 /// the uses could potentially be combined with this shift instruction and
00733 /// generate BitExtract instruction. It will only be applied if the architecture
00734 /// supports BitExtract instruction. Here is an example:
00735 /// BB1:
00736 ///   %x.extract.shift = lshr i64 %arg1, 32
00737 /// BB2:
00738 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
00739 /// ==>
00740 ///
00741 /// BB2:
00742 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
00743 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
00744 ///
00745 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
00746 /// instruction.
00747 /// Return true if any changes are made.
00748 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
00749                                 const TargetLowering &TLI) {
00750   BasicBlock *DefBB = ShiftI->getParent();
00751 
00752   /// Only insert instructions in each block once.
00753   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
00754 
00755   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
00756 
00757   bool MadeChange = false;
00758   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
00759        UI != E;) {
00760     Use &TheUse = UI.getUse();
00761     Instruction *User = cast<Instruction>(*UI);
00762     // Preincrement use iterator so we don't invalidate it.
00763     ++UI;
00764 
00765     // Don't bother for PHI nodes.
00766     if (isa<PHINode>(User))
00767       continue;
00768 
00769     if (!isExtractBitsCandidateUse(User))
00770       continue;
00771 
00772     BasicBlock *UserBB = User->getParent();
00773 
00774     if (UserBB == DefBB) {
00775       // If the shift and truncate instruction are in the same BB. The use of
00776       // the truncate(TruncUse) may still introduce another truncate if not
00777       // legal. In this case, we would like to sink both shift and truncate
00778       // instruction to the BB of TruncUse.
00779       // for example:
00780       // BB1:
00781       // i64 shift.result = lshr i64 opnd, imm
00782       // trunc.result = trunc shift.result to i16
00783       //
00784       // BB2:
00785       //   ----> We will have an implicit truncate here if the architecture does
00786       //   not have i16 compare.
00787       // cmp i16 trunc.result, opnd2
00788       //
00789       if (isa<TruncInst>(User) && shiftIsLegal
00790           // If the type of the truncate is legal, no trucate will be
00791           // introduced in other basic blocks.
00792           && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
00793         MadeChange =
00794             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
00795 
00796       continue;
00797     }
00798     // If we have already inserted a shift into this block, use it.
00799     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
00800 
00801     if (!InsertedShift) {
00802       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
00803 
00804       if (ShiftI->getOpcode() == Instruction::AShr)
00805         InsertedShift =
00806             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
00807       else
00808         InsertedShift =
00809             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
00810 
00811       MadeChange = true;
00812     }
00813 
00814     // Replace a use of the shift with a use of the new shift.
00815     TheUse = InsertedShift;
00816   }
00817 
00818   // If we removed all uses, nuke the shift.
00819   if (ShiftI->use_empty())
00820     ShiftI->eraseFromParent();
00821 
00822   return MadeChange;
00823 }
00824 
00825 namespace {
00826 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
00827 protected:
00828   void replaceCall(Value *With) override {
00829     CI->replaceAllUsesWith(With);
00830     CI->eraseFromParent();
00831   }
00832   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
00833       if (ConstantInt *SizeCI =
00834                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
00835         return SizeCI->isAllOnesValue();
00836     return false;
00837   }
00838 };
00839 } // end anonymous namespace
00840 
00841 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
00842   BasicBlock *BB = CI->getParent();
00843 
00844   // Lower inline assembly if we can.
00845   // If we found an inline asm expession, and if the target knows how to
00846   // lower it to normal LLVM code, do so now.
00847   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
00848     if (TLI->ExpandInlineAsm(CI)) {
00849       // Avoid invalidating the iterator.
00850       CurInstIterator = BB->begin();
00851       // Avoid processing instructions out of order, which could cause
00852       // reuse before a value is defined.
00853       SunkAddrs.clear();
00854       return true;
00855     }
00856     // Sink address computing for memory operands into the block.
00857     if (OptimizeInlineAsmInst(CI))
00858       return true;
00859   }
00860 
00861   // Lower all uses of llvm.objectsize.*
00862   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
00863   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
00864     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
00865     Type *ReturnTy = CI->getType();
00866     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
00867 
00868     // Substituting this can cause recursive simplifications, which can
00869     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
00870     // happens.
00871     WeakVH IterHandle(CurInstIterator);
00872 
00873     replaceAndRecursivelySimplify(CI, RetVal,
00874                                   TLI ? TLI->getDataLayout() : nullptr,
00875                                   TLInfo, ModifiedDT ? nullptr : DT);
00876 
00877     // If the iterator instruction was recursively deleted, start over at the
00878     // start of the block.
00879     if (IterHandle != CurInstIterator) {
00880       CurInstIterator = BB->begin();
00881       SunkAddrs.clear();
00882     }
00883     return true;
00884   }
00885 
00886   if (II && TLI) {
00887     SmallVector<Value*, 2> PtrOps;
00888     Type *AccessTy;
00889     if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
00890       while (!PtrOps.empty())
00891         if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
00892           return true;
00893   }
00894 
00895   // From here on out we're working with named functions.
00896   if (!CI->getCalledFunction()) return false;
00897 
00898   // We'll need DataLayout from here on out.
00899   const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
00900   if (!TD) return false;
00901 
00902   // Lower all default uses of _chk calls.  This is very similar
00903   // to what InstCombineCalls does, but here we are only lowering calls
00904   // that have the default "don't know" as the objectsize.  Anything else
00905   // should be left alone.
00906   CodeGenPrepareFortifiedLibCalls Simplifier;
00907   return Simplifier.fold(CI, TD, TLInfo);
00908 }
00909 
00910 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
00911 /// instructions to the predecessor to enable tail call optimizations. The
00912 /// case it is currently looking for is:
00913 /// @code
00914 /// bb0:
00915 ///   %tmp0 = tail call i32 @f0()
00916 ///   br label %return
00917 /// bb1:
00918 ///   %tmp1 = tail call i32 @f1()
00919 ///   br label %return
00920 /// bb2:
00921 ///   %tmp2 = tail call i32 @f2()
00922 ///   br label %return
00923 /// return:
00924 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
00925 ///   ret i32 %retval
00926 /// @endcode
00927 ///
00928 /// =>
00929 ///
00930 /// @code
00931 /// bb0:
00932 ///   %tmp0 = tail call i32 @f0()
00933 ///   ret i32 %tmp0
00934 /// bb1:
00935 ///   %tmp1 = tail call i32 @f1()
00936 ///   ret i32 %tmp1
00937 /// bb2:
00938 ///   %tmp2 = tail call i32 @f2()
00939 ///   ret i32 %tmp2
00940 /// @endcode
00941 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
00942   if (!TLI)
00943     return false;
00944 
00945   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
00946   if (!RI)
00947     return false;
00948 
00949   PHINode *PN = nullptr;
00950   BitCastInst *BCI = nullptr;
00951   Value *V = RI->getReturnValue();
00952   if (V) {
00953     BCI = dyn_cast<BitCastInst>(V);
00954     if (BCI)
00955       V = BCI->getOperand(0);
00956 
00957     PN = dyn_cast<PHINode>(V);
00958     if (!PN)
00959       return false;
00960   }
00961 
00962   if (PN && PN->getParent() != BB)
00963     return false;
00964 
00965   // It's not safe to eliminate the sign / zero extension of the return value.
00966   // See llvm::isInTailCallPosition().
00967   const Function *F = BB->getParent();
00968   AttributeSet CallerAttrs = F->getAttributes();
00969   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
00970       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
00971     return false;
00972 
00973   // Make sure there are no instructions between the PHI and return, or that the
00974   // return is the first instruction in the block.
00975   if (PN) {
00976     BasicBlock::iterator BI = BB->begin();
00977     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
00978     if (&*BI == BCI)
00979       // Also skip over the bitcast.
00980       ++BI;
00981     if (&*BI != RI)
00982       return false;
00983   } else {
00984     BasicBlock::iterator BI = BB->begin();
00985     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
00986     if (&*BI != RI)
00987       return false;
00988   }
00989 
00990   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
00991   /// call.
00992   SmallVector<CallInst*, 4> TailCalls;
00993   if (PN) {
00994     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
00995       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
00996       // Make sure the phi value is indeed produced by the tail call.
00997       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
00998           TLI->mayBeEmittedAsTailCall(CI))
00999         TailCalls.push_back(CI);
01000     }
01001   } else {
01002     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
01003     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
01004       if (!VisitedBBs.insert(*PI).second)
01005         continue;
01006 
01007       BasicBlock::InstListType &InstList = (*PI)->getInstList();
01008       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
01009       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
01010       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
01011       if (RI == RE)
01012         continue;
01013 
01014       CallInst *CI = dyn_cast<CallInst>(&*RI);
01015       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
01016         TailCalls.push_back(CI);
01017     }
01018   }
01019 
01020   bool Changed = false;
01021   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
01022     CallInst *CI = TailCalls[i];
01023     CallSite CS(CI);
01024 
01025     // Conservatively require the attributes of the call to match those of the
01026     // return. Ignore noalias because it doesn't affect the call sequence.
01027     AttributeSet CalleeAttrs = CS.getAttributes();
01028     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
01029           removeAttribute(Attribute::NoAlias) !=
01030         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
01031           removeAttribute(Attribute::NoAlias))
01032       continue;
01033 
01034     // Make sure the call instruction is followed by an unconditional branch to
01035     // the return block.
01036     BasicBlock *CallBB = CI->getParent();
01037     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
01038     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
01039       continue;
01040 
01041     // Duplicate the return into CallBB.
01042     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
01043     ModifiedDT = Changed = true;
01044     ++NumRetsDup;
01045   }
01046 
01047   // If we eliminated all predecessors of the block, delete the block now.
01048   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
01049     BB->eraseFromParent();
01050 
01051   return Changed;
01052 }
01053 
01054 //===----------------------------------------------------------------------===//
01055 // Memory Optimization
01056 //===----------------------------------------------------------------------===//
01057 
01058 namespace {
01059 
01060 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
01061 /// which holds actual Value*'s for register values.
01062 struct ExtAddrMode : public TargetLowering::AddrMode {
01063   Value *BaseReg;
01064   Value *ScaledReg;
01065   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
01066   void print(raw_ostream &OS) const;
01067   void dump() const;
01068 
01069   bool operator==(const ExtAddrMode& O) const {
01070     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
01071            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
01072            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
01073   }
01074 };
01075 
01076 #ifndef NDEBUG
01077 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
01078   AM.print(OS);
01079   return OS;
01080 }
01081 #endif
01082 
01083 void ExtAddrMode::print(raw_ostream &OS) const {
01084   bool NeedPlus = false;
01085   OS << "[";
01086   if (BaseGV) {
01087     OS << (NeedPlus ? " + " : "")
01088        << "GV:";
01089     BaseGV->printAsOperand(OS, /*PrintType=*/false);
01090     NeedPlus = true;
01091   }
01092 
01093   if (BaseOffs) {
01094     OS << (NeedPlus ? " + " : "")
01095        << BaseOffs;
01096     NeedPlus = true;
01097   }
01098 
01099   if (BaseReg) {
01100     OS << (NeedPlus ? " + " : "")
01101        << "Base:";
01102     BaseReg->printAsOperand(OS, /*PrintType=*/false);
01103     NeedPlus = true;
01104   }
01105   if (Scale) {
01106     OS << (NeedPlus ? " + " : "")
01107        << Scale << "*";
01108     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
01109   }
01110 
01111   OS << ']';
01112 }
01113 
01114 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
01115 void ExtAddrMode::dump() const {
01116   print(dbgs());
01117   dbgs() << '\n';
01118 }
01119 #endif
01120 
01121 /// \brief This class provides transaction based operation on the IR.
01122 /// Every change made through this class is recorded in the internal state and
01123 /// can be undone (rollback) until commit is called.
01124 class TypePromotionTransaction {
01125 
01126   /// \brief This represents the common interface of the individual transaction.
01127   /// Each class implements the logic for doing one specific modification on
01128   /// the IR via the TypePromotionTransaction.
01129   class TypePromotionAction {
01130   protected:
01131     /// The Instruction modified.
01132     Instruction *Inst;
01133 
01134   public:
01135     /// \brief Constructor of the action.
01136     /// The constructor performs the related action on the IR.
01137     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
01138 
01139     virtual ~TypePromotionAction() {}
01140 
01141     /// \brief Undo the modification done by this action.
01142     /// When this method is called, the IR must be in the same state as it was
01143     /// before this action was applied.
01144     /// \pre Undoing the action works if and only if the IR is in the exact same
01145     /// state as it was directly after this action was applied.
01146     virtual void undo() = 0;
01147 
01148     /// \brief Advocate every change made by this action.
01149     /// When the results on the IR of the action are to be kept, it is important
01150     /// to call this function, otherwise hidden information may be kept forever.
01151     virtual void commit() {
01152       // Nothing to be done, this action is not doing anything.
01153     }
01154   };
01155 
01156   /// \brief Utility to remember the position of an instruction.
01157   class InsertionHandler {
01158     /// Position of an instruction.
01159     /// Either an instruction:
01160     /// - Is the first in a basic block: BB is used.
01161     /// - Has a previous instructon: PrevInst is used.
01162     union {
01163       Instruction *PrevInst;
01164       BasicBlock *BB;
01165     } Point;
01166     /// Remember whether or not the instruction had a previous instruction.
01167     bool HasPrevInstruction;
01168 
01169   public:
01170     /// \brief Record the position of \p Inst.
01171     InsertionHandler(Instruction *Inst) {
01172       BasicBlock::iterator It = Inst;
01173       HasPrevInstruction = (It != (Inst->getParent()->begin()));
01174       if (HasPrevInstruction)
01175         Point.PrevInst = --It;
01176       else
01177         Point.BB = Inst->getParent();
01178     }
01179 
01180     /// \brief Insert \p Inst at the recorded position.
01181     void insert(Instruction *Inst) {
01182       if (HasPrevInstruction) {
01183         if (Inst->getParent())
01184           Inst->removeFromParent();
01185         Inst->insertAfter(Point.PrevInst);
01186       } else {
01187         Instruction *Position = Point.BB->getFirstInsertionPt();
01188         if (Inst->getParent())
01189           Inst->moveBefore(Position);
01190         else
01191           Inst->insertBefore(Position);
01192       }
01193     }
01194   };
01195 
01196   /// \brief Move an instruction before another.
01197   class InstructionMoveBefore : public TypePromotionAction {
01198     /// Original position of the instruction.
01199     InsertionHandler Position;
01200 
01201   public:
01202     /// \brief Move \p Inst before \p Before.
01203     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
01204         : TypePromotionAction(Inst), Position(Inst) {
01205       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
01206       Inst->moveBefore(Before);
01207     }
01208 
01209     /// \brief Move the instruction back to its original position.
01210     void undo() override {
01211       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
01212       Position.insert(Inst);
01213     }
01214   };
01215 
01216   /// \brief Set the operand of an instruction with a new value.
01217   class OperandSetter : public TypePromotionAction {
01218     /// Original operand of the instruction.
01219     Value *Origin;
01220     /// Index of the modified instruction.
01221     unsigned Idx;
01222 
01223   public:
01224     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
01225     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
01226         : TypePromotionAction(Inst), Idx(Idx) {
01227       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
01228                    << "for:" << *Inst << "\n"
01229                    << "with:" << *NewVal << "\n");
01230       Origin = Inst->getOperand(Idx);
01231       Inst->setOperand(Idx, NewVal);
01232     }
01233 
01234     /// \brief Restore the original value of the instruction.
01235     void undo() override {
01236       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
01237                    << "for: " << *Inst << "\n"
01238                    << "with: " << *Origin << "\n");
01239       Inst->setOperand(Idx, Origin);
01240     }
01241   };
01242 
01243   /// \brief Hide the operands of an instruction.
01244   /// Do as if this instruction was not using any of its operands.
01245   class OperandsHider : public TypePromotionAction {
01246     /// The list of original operands.
01247     SmallVector<Value *, 4> OriginalValues;
01248 
01249   public:
01250     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
01251     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
01252       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
01253       unsigned NumOpnds = Inst->getNumOperands();
01254       OriginalValues.reserve(NumOpnds);
01255       for (unsigned It = 0; It < NumOpnds; ++It) {
01256         // Save the current operand.
01257         Value *Val = Inst->getOperand(It);
01258         OriginalValues.push_back(Val);
01259         // Set a dummy one.
01260         // We could use OperandSetter here, but that would implied an overhead
01261         // that we are not willing to pay.
01262         Inst->setOperand(It, UndefValue::get(Val->getType()));
01263       }
01264     }
01265 
01266     /// \brief Restore the original list of uses.
01267     void undo() override {
01268       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
01269       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
01270         Inst->setOperand(It, OriginalValues[It]);
01271     }
01272   };
01273 
01274   /// \brief Build a truncate instruction.
01275   class TruncBuilder : public TypePromotionAction {
01276     Value *Val;
01277   public:
01278     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
01279     /// result.
01280     /// trunc Opnd to Ty.
01281     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
01282       IRBuilder<> Builder(Opnd);
01283       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
01284       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
01285     }
01286 
01287     /// \brief Get the built value.
01288     Value *getBuiltValue() { return Val; }
01289 
01290     /// \brief Remove the built instruction.
01291     void undo() override {
01292       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
01293       if (Instruction *IVal = dyn_cast<Instruction>(Val))
01294         IVal->eraseFromParent();
01295     }
01296   };
01297 
01298   /// \brief Build a sign extension instruction.
01299   class SExtBuilder : public TypePromotionAction {
01300     Value *Val;
01301   public:
01302     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
01303     /// result.
01304     /// sext Opnd to Ty.
01305     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
01306         : TypePromotionAction(InsertPt) {
01307       IRBuilder<> Builder(InsertPt);
01308       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
01309       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
01310     }
01311 
01312     /// \brief Get the built value.
01313     Value *getBuiltValue() { return Val; }
01314 
01315     /// \brief Remove the built instruction.
01316     void undo() override {
01317       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
01318       if (Instruction *IVal = dyn_cast<Instruction>(Val))
01319         IVal->eraseFromParent();
01320     }
01321   };
01322 
01323   /// \brief Build a zero extension instruction.
01324   class ZExtBuilder : public TypePromotionAction {
01325     Value *Val;
01326   public:
01327     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
01328     /// result.
01329     /// zext Opnd to Ty.
01330     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
01331         : TypePromotionAction(InsertPt) {
01332       IRBuilder<> Builder(InsertPt);
01333       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
01334       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
01335     }
01336 
01337     /// \brief Get the built value.
01338     Value *getBuiltValue() { return Val; }
01339 
01340     /// \brief Remove the built instruction.
01341     void undo() override {
01342       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
01343       if (Instruction *IVal = dyn_cast<Instruction>(Val))
01344         IVal->eraseFromParent();
01345     }
01346   };
01347 
01348   /// \brief Mutate an instruction to another type.
01349   class TypeMutator : public TypePromotionAction {
01350     /// Record the original type.
01351     Type *OrigTy;
01352 
01353   public:
01354     /// \brief Mutate the type of \p Inst into \p NewTy.
01355     TypeMutator(Instruction *Inst, Type *NewTy)
01356         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
01357       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
01358                    << "\n");
01359       Inst->mutateType(NewTy);
01360     }
01361 
01362     /// \brief Mutate the instruction back to its original type.
01363     void undo() override {
01364       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
01365                    << "\n");
01366       Inst->mutateType(OrigTy);
01367     }
01368   };
01369 
01370   /// \brief Replace the uses of an instruction by another instruction.
01371   class UsesReplacer : public TypePromotionAction {
01372     /// Helper structure to keep track of the replaced uses.
01373     struct InstructionAndIdx {
01374       /// The instruction using the instruction.
01375       Instruction *Inst;
01376       /// The index where this instruction is used for Inst.
01377       unsigned Idx;
01378       InstructionAndIdx(Instruction *Inst, unsigned Idx)
01379           : Inst(Inst), Idx(Idx) {}
01380     };
01381 
01382     /// Keep track of the original uses (pair Instruction, Index).
01383     SmallVector<InstructionAndIdx, 4> OriginalUses;
01384     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
01385 
01386   public:
01387     /// \brief Replace all the use of \p Inst by \p New.
01388     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
01389       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
01390                    << "\n");
01391       // Record the original uses.
01392       for (Use &U : Inst->uses()) {
01393         Instruction *UserI = cast<Instruction>(U.getUser());
01394         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
01395       }
01396       // Now, we can replace the uses.
01397       Inst->replaceAllUsesWith(New);
01398     }
01399 
01400     /// \brief Reassign the original uses of Inst to Inst.
01401     void undo() override {
01402       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
01403       for (use_iterator UseIt = OriginalUses.begin(),
01404                         EndIt = OriginalUses.end();
01405            UseIt != EndIt; ++UseIt) {
01406         UseIt->Inst->setOperand(UseIt->Idx, Inst);
01407       }
01408     }
01409   };
01410 
01411   /// \brief Remove an instruction from the IR.
01412   class InstructionRemover : public TypePromotionAction {
01413     /// Original position of the instruction.
01414     InsertionHandler Inserter;
01415     /// Helper structure to hide all the link to the instruction. In other
01416     /// words, this helps to do as if the instruction was removed.
01417     OperandsHider Hider;
01418     /// Keep track of the uses replaced, if any.
01419     UsesReplacer *Replacer;
01420 
01421   public:
01422     /// \brief Remove all reference of \p Inst and optinally replace all its
01423     /// uses with New.
01424     /// \pre If !Inst->use_empty(), then New != nullptr
01425     InstructionRemover(Instruction *Inst, Value *New = nullptr)
01426         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
01427           Replacer(nullptr) {
01428       if (New)
01429         Replacer = new UsesReplacer(Inst, New);
01430       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
01431       Inst->removeFromParent();
01432     }
01433 
01434     ~InstructionRemover() { delete Replacer; }
01435 
01436     /// \brief Really remove the instruction.
01437     void commit() override { delete Inst; }
01438 
01439     /// \brief Resurrect the instruction and reassign it to the proper uses if
01440     /// new value was provided when build this action.
01441     void undo() override {
01442       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
01443       Inserter.insert(Inst);
01444       if (Replacer)
01445         Replacer->undo();
01446       Hider.undo();
01447     }
01448   };
01449 
01450 public:
01451   /// Restoration point.
01452   /// The restoration point is a pointer to an action instead of an iterator
01453   /// because the iterator may be invalidated but not the pointer.
01454   typedef const TypePromotionAction *ConstRestorationPt;
01455   /// Advocate every changes made in that transaction.
01456   void commit();
01457   /// Undo all the changes made after the given point.
01458   void rollback(ConstRestorationPt Point);
01459   /// Get the current restoration point.
01460   ConstRestorationPt getRestorationPoint() const;
01461 
01462   /// \name API for IR modification with state keeping to support rollback.
01463   /// @{
01464   /// Same as Instruction::setOperand.
01465   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
01466   /// Same as Instruction::eraseFromParent.
01467   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
01468   /// Same as Value::replaceAllUsesWith.
01469   void replaceAllUsesWith(Instruction *Inst, Value *New);
01470   /// Same as Value::mutateType.
01471   void mutateType(Instruction *Inst, Type *NewTy);
01472   /// Same as IRBuilder::createTrunc.
01473   Value *createTrunc(Instruction *Opnd, Type *Ty);
01474   /// Same as IRBuilder::createSExt.
01475   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
01476   /// Same as IRBuilder::createZExt.
01477   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
01478   /// Same as Instruction::moveBefore.
01479   void moveBefore(Instruction *Inst, Instruction *Before);
01480   /// @}
01481 
01482 private:
01483   /// The ordered list of actions made so far.
01484   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
01485   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
01486 };
01487 
01488 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
01489                                           Value *NewVal) {
01490   Actions.push_back(
01491       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
01492 }
01493 
01494 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
01495                                                 Value *NewVal) {
01496   Actions.push_back(
01497       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
01498 }
01499 
01500 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
01501                                                   Value *New) {
01502   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
01503 }
01504 
01505 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
01506   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
01507 }
01508 
01509 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
01510                                              Type *Ty) {
01511   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
01512   Value *Val = Ptr->getBuiltValue();
01513   Actions.push_back(std::move(Ptr));
01514   return Val;
01515 }
01516 
01517 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
01518                                             Value *Opnd, Type *Ty) {
01519   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
01520   Value *Val = Ptr->getBuiltValue();
01521   Actions.push_back(std::move(Ptr));
01522   return Val;
01523 }
01524 
01525 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
01526                                             Value *Opnd, Type *Ty) {
01527   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
01528   Value *Val = Ptr->getBuiltValue();
01529   Actions.push_back(std::move(Ptr));
01530   return Val;
01531 }
01532 
01533 void TypePromotionTransaction::moveBefore(Instruction *Inst,
01534                                           Instruction *Before) {
01535   Actions.push_back(
01536       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
01537 }
01538 
01539 TypePromotionTransaction::ConstRestorationPt
01540 TypePromotionTransaction::getRestorationPoint() const {
01541   return !Actions.empty() ? Actions.back().get() : nullptr;
01542 }
01543 
01544 void TypePromotionTransaction::commit() {
01545   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
01546        ++It)
01547     (*It)->commit();
01548   Actions.clear();
01549 }
01550 
01551 void TypePromotionTransaction::rollback(
01552     TypePromotionTransaction::ConstRestorationPt Point) {
01553   while (!Actions.empty() && Point != Actions.back().get()) {
01554     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
01555     Curr->undo();
01556   }
01557 }
01558 
01559 /// \brief A helper class for matching addressing modes.
01560 ///
01561 /// This encapsulates the logic for matching the target-legal addressing modes.
01562 class AddressingModeMatcher {
01563   SmallVectorImpl<Instruction*> &AddrModeInsts;
01564   const TargetLowering &TLI;
01565 
01566   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
01567   /// the memory instruction that we're computing this address for.
01568   Type *AccessTy;
01569   Instruction *MemoryInst;
01570 
01571   /// AddrMode - This is the addressing mode that we're building up.  This is
01572   /// part of the return value of this addressing mode matching stuff.
01573   ExtAddrMode &AddrMode;
01574 
01575   /// The truncate instruction inserted by other CodeGenPrepare optimizations.
01576   const SetOfInstrs &InsertedTruncs;
01577   /// A map from the instructions to their type before promotion.
01578   InstrToOrigTy &PromotedInsts;
01579   /// The ongoing transaction where every action should be registered.
01580   TypePromotionTransaction &TPT;
01581 
01582   /// IgnoreProfitability - This is set to true when we should not do
01583   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
01584   /// always returns true.
01585   bool IgnoreProfitability;
01586 
01587   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
01588                         const TargetLowering &T, Type *AT,
01589                         Instruction *MI, ExtAddrMode &AM,
01590                         const SetOfInstrs &InsertedTruncs,
01591                         InstrToOrigTy &PromotedInsts,
01592                         TypePromotionTransaction &TPT)
01593       : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
01594         InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
01595     IgnoreProfitability = false;
01596   }
01597 public:
01598 
01599   /// Match - Find the maximal addressing mode that a load/store of V can fold,
01600   /// give an access type of AccessTy.  This returns a list of involved
01601   /// instructions in AddrModeInsts.
01602   /// \p InsertedTruncs The truncate instruction inserted by other
01603   /// CodeGenPrepare
01604   /// optimizations.
01605   /// \p PromotedInsts maps the instructions to their type before promotion.
01606   /// \p The ongoing transaction where every action should be registered.
01607   static ExtAddrMode Match(Value *V, Type *AccessTy,
01608                            Instruction *MemoryInst,
01609                            SmallVectorImpl<Instruction*> &AddrModeInsts,
01610                            const TargetLowering &TLI,
01611                            const SetOfInstrs &InsertedTruncs,
01612                            InstrToOrigTy &PromotedInsts,
01613                            TypePromotionTransaction &TPT) {
01614     ExtAddrMode Result;
01615 
01616     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
01617                                          MemoryInst, Result, InsertedTruncs,
01618                                          PromotedInsts, TPT).MatchAddr(V, 0);
01619     (void)Success; assert(Success && "Couldn't select *anything*?");
01620     return Result;
01621   }
01622 private:
01623   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
01624   bool MatchAddr(Value *V, unsigned Depth);
01625   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
01626                           bool *MovedAway = nullptr);
01627   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
01628                                             ExtAddrMode &AMBefore,
01629                                             ExtAddrMode &AMAfter);
01630   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
01631   bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
01632                              Value *PromotedOperand) const;
01633 };
01634 
01635 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
01636 /// Return true and update AddrMode if this addr mode is legal for the target,
01637 /// false if not.
01638 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
01639                                              unsigned Depth) {
01640   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
01641   // mode.  Just process that directly.
01642   if (Scale == 1)
01643     return MatchAddr(ScaleReg, Depth);
01644 
01645   // If the scale is 0, it takes nothing to add this.
01646   if (Scale == 0)
01647     return true;
01648 
01649   // If we already have a scale of this value, we can add to it, otherwise, we
01650   // need an available scale field.
01651   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
01652     return false;
01653 
01654   ExtAddrMode TestAddrMode = AddrMode;
01655 
01656   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
01657   // [A+B + A*7] -> [B+A*8].
01658   TestAddrMode.Scale += Scale;
01659   TestAddrMode.ScaledReg = ScaleReg;
01660 
01661   // If the new address isn't legal, bail out.
01662   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
01663     return false;
01664 
01665   // It was legal, so commit it.
01666   AddrMode = TestAddrMode;
01667 
01668   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
01669   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
01670   // X*Scale + C*Scale to addr mode.
01671   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
01672   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
01673       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
01674     TestAddrMode.ScaledReg = AddLHS;
01675     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
01676 
01677     // If this addressing mode is legal, commit it and remember that we folded
01678     // this instruction.
01679     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
01680       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
01681       AddrMode = TestAddrMode;
01682       return true;
01683     }
01684   }
01685 
01686   // Otherwise, not (x+c)*scale, just return what we have.
01687   return true;
01688 }
01689 
01690 /// MightBeFoldableInst - This is a little filter, which returns true if an
01691 /// addressing computation involving I might be folded into a load/store
01692 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
01693 /// the set of instructions that MatchOperationAddr can.
01694 static bool MightBeFoldableInst(Instruction *I) {
01695   switch (I->getOpcode()) {
01696   case Instruction::BitCast:
01697   case Instruction::AddrSpaceCast:
01698     // Don't touch identity bitcasts.
01699     if (I->getType() == I->getOperand(0)->getType())
01700       return false;
01701     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
01702   case Instruction::PtrToInt:
01703     // PtrToInt is always a noop, as we know that the int type is pointer sized.
01704     return true;
01705   case Instruction::IntToPtr:
01706     // We know the input is intptr_t, so this is foldable.
01707     return true;
01708   case Instruction::Add:
01709     return true;
01710   case Instruction::Mul:
01711   case Instruction::Shl:
01712     // Can only handle X*C and X << C.
01713     return isa<ConstantInt>(I->getOperand(1));
01714   case Instruction::GetElementPtr:
01715     return true;
01716   default:
01717     return false;
01718   }
01719 }
01720 
01721 /// \brief Hepler class to perform type promotion.
01722 class TypePromotionHelper {
01723   /// \brief Utility function to check whether or not a sign or zero extension
01724   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
01725   /// either using the operands of \p Inst or promoting \p Inst.
01726   /// The type of the extension is defined by \p IsSExt.
01727   /// In other words, check if:
01728   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
01729   /// #1 Promotion applies:
01730   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
01731   /// #2 Operand reuses:
01732   /// ext opnd1 to ConsideredExtType.
01733   /// \p PromotedInsts maps the instructions to their type before promotion.
01734   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
01735                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
01736 
01737   /// \brief Utility function to determine if \p OpIdx should be promoted when
01738   /// promoting \p Inst.
01739   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
01740     if (isa<SelectInst>(Inst) && OpIdx == 0)
01741       return false;
01742     return true;
01743   }
01744 
01745   /// \brief Utility function to promote the operand of \p Ext when this
01746   /// operand is a promotable trunc or sext or zext.
01747   /// \p PromotedInsts maps the instructions to their type before promotion.
01748   /// \p CreatedInsts[out] contains how many non-free instructions have been
01749   /// created to promote the operand of Ext.
01750   /// Should never be called directly.
01751   /// \return The promoted value which is used instead of Ext.
01752   static Value *promoteOperandForTruncAndAnyExt(Instruction *Ext,
01753                                                 TypePromotionTransaction &TPT,
01754                                                 InstrToOrigTy &PromotedInsts,
01755                                                 unsigned &CreatedInsts);
01756 
01757   /// \brief Utility function to promote the operand of \p Ext when this
01758   /// operand is promotable and is not a supported trunc or sext.
01759   /// \p PromotedInsts maps the instructions to their type before promotion.
01760   /// \p CreatedInsts[out] contains how many non-free instructions have been
01761   /// created to promote the operand of Ext.
01762   /// Should never be called directly.
01763   /// \return The promoted value which is used instead of Ext.
01764   static Value *promoteOperandForOther(Instruction *Ext,
01765                                        TypePromotionTransaction &TPT,
01766                                        InstrToOrigTy &PromotedInsts,
01767                                        unsigned &CreatedInsts, bool IsSExt);
01768 
01769   /// \see promoteOperandForOther.
01770   static Value *signExtendOperandForOther(Instruction *Ext,
01771                                           TypePromotionTransaction &TPT,
01772                                           InstrToOrigTy &PromotedInsts,
01773                                           unsigned &CreatedInsts) {
01774     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, true);
01775   }
01776 
01777   /// \see promoteOperandForOther.
01778   static Value *zeroExtendOperandForOther(Instruction *Ext,
01779                                           TypePromotionTransaction &TPT,
01780                                           InstrToOrigTy &PromotedInsts,
01781                                           unsigned &CreatedInsts) {
01782     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInsts, false);
01783   }
01784 
01785 public:
01786   /// Type for the utility function that promotes the operand of Ext.
01787   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
01788                            InstrToOrigTy &PromotedInsts,
01789                            unsigned &CreatedInsts);
01790   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
01791   /// action to promote the operand of \p Ext instead of using Ext.
01792   /// \return NULL if no promotable action is possible with the current
01793   /// sign extension.
01794   /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
01795   /// the others CodeGenPrepare optimizations. This information is important
01796   /// because we do not want to promote these instructions as CodeGenPrepare
01797   /// will reinsert them later. Thus creating an infinite loop: create/remove.
01798   /// \p PromotedInsts maps the instructions to their type before promotion.
01799   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedTruncs,
01800                           const TargetLowering &TLI,
01801                           const InstrToOrigTy &PromotedInsts);
01802 };
01803 
01804 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
01805                                         Type *ConsideredExtType,
01806                                         const InstrToOrigTy &PromotedInsts,
01807                                         bool IsSExt) {
01808   // We can always get through zext.
01809   if (isa<ZExtInst>(Inst))
01810     return true;
01811 
01812   // sext(sext) is ok too.
01813   if (IsSExt && isa<SExtInst>(Inst))
01814     return true;
01815 
01816   // We can get through binary operator, if it is legal. In other words, the
01817   // binary operator must have a nuw or nsw flag.
01818   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
01819   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
01820       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
01821        (IsSExt && BinOp->hasNoSignedWrap())))
01822     return true;
01823 
01824   // Check if we can do the following simplification.
01825   // ext(trunc(opnd)) --> ext(opnd)
01826   if (!isa<TruncInst>(Inst))
01827     return false;
01828 
01829   Value *OpndVal = Inst->getOperand(0);
01830   // Check if we can use this operand in the extension.
01831   // If the type is larger than the result type of the extension,
01832   // we cannot.
01833   if (OpndVal->getType()->getIntegerBitWidth() >
01834       ConsideredExtType->getIntegerBitWidth())
01835     return false;
01836 
01837   // If the operand of the truncate is not an instruction, we will not have
01838   // any information on the dropped bits.
01839   // (Actually we could for constant but it is not worth the extra logic).
01840   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
01841   if (!Opnd)
01842     return false;
01843 
01844   // Check if the source of the type is narrow enough.
01845   // I.e., check that trunc just drops extended bits of the same kind of
01846   // the extension.
01847   // #1 get the type of the operand and check the kind of the extended bits.
01848   const Type *OpndType;
01849   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
01850   if (It != PromotedInsts.end() && It->second.IsSExt == IsSExt)
01851     OpndType = It->second.Ty;
01852   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
01853     OpndType = Opnd->getOperand(0)->getType();
01854   else
01855     return false;
01856 
01857   // #2 check that the truncate just drop extended bits.
01858   if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
01859     return true;
01860 
01861   return false;
01862 }
01863 
01864 TypePromotionHelper::Action TypePromotionHelper::getAction(
01865     Instruction *Ext, const SetOfInstrs &InsertedTruncs,
01866     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
01867   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
01868          "Unexpected instruction type");
01869   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
01870   Type *ExtTy = Ext->getType();
01871   bool IsSExt = isa<SExtInst>(Ext);
01872   // If the operand of the extension is not an instruction, we cannot
01873   // get through.
01874   // If it, check we can get through.
01875   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
01876     return nullptr;
01877 
01878   // Do not promote if the operand has been added by codegenprepare.
01879   // Otherwise, it means we are undoing an optimization that is likely to be
01880   // redone, thus causing potential infinite loop.
01881   if (isa<TruncInst>(ExtOpnd) && InsertedTruncs.count(ExtOpnd))
01882     return nullptr;
01883 
01884   // SExt or Trunc instructions.
01885   // Return the related handler.
01886   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
01887       isa<ZExtInst>(ExtOpnd))
01888     return promoteOperandForTruncAndAnyExt;
01889 
01890   // Regular instruction.
01891   // Abort early if we will have to insert non-free instructions.
01892   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
01893     return nullptr;
01894   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
01895 }
01896 
01897 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
01898     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
01899     InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
01900   // By construction, the operand of SExt is an instruction. Otherwise we cannot
01901   // get through it and this method should not be called.
01902   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
01903   Value *ExtVal = SExt;
01904   if (isa<ZExtInst>(SExtOpnd)) {
01905     // Replace s|zext(zext(opnd))
01906     // => zext(opnd).
01907     Value *ZExt =
01908         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
01909     TPT.replaceAllUsesWith(SExt, ZExt);
01910     TPT.eraseInstruction(SExt);
01911     ExtVal = ZExt;
01912   } else {
01913     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
01914     // => z|sext(opnd).
01915     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
01916   }
01917   CreatedInsts = 0;
01918 
01919   // Remove dead code.
01920   if (SExtOpnd->use_empty())
01921     TPT.eraseInstruction(SExtOpnd);
01922 
01923   // Check if the extension is still needed.
01924   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
01925   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
01926     return ExtVal;
01927 
01928   // At this point we have: ext ty opnd to ty.
01929   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
01930   Value *NextVal = ExtInst->getOperand(0);
01931   TPT.eraseInstruction(ExtInst, NextVal);
01932   return NextVal;
01933 }
01934 
01935 Value *TypePromotionHelper::promoteOperandForOther(
01936     Instruction *Ext, TypePromotionTransaction &TPT,
01937     InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts, bool IsSExt) {
01938   // By construction, the operand of Ext is an instruction. Otherwise we cannot
01939   // get through it and this method should not be called.
01940   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
01941   CreatedInsts = 0;
01942   if (!ExtOpnd->hasOneUse()) {
01943     // ExtOpnd will be promoted.
01944     // All its uses, but Ext, will need to use a truncated value of the
01945     // promoted version.
01946     // Create the truncate now.
01947     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
01948     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
01949       ITrunc->removeFromParent();
01950       // Insert it just after the definition.
01951       ITrunc->insertAfter(ExtOpnd);
01952     }
01953 
01954     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
01955     // Restore the operand of Ext (which has been replace by the previous call
01956     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
01957     TPT.setOperand(Ext, 0, ExtOpnd);
01958   }
01959 
01960   // Get through the Instruction:
01961   // 1. Update its type.
01962   // 2. Replace the uses of Ext by Inst.
01963   // 3. Extend each operand that needs to be extended.
01964 
01965   // Remember the original type of the instruction before promotion.
01966   // This is useful to know that the high bits are sign extended bits.
01967   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
01968       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
01969   // Step #1.
01970   TPT.mutateType(ExtOpnd, Ext->getType());
01971   // Step #2.
01972   TPT.replaceAllUsesWith(Ext, ExtOpnd);
01973   // Step #3.
01974   Instruction *ExtForOpnd = Ext;
01975 
01976   DEBUG(dbgs() << "Propagate Ext to operands\n");
01977   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
01978        ++OpIdx) {
01979     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
01980     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
01981         !shouldExtOperand(ExtOpnd, OpIdx)) {
01982       DEBUG(dbgs() << "No need to propagate\n");
01983       continue;
01984     }
01985     // Check if we can statically extend the operand.
01986     Value *Opnd = ExtOpnd->getOperand(OpIdx);
01987     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
01988       DEBUG(dbgs() << "Statically extend\n");
01989       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
01990       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
01991                             : Cst->getValue().zext(BitWidth);
01992       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
01993       continue;
01994     }
01995     // UndefValue are typed, so we have to statically sign extend them.
01996     if (isa<UndefValue>(Opnd)) {
01997       DEBUG(dbgs() << "Statically extend\n");
01998       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
01999       continue;
02000     }
02001 
02002     // Otherwise we have to explicity sign extend the operand.
02003     // Check if Ext was reused to extend an operand.
02004     if (!ExtForOpnd) {
02005       // If yes, create a new one.
02006       DEBUG(dbgs() << "More operands to ext\n");
02007       ExtForOpnd =
02008           cast<Instruction>(IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
02009                                    : TPT.createZExt(Ext, Opnd, Ext->getType()));
02010       ++CreatedInsts;
02011     }
02012 
02013     TPT.setOperand(ExtForOpnd, 0, Opnd);
02014 
02015     // Move the sign extension before the insertion point.
02016     TPT.moveBefore(ExtForOpnd, ExtOpnd);
02017     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
02018     // If more sext are required, new instructions will have to be created.
02019     ExtForOpnd = nullptr;
02020   }
02021   if (ExtForOpnd == Ext) {
02022     DEBUG(dbgs() << "Extension is useless now\n");
02023     TPT.eraseInstruction(Ext);
02024   }
02025   return ExtOpnd;
02026 }
02027 
02028 /// IsPromotionProfitable - Check whether or not promoting an instruction
02029 /// to a wider type was profitable.
02030 /// \p MatchedSize gives the number of instructions that have been matched
02031 /// in the addressing mode after the promotion was applied.
02032 /// \p SizeWithPromotion gives the number of created instructions for
02033 /// the promotion plus the number of instructions that have been
02034 /// matched in the addressing mode before the promotion.
02035 /// \p PromotedOperand is the value that has been promoted.
02036 /// \return True if the promotion is profitable, false otherwise.
02037 bool
02038 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
02039                                              unsigned SizeWithPromotion,
02040                                              Value *PromotedOperand) const {
02041   // We folded less instructions than what we created to promote the operand.
02042   // This is not profitable.
02043   if (MatchedSize < SizeWithPromotion)
02044     return false;
02045   if (MatchedSize > SizeWithPromotion)
02046     return true;
02047   // The promotion is neutral but it may help folding the sign extension in
02048   // loads for instance.
02049   // Check that we did not create an illegal instruction.
02050   Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
02051   if (!PromotedInst)
02052     return false;
02053   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
02054   // If the ISDOpcode is undefined, it was undefined before the promotion.
02055   if (!ISDOpcode)
02056     return true;
02057   // Otherwise, check if the promoted instruction is legal or not.
02058   return TLI.isOperationLegalOrCustom(
02059       ISDOpcode, TLI.getValueType(PromotedInst->getType()));
02060 }
02061 
02062 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
02063 /// fold the operation into the addressing mode.  If so, update the addressing
02064 /// mode and return true, otherwise return false without modifying AddrMode.
02065 /// If \p MovedAway is not NULL, it contains the information of whether or
02066 /// not AddrInst has to be folded into the addressing mode on success.
02067 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
02068 /// because it has been moved away.
02069 /// Thus AddrInst must not be added in the matched instructions.
02070 /// This state can happen when AddrInst is a sext, since it may be moved away.
02071 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
02072 /// not be referenced anymore.
02073 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
02074                                                unsigned Depth,
02075                                                bool *MovedAway) {
02076   // Avoid exponential behavior on extremely deep expression trees.
02077   if (Depth >= 5) return false;
02078 
02079   // By default, all matched instructions stay in place.
02080   if (MovedAway)
02081     *MovedAway = false;
02082 
02083   switch (Opcode) {
02084   case Instruction::PtrToInt:
02085     // PtrToInt is always a noop, as we know that the int type is pointer sized.
02086     return MatchAddr(AddrInst->getOperand(0), Depth);
02087   case Instruction::IntToPtr:
02088     // This inttoptr is a no-op if the integer type is pointer sized.
02089     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
02090         TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
02091       return MatchAddr(AddrInst->getOperand(0), Depth);
02092     return false;
02093   case Instruction::BitCast:
02094   case Instruction::AddrSpaceCast:
02095     // BitCast is always a noop, and we can handle it as long as it is
02096     // int->int or pointer->pointer (we don't want int<->fp or something).
02097     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
02098          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
02099         // Don't touch identity bitcasts.  These were probably put here by LSR,
02100         // and we don't want to mess around with them.  Assume it knows what it
02101         // is doing.
02102         AddrInst->getOperand(0)->getType() != AddrInst->getType())
02103       return MatchAddr(AddrInst->getOperand(0), Depth);
02104     return false;
02105   case Instruction::Add: {
02106     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
02107     ExtAddrMode BackupAddrMode = AddrMode;
02108     unsigned OldSize = AddrModeInsts.size();
02109     // Start a transaction at this point.
02110     // The LHS may match but not the RHS.
02111     // Therefore, we need a higher level restoration point to undo partially
02112     // matched operation.
02113     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
02114         TPT.getRestorationPoint();
02115 
02116     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
02117         MatchAddr(AddrInst->getOperand(0), Depth+1))
02118       return true;
02119 
02120     // Restore the old addr mode info.
02121     AddrMode = BackupAddrMode;
02122     AddrModeInsts.resize(OldSize);
02123     TPT.rollback(LastKnownGood);
02124 
02125     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
02126     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
02127         MatchAddr(AddrInst->getOperand(1), Depth+1))
02128       return true;
02129 
02130     // Otherwise we definitely can't merge the ADD in.
02131     AddrMode = BackupAddrMode;
02132     AddrModeInsts.resize(OldSize);
02133     TPT.rollback(LastKnownGood);
02134     break;
02135   }
02136   //case Instruction::Or:
02137   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
02138   //break;
02139   case Instruction::Mul:
02140   case Instruction::Shl: {
02141     // Can only handle X*C and X << C.
02142     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
02143     if (!RHS)
02144       return false;
02145     int64_t Scale = RHS->getSExtValue();
02146     if (Opcode == Instruction::Shl)
02147       Scale = 1LL << Scale;
02148 
02149     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
02150   }
02151   case Instruction::GetElementPtr: {
02152     // Scan the GEP.  We check it if it contains constant offsets and at most
02153     // one variable offset.
02154     int VariableOperand = -1;
02155     unsigned VariableScale = 0;
02156 
02157     int64_t ConstantOffset = 0;
02158     const DataLayout *TD = TLI.getDataLayout();
02159     gep_type_iterator GTI = gep_type_begin(AddrInst);
02160     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
02161       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
02162         const StructLayout *SL = TD->getStructLayout(STy);
02163         unsigned Idx =
02164           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
02165         ConstantOffset += SL->getElementOffset(Idx);
02166       } else {
02167         uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
02168         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
02169           ConstantOffset += CI->getSExtValue()*TypeSize;
02170         } else if (TypeSize) {  // Scales of zero don't do anything.
02171           // We only allow one variable index at the moment.
02172           if (VariableOperand != -1)
02173             return false;
02174 
02175           // Remember the variable index.
02176           VariableOperand = i;
02177           VariableScale = TypeSize;
02178         }
02179       }
02180     }
02181 
02182     // A common case is for the GEP to only do a constant offset.  In this case,
02183     // just add it to the disp field and check validity.
02184     if (VariableOperand == -1) {
02185       AddrMode.BaseOffs += ConstantOffset;
02186       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
02187         // Check to see if we can fold the base pointer in too.
02188         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
02189           return true;
02190       }
02191       AddrMode.BaseOffs -= ConstantOffset;
02192       return false;
02193     }
02194 
02195     // Save the valid addressing mode in case we can't match.
02196     ExtAddrMode BackupAddrMode = AddrMode;
02197     unsigned OldSize = AddrModeInsts.size();
02198 
02199     // See if the scale and offset amount is valid for this target.
02200     AddrMode.BaseOffs += ConstantOffset;
02201 
02202     // Match the base operand of the GEP.
02203     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
02204       // If it couldn't be matched, just stuff the value in a register.
02205       if (AddrMode.HasBaseReg) {
02206         AddrMode = BackupAddrMode;
02207         AddrModeInsts.resize(OldSize);
02208         return false;
02209       }
02210       AddrMode.HasBaseReg = true;
02211       AddrMode.BaseReg = AddrInst->getOperand(0);
02212     }
02213 
02214     // Match the remaining variable portion of the GEP.
02215     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
02216                           Depth)) {
02217       // If it couldn't be matched, try stuffing the base into a register
02218       // instead of matching it, and retrying the match of the scale.
02219       AddrMode = BackupAddrMode;
02220       AddrModeInsts.resize(OldSize);
02221       if (AddrMode.HasBaseReg)
02222         return false;
02223       AddrMode.HasBaseReg = true;
02224       AddrMode.BaseReg = AddrInst->getOperand(0);
02225       AddrMode.BaseOffs += ConstantOffset;
02226       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
02227                             VariableScale, Depth)) {
02228         // If even that didn't work, bail.
02229         AddrMode = BackupAddrMode;
02230         AddrModeInsts.resize(OldSize);
02231         return false;
02232       }
02233     }
02234 
02235     return true;
02236   }
02237   case Instruction::SExt:
02238   case Instruction::ZExt: {
02239     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
02240     if (!Ext)
02241       return false;
02242 
02243     // Try to move this ext out of the way of the addressing mode.
02244     // Ask for a method for doing so.
02245     TypePromotionHelper::Action TPH =
02246         TypePromotionHelper::getAction(Ext, InsertedTruncs, TLI, PromotedInsts);
02247     if (!TPH)
02248       return false;
02249 
02250     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
02251         TPT.getRestorationPoint();
02252     unsigned CreatedInsts = 0;
02253     Value *PromotedOperand = TPH(Ext, TPT, PromotedInsts, CreatedInsts);
02254     // SExt has been moved away.
02255     // Thus either it will be rematched later in the recursive calls or it is
02256     // gone. Anyway, we must not fold it into the addressing mode at this point.
02257     // E.g.,
02258     // op = add opnd, 1
02259     // idx = ext op
02260     // addr = gep base, idx
02261     // is now:
02262     // promotedOpnd = ext opnd            <- no match here
02263     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
02264     // addr = gep base, op                <- match
02265     if (MovedAway)
02266       *MovedAway = true;
02267 
02268     assert(PromotedOperand &&
02269            "TypePromotionHelper should have filtered out those cases");
02270 
02271     ExtAddrMode BackupAddrMode = AddrMode;
02272     unsigned OldSize = AddrModeInsts.size();
02273 
02274     if (!MatchAddr(PromotedOperand, Depth) ||
02275         !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
02276                                PromotedOperand)) {
02277       AddrMode = BackupAddrMode;
02278       AddrModeInsts.resize(OldSize);
02279       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
02280       TPT.rollback(LastKnownGood);
02281       return false;
02282     }
02283     return true;
02284   }
02285   }
02286   return false;
02287 }
02288 
02289 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
02290 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
02291 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
02292 /// or intptr_t for the target.
02293 ///
02294 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
02295   // Start a transaction at this point that we will rollback if the matching
02296   // fails.
02297   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
02298       TPT.getRestorationPoint();
02299   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
02300     // Fold in immediates if legal for the target.
02301     AddrMode.BaseOffs += CI->getSExtValue();
02302     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
02303       return true;
02304     AddrMode.BaseOffs -= CI->getSExtValue();
02305   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
02306     // If this is a global variable, try to fold it into the addressing mode.
02307     if (!AddrMode.BaseGV) {
02308       AddrMode.BaseGV = GV;
02309       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
02310         return true;
02311       AddrMode.BaseGV = nullptr;
02312     }
02313   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
02314     ExtAddrMode BackupAddrMode = AddrMode;
02315     unsigned OldSize = AddrModeInsts.size();
02316 
02317     // Check to see if it is possible to fold this operation.
02318     bool MovedAway = false;
02319     if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
02320       // This instruction may have been move away. If so, there is nothing
02321       // to check here.
02322       if (MovedAway)
02323         return true;
02324       // Okay, it's possible to fold this.  Check to see if it is actually
02325       // *profitable* to do so.  We use a simple cost model to avoid increasing
02326       // register pressure too much.
02327       if (I->hasOneUse() ||
02328           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
02329         AddrModeInsts.push_back(I);
02330         return true;
02331       }
02332 
02333       // It isn't profitable to do this, roll back.
02334       //cerr << "NOT FOLDING: " << *I;
02335       AddrMode = BackupAddrMode;
02336       AddrModeInsts.resize(OldSize);
02337       TPT.rollback(LastKnownGood);
02338     }
02339   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
02340     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
02341       return true;
02342     TPT.rollback(LastKnownGood);
02343   } else if (isa<ConstantPointerNull>(Addr)) {
02344     // Null pointer gets folded without affecting the addressing mode.
02345     return true;
02346   }
02347 
02348   // Worse case, the target should support [reg] addressing modes. :)
02349   if (!AddrMode.HasBaseReg) {
02350     AddrMode.HasBaseReg = true;
02351     AddrMode.BaseReg = Addr;
02352     // Still check for legality in case the target supports [imm] but not [i+r].
02353     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
02354       return true;
02355     AddrMode.HasBaseReg = false;
02356     AddrMode.BaseReg = nullptr;
02357   }
02358 
02359   // If the base register is already taken, see if we can do [r+r].
02360   if (AddrMode.Scale == 0) {
02361     AddrMode.Scale = 1;
02362     AddrMode.ScaledReg = Addr;
02363     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
02364       return true;
02365     AddrMode.Scale = 0;
02366     AddrMode.ScaledReg = nullptr;
02367   }
02368   // Couldn't match.
02369   TPT.rollback(LastKnownGood);
02370   return false;
02371 }
02372 
02373 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
02374 /// inline asm call are due to memory operands.  If so, return true, otherwise
02375 /// return false.
02376 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
02377                                     const TargetLowering &TLI) {
02378   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
02379   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
02380     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
02381 
02382     // Compute the constraint code and ConstraintType to use.
02383     TLI.ComputeConstraintToUse(OpInfo, SDValue());
02384 
02385     // If this asm operand is our Value*, and if it isn't an indirect memory
02386     // operand, we can't fold it!
02387     if (OpInfo.CallOperandVal == OpVal &&
02388         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
02389          !OpInfo.isIndirect))
02390       return false;
02391   }
02392 
02393   return true;
02394 }
02395 
02396 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
02397 /// memory use.  If we find an obviously non-foldable instruction, return true.
02398 /// Add the ultimately found memory instructions to MemoryUses.
02399 static bool FindAllMemoryUses(Instruction *I,
02400                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
02401                               SmallPtrSetImpl<Instruction*> &ConsideredInsts,
02402                               const TargetLowering &TLI) {
02403   // If we already considered this instruction, we're done.
02404   if (!ConsideredInsts.insert(I).second)
02405     return false;
02406 
02407   // If this is an obviously unfoldable instruction, bail out.
02408   if (!MightBeFoldableInst(I))
02409     return true;
02410 
02411   // Loop over all the uses, recursively processing them.
02412   for (Use &U : I->uses()) {
02413     Instruction *UserI = cast<Instruction>(U.getUser());
02414 
02415     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
02416       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
02417       continue;
02418     }
02419 
02420     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
02421       unsigned opNo = U.getOperandNo();
02422       if (opNo == 0) return true; // Storing addr, not into addr.
02423       MemoryUses.push_back(std::make_pair(SI, opNo));
02424       continue;
02425     }
02426 
02427     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
02428       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
02429       if (!IA) return true;
02430 
02431       // If this is a memory operand, we're cool, otherwise bail out.
02432       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
02433         return true;
02434       continue;
02435     }
02436 
02437     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
02438       return true;
02439   }
02440 
02441   return false;
02442 }
02443 
02444 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
02445 /// the use site that we're folding it into.  If so, there is no cost to
02446 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
02447 /// that we know are live at the instruction already.
02448 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
02449                                                    Value *KnownLive2) {
02450   // If Val is either of the known-live values, we know it is live!
02451   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
02452     return true;
02453 
02454   // All values other than instructions and arguments (e.g. constants) are live.
02455   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
02456 
02457   // If Val is a constant sized alloca in the entry block, it is live, this is
02458   // true because it is just a reference to the stack/frame pointer, which is
02459   // live for the whole function.
02460   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
02461     if (AI->isStaticAlloca())
02462       return true;
02463 
02464   // Check to see if this value is already used in the memory instruction's
02465   // block.  If so, it's already live into the block at the very least, so we
02466   // can reasonably fold it.
02467   return Val->isUsedInBasicBlock(MemoryInst->getParent());
02468 }
02469 
02470 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
02471 /// mode of the machine to fold the specified instruction into a load or store
02472 /// that ultimately uses it.  However, the specified instruction has multiple
02473 /// uses.  Given this, it may actually increase register pressure to fold it
02474 /// into the load.  For example, consider this code:
02475 ///
02476 ///     X = ...
02477 ///     Y = X+1
02478 ///     use(Y)   -> nonload/store
02479 ///     Z = Y+1
02480 ///     load Z
02481 ///
02482 /// In this case, Y has multiple uses, and can be folded into the load of Z
02483 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
02484 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
02485 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
02486 /// number of computations either.
02487 ///
02488 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
02489 /// X was live across 'load Z' for other reasons, we actually *would* want to
02490 /// fold the addressing mode in the Z case.  This would make Y die earlier.
02491 bool AddressingModeMatcher::
02492 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
02493                                      ExtAddrMode &AMAfter) {
02494   if (IgnoreProfitability) return true;
02495 
02496   // AMBefore is the addressing mode before this instruction was folded into it,
02497   // and AMAfter is the addressing mode after the instruction was folded.  Get
02498   // the set of registers referenced by AMAfter and subtract out those
02499   // referenced by AMBefore: this is the set of values which folding in this
02500   // address extends the lifetime of.
02501   //
02502   // Note that there are only two potential values being referenced here,
02503   // BaseReg and ScaleReg (global addresses are always available, as are any
02504   // folded immediates).
02505   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
02506 
02507   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
02508   // lifetime wasn't extended by adding this instruction.
02509   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
02510     BaseReg = nullptr;
02511   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
02512     ScaledReg = nullptr;
02513 
02514   // If folding this instruction (and it's subexprs) didn't extend any live
02515   // ranges, we're ok with it.
02516   if (!BaseReg && !ScaledReg)
02517     return true;
02518 
02519   // If all uses of this instruction are ultimately load/store/inlineasm's,
02520   // check to see if their addressing modes will include this instruction.  If
02521   // so, we can fold it into all uses, so it doesn't matter if it has multiple
02522   // uses.
02523   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
02524   SmallPtrSet<Instruction*, 16> ConsideredInsts;
02525   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
02526     return false;  // Has a non-memory, non-foldable use!
02527 
02528   // Now that we know that all uses of this instruction are part of a chain of
02529   // computation involving only operations that could theoretically be folded
02530   // into a memory use, loop over each of these uses and see if they could
02531   // *actually* fold the instruction.
02532   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
02533   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
02534     Instruction *User = MemoryUses[i].first;
02535     unsigned OpNo = MemoryUses[i].second;
02536 
02537     // Get the access type of this use.  If the use isn't a pointer, we don't
02538     // know what it accesses.
02539     Value *Address = User->getOperand(OpNo);
02540     if (!Address->getType()->isPointerTy())
02541       return false;
02542     Type *AddressAccessTy = Address->getType()->getPointerElementType();
02543 
02544     // Do a match against the root of this address, ignoring profitability. This
02545     // will tell us if the addressing mode for the memory operation will
02546     // *actually* cover the shared instruction.
02547     ExtAddrMode Result;
02548     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
02549         TPT.getRestorationPoint();
02550     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
02551                                   MemoryInst, Result, InsertedTruncs,
02552                                   PromotedInsts, TPT);
02553     Matcher.IgnoreProfitability = true;
02554     bool Success = Matcher.MatchAddr(Address, 0);
02555     (void)Success; assert(Success && "Couldn't select *anything*?");
02556 
02557     // The match was to check the profitability, the changes made are not
02558     // part of the original matcher. Therefore, they should be dropped
02559     // otherwise the original matcher will not present the right state.
02560     TPT.rollback(LastKnownGood);
02561 
02562     // If the match didn't cover I, then it won't be shared by it.
02563     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
02564                   I) == MatchedAddrModeInsts.end())
02565       return false;
02566 
02567     MatchedAddrModeInsts.clear();
02568   }
02569 
02570   return true;
02571 }
02572 
02573 } // end anonymous namespace
02574 
02575 /// IsNonLocalValue - Return true if the specified values are defined in a
02576 /// different basic block than BB.
02577 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
02578   if (Instruction *I = dyn_cast<Instruction>(V))
02579     return I->getParent() != BB;
02580   return false;
02581 }
02582 
02583 /// OptimizeMemoryInst - Load and Store Instructions often have
02584 /// addressing modes that can do significant amounts of computation.  As such,
02585 /// instruction selection will try to get the load or store to do as much
02586 /// computation as possible for the program.  The problem is that isel can only
02587 /// see within a single block.  As such, we sink as much legal addressing mode
02588 /// stuff into the block as possible.
02589 ///
02590 /// This method is used to optimize both load/store and inline asms with memory
02591 /// operands.
02592 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
02593                                         Type *AccessTy) {
02594   Value *Repl = Addr;
02595 
02596   // Try to collapse single-value PHI nodes.  This is necessary to undo
02597   // unprofitable PRE transformations.
02598   SmallVector<Value*, 8> worklist;
02599   SmallPtrSet<Value*, 16> Visited;
02600   worklist.push_back(Addr);
02601 
02602   // Use a worklist to iteratively look through PHI nodes, and ensure that
02603   // the addressing mode obtained from the non-PHI roots of the graph
02604   // are equivalent.
02605   Value *Consensus = nullptr;
02606   unsigned NumUsesConsensus = 0;
02607   bool IsNumUsesConsensusValid = false;
02608   SmallVector<Instruction*, 16> AddrModeInsts;
02609   ExtAddrMode AddrMode;
02610   TypePromotionTransaction TPT;
02611   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
02612       TPT.getRestorationPoint();
02613   while (!worklist.empty()) {
02614     Value *V = worklist.back();
02615     worklist.pop_back();
02616 
02617     // Break use-def graph loops.
02618     if (!Visited.insert(V).second) {
02619       Consensus = nullptr;
02620       break;
02621     }
02622 
02623     // For a PHI node, push all of its incoming values.
02624     if (PHINode *P = dyn_cast<PHINode>(V)) {
02625       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
02626         worklist.push_back(P->getIncomingValue(i));
02627       continue;
02628     }
02629 
02630     // For non-PHIs, determine the addressing mode being computed.
02631     SmallVector<Instruction*, 16> NewAddrModeInsts;
02632     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
02633         V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
02634         PromotedInsts, TPT);
02635 
02636     // This check is broken into two cases with very similar code to avoid using
02637     // getNumUses() as much as possible. Some values have a lot of uses, so
02638     // calling getNumUses() unconditionally caused a significant compile-time
02639     // regression.
02640     if (!Consensus) {
02641       Consensus = V;
02642       AddrMode = NewAddrMode;
02643       AddrModeInsts = NewAddrModeInsts;
02644       continue;
02645     } else if (NewAddrMode == AddrMode) {
02646       if (!IsNumUsesConsensusValid) {
02647         NumUsesConsensus = Consensus->getNumUses();
02648         IsNumUsesConsensusValid = true;
02649       }
02650 
02651       // Ensure that the obtained addressing mode is equivalent to that obtained
02652       // for all other roots of the PHI traversal.  Also, when choosing one
02653       // such root as representative, select the one with the most uses in order
02654       // to keep the cost modeling heuristics in AddressingModeMatcher
02655       // applicable.
02656       unsigned NumUses = V->getNumUses();
02657       if (NumUses > NumUsesConsensus) {
02658         Consensus = V;
02659         NumUsesConsensus = NumUses;
02660         AddrModeInsts = NewAddrModeInsts;
02661       }
02662       continue;
02663     }
02664 
02665     Consensus = nullptr;
02666     break;
02667   }
02668 
02669   // If the addressing mode couldn't be determined, or if multiple different
02670   // ones were determined, bail out now.
02671   if (!Consensus) {
02672     TPT.rollback(LastKnownGood);
02673     return false;
02674   }
02675   TPT.commit();
02676 
02677   // Check to see if any of the instructions supersumed by this addr mode are
02678   // non-local to I's BB.
02679   bool AnyNonLocal = false;
02680   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
02681     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
02682       AnyNonLocal = true;
02683       break;
02684     }
02685   }
02686 
02687   // If all the instructions matched are already in this BB, don't do anything.
02688   if (!AnyNonLocal) {
02689     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
02690     return false;
02691   }
02692 
02693   // Insert this computation right after this user.  Since our caller is
02694   // scanning from the top of the BB to the bottom, reuse of the expr are
02695   // guaranteed to happen later.
02696   IRBuilder<> Builder(MemoryInst);
02697 
02698   // Now that we determined the addressing expression we want to use and know
02699   // that we have to sink it into this block.  Check to see if we have already
02700   // done this for some other load/store instr in this block.  If so, reuse the
02701   // computation.
02702   Value *&SunkAddr = SunkAddrs[Addr];
02703   if (SunkAddr) {
02704     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
02705                  << *MemoryInst << "\n");
02706     if (SunkAddr->getType() != Addr->getType())
02707       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
02708   } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
02709                TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
02710     // By default, we use the GEP-based method when AA is used later. This
02711     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
02712     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
02713                  << *MemoryInst << "\n");
02714     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
02715     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
02716 
02717     // First, find the pointer.
02718     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
02719       ResultPtr = AddrMode.BaseReg;
02720       AddrMode.BaseReg = nullptr;
02721     }
02722 
02723     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
02724       // We can't add more than one pointer together, nor can we scale a
02725       // pointer (both of which seem meaningless).
02726       if (ResultPtr || AddrMode.Scale != 1)
02727         return false;
02728 
02729       ResultPtr = AddrMode.ScaledReg;
02730       AddrMode.Scale = 0;
02731     }
02732 
02733     if (AddrMode.BaseGV) {
02734       if (ResultPtr)
02735         return false;
02736 
02737       ResultPtr = AddrMode.BaseGV;
02738     }
02739 
02740     // If the real base value actually came from an inttoptr, then the matcher
02741     // will look through it and provide only the integer value. In that case,
02742     // use it here.
02743     if (!ResultPtr && AddrMode.BaseReg) {
02744       ResultPtr =
02745         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
02746       AddrMode.BaseReg = nullptr;
02747     } else if (!ResultPtr && AddrMode.Scale == 1) {
02748       ResultPtr =
02749         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
02750       AddrMode.Scale = 0;
02751     }
02752 
02753     if (!ResultPtr &&
02754         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
02755       SunkAddr = Constant::getNullValue(Addr->getType());
02756     } else if (!ResultPtr) {
02757       return false;
02758     } else {
02759       Type *I8PtrTy =
02760         Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
02761 
02762       // Start with the base register. Do this first so that subsequent address
02763       // matching finds it last, which will prevent it from trying to match it
02764       // as the scaled value in case it happens to be a mul. That would be
02765       // problematic if we've sunk a different mul for the scale, because then
02766       // we'd end up sinking both muls.
02767       if (AddrMode.BaseReg) {
02768         Value *V = AddrMode.BaseReg;
02769         if (V->getType() != IntPtrTy)
02770           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
02771 
02772         ResultIndex = V;
02773       }
02774 
02775       // Add the scale value.
02776       if (AddrMode.Scale) {
02777         Value *V = AddrMode.ScaledReg;
02778         if (V->getType() == IntPtrTy) {
02779           // done.
02780         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
02781                    cast<IntegerType>(V->getType())->getBitWidth()) {
02782           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
02783         } else {
02784           // It is only safe to sign extend the BaseReg if we know that the math
02785           // required to create it did not overflow before we extend it. Since
02786           // the original IR value was tossed in favor of a constant back when
02787           // the AddrMode was created we need to bail out gracefully if widths
02788           // do not match instead of extending it.
02789           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
02790           if (I && (ResultIndex != AddrMode.BaseReg))
02791             I->eraseFromParent();
02792           return false;
02793         }
02794 
02795         if (AddrMode.Scale != 1)
02796           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
02797                                 "sunkaddr");
02798         if (ResultIndex)
02799           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
02800         else
02801           ResultIndex = V;
02802       }
02803 
02804       // Add in the Base Offset if present.
02805       if (AddrMode.BaseOffs) {
02806         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
02807         if (ResultIndex) {
02808           // We need to add this separately from the scale above to help with
02809           // SDAG consecutive load/store merging.
02810           if (ResultPtr->getType() != I8PtrTy)
02811             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
02812           ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
02813         }
02814 
02815         ResultIndex = V;
02816       }
02817 
02818       if (!ResultIndex) {
02819         SunkAddr = ResultPtr;
02820       } else {
02821         if (ResultPtr->getType() != I8PtrTy)
02822           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
02823         SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
02824       }
02825 
02826       if (SunkAddr->getType() != Addr->getType())
02827         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
02828     }
02829   } else {
02830     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
02831                  << *MemoryInst << "\n");
02832     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
02833     Value *Result = nullptr;
02834 
02835     // Start with the base register. Do this first so that subsequent address
02836     // matching finds it last, which will prevent it from trying to match it
02837     // as the scaled value in case it happens to be a mul. That would be
02838     // problematic if we've sunk a different mul for the scale, because then
02839     // we'd end up sinking both muls.
02840     if (AddrMode.BaseReg) {
02841       Value *V = AddrMode.BaseReg;
02842       if (V->getType()->isPointerTy())
02843         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
02844       if (V->getType() != IntPtrTy)
02845         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
02846       Result = V;
02847     }
02848 
02849     // Add the scale value.
02850     if (AddrMode.Scale) {
02851       Value *V = AddrMode.ScaledReg;
02852       if (V->getType() == IntPtrTy) {
02853         // done.
02854       } else if (V->getType()->isPointerTy()) {
02855         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
02856       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
02857                  cast<IntegerType>(V->getType())->getBitWidth()) {
02858         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
02859       } else {
02860         // It is only safe to sign extend the BaseReg if we know that the math
02861         // required to create it did not overflow before we extend it. Since
02862         // the original IR value was tossed in favor of a constant back when
02863         // the AddrMode was created we need to bail out gracefully if widths
02864         // do not match instead of extending it.
02865         Instruction *I = dyn_cast_or_null<Instruction>(Result);
02866         if (I && (Result != AddrMode.BaseReg))
02867           I->eraseFromParent();
02868         return false;
02869       }
02870       if (AddrMode.Scale != 1)
02871         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
02872                               "sunkaddr");
02873       if (Result)
02874         Result = Builder.CreateAdd(Result, V, "sunkaddr");
02875       else
02876         Result = V;
02877     }
02878 
02879     // Add in the BaseGV if present.
02880     if (AddrMode.BaseGV) {
02881       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
02882       if (Result)
02883         Result = Builder.CreateAdd(Result, V, "sunkaddr");
02884       else
02885         Result = V;
02886     }
02887 
02888     // Add in the Base Offset if present.
02889     if (AddrMode.BaseOffs) {
02890       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
02891       if (Result)
02892         Result = Builder.CreateAdd(Result, V, "sunkaddr");
02893       else
02894         Result = V;
02895     }
02896 
02897     if (!Result)
02898       SunkAddr = Constant::getNullValue(Addr->getType());
02899     else
02900       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
02901   }
02902 
02903   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
02904 
02905   // If we have no uses, recursively delete the value and all dead instructions
02906   // using it.
02907   if (Repl->use_empty()) {
02908     // This can cause recursive deletion, which can invalidate our iterator.
02909     // Use a WeakVH to hold onto it in case this happens.
02910     WeakVH IterHandle(CurInstIterator);
02911     BasicBlock *BB = CurInstIterator->getParent();
02912 
02913     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
02914 
02915     if (IterHandle != CurInstIterator) {
02916       // If the iterator instruction was recursively deleted, start over at the
02917       // start of the block.
02918       CurInstIterator = BB->begin();
02919       SunkAddrs.clear();
02920     }
02921   }
02922   ++NumMemoryInsts;
02923   return true;
02924 }
02925 
02926 /// OptimizeInlineAsmInst - If there are any memory operands, use
02927 /// OptimizeMemoryInst to sink their address computing into the block when
02928 /// possible / profitable.
02929 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
02930   bool MadeChange = false;
02931 
02932   TargetLowering::AsmOperandInfoVector
02933     TargetConstraints = TLI->ParseConstraints(CS);
02934   unsigned ArgNo = 0;
02935   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
02936     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
02937 
02938     // Compute the constraint code and ConstraintType to use.
02939     TLI->ComputeConstraintToUse(OpInfo, SDValue());
02940 
02941     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
02942         OpInfo.isIndirect) {
02943       Value *OpVal = CS->getArgOperand(ArgNo++);
02944       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
02945     } else if (OpInfo.Type == InlineAsm::isInput)
02946       ArgNo++;
02947   }
02948 
02949   return MadeChange;
02950 }
02951 
02952 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
02953 /// basic block as the load, unless conditions are unfavorable. This allows
02954 /// SelectionDAG to fold the extend into the load.
02955 ///
02956 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
02957   // Look for a load being extended.
02958   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
02959   if (!LI) return false;
02960 
02961   // If they're already in the same block, there's nothing to do.
02962   if (LI->getParent() == I->getParent())
02963     return false;
02964 
02965   // If the load has other users and the truncate is not free, this probably
02966   // isn't worthwhile.
02967   if (!LI->hasOneUse() &&
02968       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
02969               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
02970       !TLI->isTruncateFree(I->getType(), LI->getType()))
02971     return false;
02972 
02973   // Check whether the target supports casts folded into loads.
02974   unsigned LType;
02975   if (isa<ZExtInst>(I))
02976     LType = ISD::ZEXTLOAD;
02977   else {
02978     assert(isa<SExtInst>(I) && "Unexpected ext type!");
02979     LType = ISD::SEXTLOAD;
02980   }
02981   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
02982     return false;
02983 
02984   // Move the extend into the same block as the load, so that SelectionDAG
02985   // can fold it.
02986   I->removeFromParent();
02987   I->insertAfter(LI);
02988   ++NumExtsMoved;
02989   return true;
02990 }
02991 
02992 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
02993   BasicBlock *DefBB = I->getParent();
02994 
02995   // If the result of a {s|z}ext and its source are both live out, rewrite all
02996   // other uses of the source with result of extension.
02997   Value *Src = I->getOperand(0);
02998   if (Src->hasOneUse())
02999     return false;
03000 
03001   // Only do this xform if truncating is free.
03002   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
03003     return false;
03004 
03005   // Only safe to perform the optimization if the source is also defined in
03006   // this block.
03007   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
03008     return false;
03009 
03010   bool DefIsLiveOut = false;
03011   for (User *U : I->users()) {
03012     Instruction *UI = cast<Instruction>(U);
03013 
03014     // Figure out which BB this ext is used in.
03015     BasicBlock *UserBB = UI->getParent();
03016     if (UserBB == DefBB) continue;
03017     DefIsLiveOut = true;
03018     break;
03019   }
03020   if (!DefIsLiveOut)
03021     return false;
03022 
03023   // Make sure none of the uses are PHI nodes.
03024   for (User *U : Src->users()) {
03025     Instruction *UI = cast<Instruction>(U);
03026     BasicBlock *UserBB = UI->getParent();
03027     if (UserBB == DefBB) continue;
03028     // Be conservative. We don't want this xform to end up introducing
03029     // reloads just before load / store instructions.
03030     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
03031       return false;
03032   }
03033 
03034   // InsertedTruncs - Only insert one trunc in each block once.
03035   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
03036 
03037   bool MadeChange = false;
03038   for (Use &U : Src->uses()) {
03039     Instruction *User = cast<Instruction>(U.getUser());
03040 
03041     // Figure out which BB this ext is used in.
03042     BasicBlock *UserBB = User->getParent();
03043     if (UserBB == DefBB) continue;
03044 
03045     // Both src and def are live in this block. Rewrite the use.
03046     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
03047 
03048     if (!InsertedTrunc) {
03049       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
03050       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
03051       InsertedTruncsSet.insert(InsertedTrunc);
03052     }
03053 
03054     // Replace a use of the {s|z}ext source with a use of the result.
03055     U = InsertedTrunc;
03056     ++NumExtUses;
03057     MadeChange = true;
03058   }
03059 
03060   return MadeChange;
03061 }
03062 
03063 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
03064 /// turned into an explicit branch.
03065 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
03066   // FIXME: This should use the same heuristics as IfConversion to determine
03067   // whether a select is better represented as a branch.  This requires that
03068   // branch probability metadata is preserved for the select, which is not the
03069   // case currently.
03070 
03071   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
03072 
03073   // If the branch is predicted right, an out of order CPU can avoid blocking on
03074   // the compare.  Emit cmovs on compares with a memory operand as branches to
03075   // avoid stalls on the load from memory.  If the compare has more than one use
03076   // there's probably another cmov or setcc around so it's not worth emitting a
03077   // branch.
03078   if (!Cmp)
03079     return false;
03080 
03081   Value *CmpOp0 = Cmp->getOperand(0);
03082   Value *CmpOp1 = Cmp->getOperand(1);
03083 
03084   // We check that the memory operand has one use to avoid uses of the loaded
03085   // value directly after the compare, making branches unprofitable.
03086   return Cmp->hasOneUse() &&
03087          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
03088           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
03089 }
03090 
03091 
03092 /// If we have a SelectInst that will likely profit from branch prediction,
03093 /// turn it into a branch.
03094 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
03095   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
03096 
03097   // Can we convert the 'select' to CF ?
03098   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
03099     return false;
03100 
03101   TargetLowering::SelectSupportKind SelectKind;
03102   if (VectorCond)
03103     SelectKind = TargetLowering::VectorMaskSelect;
03104   else if (SI->getType()->isVectorTy())
03105     SelectKind = TargetLowering::ScalarCondVectorVal;
03106   else
03107     SelectKind = TargetLowering::ScalarValSelect;
03108 
03109   // Do we have efficient codegen support for this kind of 'selects' ?
03110   if (TLI->isSelectSupported(SelectKind)) {
03111     // We have efficient codegen support for the select instruction.
03112     // Check if it is profitable to keep this 'select'.
03113     if (!TLI->isPredictableSelectExpensive() ||
03114         !isFormingBranchFromSelectProfitable(SI))
03115       return false;
03116   }
03117 
03118   ModifiedDT = true;
03119 
03120   // First, we split the block containing the select into 2 blocks.
03121   BasicBlock *StartBlock = SI->getParent();
03122   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
03123   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
03124 
03125   // Create a new block serving as the landing pad for the branch.
03126   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
03127                                              NextBlock->getParent(), NextBlock);
03128 
03129   // Move the unconditional branch from the block with the select in it into our
03130   // landing pad block.
03131   StartBlock->getTerminator()->eraseFromParent();
03132   BranchInst::Create(NextBlock, SmallBlock);
03133 
03134   // Insert the real conditional branch based on the original condition.
03135   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
03136 
03137   // The select itself is replaced with a PHI Node.
03138   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
03139   PN->takeName(SI);
03140   PN->addIncoming(SI->getTrueValue(), StartBlock);
03141   PN->addIncoming(SI->getFalseValue(), SmallBlock);
03142   SI->replaceAllUsesWith(PN);
03143   SI->eraseFromParent();
03144 
03145   // Instruct OptimizeBlock to skip to the next block.
03146   CurInstIterator = StartBlock->end();
03147   ++NumSelectsExpanded;
03148   return true;
03149 }
03150 
03151 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
03152   SmallVector<int, 16> Mask(SVI->getShuffleMask());
03153   int SplatElem = -1;
03154   for (unsigned i = 0; i < Mask.size(); ++i) {
03155     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
03156       return false;
03157     SplatElem = Mask[i];
03158   }
03159 
03160   return true;
03161 }
03162 
03163 /// Some targets have expensive vector shifts if the lanes aren't all the same
03164 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
03165 /// it's often worth sinking a shufflevector splat down to its use so that
03166 /// codegen can spot all lanes are identical.
03167 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
03168   BasicBlock *DefBB = SVI->getParent();
03169 
03170   // Only do this xform if variable vector shifts are particularly expensive.
03171   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
03172     return false;
03173 
03174   // We only expect better codegen by sinking a shuffle if we can recognise a
03175   // constant splat.
03176   if (!isBroadcastShuffle(SVI))
03177     return false;
03178 
03179   // InsertedShuffles - Only insert a shuffle in each block once.
03180   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
03181 
03182   bool MadeChange = false;
03183   for (User *U : SVI->users()) {
03184     Instruction *UI = cast<Instruction>(U);
03185 
03186     // Figure out which BB this ext is used in.
03187     BasicBlock *UserBB = UI->getParent();
03188     if (UserBB == DefBB) continue;
03189 
03190     // For now only apply this when the splat is used by a shift instruction.
03191     if (!UI->isShift()) continue;
03192 
03193     // Everything checks out, sink the shuffle if the user's block doesn't
03194     // already have a copy.
03195     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
03196 
03197     if (!InsertedShuffle) {
03198       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
03199       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
03200                                               SVI->getOperand(1),
03201                                               SVI->getOperand(2), "", InsertPt);
03202     }
03203 
03204     UI->replaceUsesOfWith(SVI, InsertedShuffle);
03205     MadeChange = true;
03206   }
03207 
03208   // If we removed all uses, nuke the shuffle.
03209   if (SVI->use_empty()) {
03210     SVI->eraseFromParent();
03211     MadeChange = true;
03212   }
03213 
03214   return MadeChange;
03215 }
03216 
03217 namespace {
03218 /// \brief Helper class to promote a scalar operation to a vector one.
03219 /// This class is used to move downward extractelement transition.
03220 /// E.g.,
03221 /// a = vector_op <2 x i32>
03222 /// b = extractelement <2 x i32> a, i32 0
03223 /// c = scalar_op b
03224 /// store c
03225 ///
03226 /// =>
03227 /// a = vector_op <2 x i32>
03228 /// c = vector_op a (equivalent to scalar_op on the related lane)
03229 /// * d = extractelement <2 x i32> c, i32 0
03230 /// * store d
03231 /// Assuming both extractelement and store can be combine, we get rid of the
03232 /// transition.
03233 class VectorPromoteHelper {
03234   /// Used to perform some checks on the legality of vector operations.
03235   const TargetLowering &TLI;
03236 
03237   /// Used to estimated the cost of the promoted chain.
03238   const TargetTransformInfo &TTI;
03239 
03240   /// The transition being moved downwards.
03241   Instruction *Transition;
03242   /// The sequence of instructions to be promoted.
03243   SmallVector<Instruction *, 4> InstsToBePromoted;
03244   /// Cost of combining a store and an extract.
03245   unsigned StoreExtractCombineCost;
03246   /// Instruction that will be combined with the transition.
03247   Instruction *CombineInst;
03248 
03249   /// \brief The instruction that represents the current end of the transition.
03250   /// Since we are faking the promotion until we reach the end of the chain
03251   /// of computation, we need a way to get the current end of the transition.
03252   Instruction *getEndOfTransition() const {
03253     if (InstsToBePromoted.empty())
03254       return Transition;
03255     return InstsToBePromoted.back();
03256   }
03257 
03258   /// \brief Return the index of the original value in the transition.
03259   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
03260   /// c, is at index 0.
03261   unsigned getTransitionOriginalValueIdx() const {
03262     assert(isa<ExtractElementInst>(Transition) &&
03263            "Other kind of transitions are not supported yet");
03264     return 0;
03265   }
03266 
03267   /// \brief Return the index of the index in the transition.
03268   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
03269   /// is at index 1.
03270   unsigned getTransitionIdx() const {
03271     assert(isa<ExtractElementInst>(Transition) &&
03272            "Other kind of transitions are not supported yet");
03273     return 1;
03274   }
03275 
03276   /// \brief Get the type of the transition.
03277   /// This is the type of the original value.
03278   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
03279   /// transition is <2 x i32>.
03280   Type *getTransitionType() const {
03281     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
03282   }
03283 
03284   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
03285   /// I.e., we have the following sequence:
03286   /// Def = Transition <ty1> a to <ty2>
03287   /// b = ToBePromoted <ty2> Def, ...
03288   /// =>
03289   /// b = ToBePromoted <ty1> a, ...
03290   /// Def = Transition <ty1> ToBePromoted to <ty2>
03291   void promoteImpl(Instruction *ToBePromoted);
03292 
03293   /// \brief Check whether or not it is profitable to promote all the
03294   /// instructions enqueued to be promoted.
03295   bool isProfitableToPromote() {
03296     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
03297     unsigned Index = isa<ConstantInt>(ValIdx)
03298                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
03299                          : -1;
03300     Type *PromotedType = getTransitionType();
03301 
03302     StoreInst *ST = cast<StoreInst>(CombineInst);
03303     unsigned AS = ST->getPointerAddressSpace();
03304     unsigned Align = ST->getAlignment();
03305     // Check if this store is supported.
03306     if (!TLI.allowsMisalignedMemoryAccesses(
03307             TLI.getValueType(ST->getValueOperand()->getType()), AS, Align)) {
03308       // If this is not supported, there is no way we can combine
03309       // the extract with the store.
03310       return false;
03311     }
03312 
03313     // The scalar chain of computation has to pay for the transition
03314     // scalar to vector.
03315     // The vector chain has to account for the combining cost.
03316     uint64_t ScalarCost =
03317         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
03318     uint64_t VectorCost = StoreExtractCombineCost;
03319     for (const auto &Inst : InstsToBePromoted) {
03320       // Compute the cost.
03321       // By construction, all instructions being promoted are arithmetic ones.
03322       // Moreover, one argument is a constant that can be viewed as a splat
03323       // constant.
03324       Value *Arg0 = Inst->getOperand(0);
03325       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
03326                             isa<ConstantFP>(Arg0);
03327       TargetTransformInfo::OperandValueKind Arg0OVK =
03328           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
03329                          : TargetTransformInfo::OK_AnyValue;
03330       TargetTransformInfo::OperandValueKind Arg1OVK =
03331           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
03332                           : TargetTransformInfo::OK_AnyValue;
03333       ScalarCost += TTI.getArithmeticInstrCost(
03334           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
03335       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
03336                                                Arg0OVK, Arg1OVK);
03337     }
03338     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
03339                  << ScalarCost << "\nVector: " << VectorCost << '\n');
03340     return ScalarCost > VectorCost;
03341   }
03342 
03343   /// \brief Generate a constant vector with \p Val with the same
03344   /// number of elements as the transition.
03345   /// \p UseSplat defines whether or not \p Val should be replicated
03346   /// accross the whole vector.
03347   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
03348   /// otherwise we generate a vector with as many undef as possible:
03349   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
03350   /// used at the index of the extract.
03351   Value *getConstantVector(Constant *Val, bool UseSplat) const {
03352     unsigned ExtractIdx = UINT_MAX;
03353     if (!UseSplat) {
03354       // If we cannot determine where the constant must be, we have to
03355       // use a splat constant.
03356       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
03357       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
03358         ExtractIdx = CstVal->getSExtValue();
03359       else
03360         UseSplat = true;
03361     }
03362 
03363     unsigned End = getTransitionType()->getVectorNumElements();
03364     if (UseSplat)
03365       return ConstantVector::getSplat(End, Val);
03366 
03367     SmallVector<Constant *, 4> ConstVec;
03368     UndefValue *UndefVal = UndefValue::get(Val->getType());
03369     for (unsigned Idx = 0; Idx != End; ++Idx) {
03370       if (Idx == ExtractIdx)
03371         ConstVec.push_back(Val);
03372       else
03373         ConstVec.push_back(UndefVal);
03374     }
03375     return ConstantVector::get(ConstVec);
03376   }
03377 
03378   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
03379   /// in \p Use can trigger undefined behavior.
03380   static bool canCauseUndefinedBehavior(const Instruction *Use,
03381                                         unsigned OperandIdx) {
03382     // This is not safe to introduce undef when the operand is on
03383     // the right hand side of a division-like instruction.
03384     if (OperandIdx != 1)
03385       return false;
03386     switch (Use->getOpcode()) {
03387     default:
03388       return false;
03389     case Instruction::SDiv:
03390     case Instruction::UDiv:
03391     case Instruction::SRem:
03392     case Instruction::URem:
03393       return true;
03394     case Instruction::FDiv:
03395     case Instruction::FRem:
03396       return !Use->hasNoNaNs();
03397     }
03398     llvm_unreachable(nullptr);
03399   }
03400 
03401 public:
03402   VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
03403                       Instruction *Transition, unsigned CombineCost)
03404       : TLI(TLI), TTI(TTI), Transition(Transition),
03405         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
03406     assert(Transition && "Do not know how to promote null");
03407   }
03408 
03409   /// \brief Check if we can promote \p ToBePromoted to \p Type.
03410   bool canPromote(const Instruction *ToBePromoted) const {
03411     // We could support CastInst too.
03412     return isa<BinaryOperator>(ToBePromoted);
03413   }
03414 
03415   /// \brief Check if it is profitable to promote \p ToBePromoted
03416   /// by moving downward the transition through.
03417   bool shouldPromote(const Instruction *ToBePromoted) const {
03418     // Promote only if all the operands can be statically expanded.
03419     // Indeed, we do not want to introduce any new kind of transitions.
03420     for (const Use &U : ToBePromoted->operands()) {
03421       const Value *Val = U.get();
03422       if (Val == getEndOfTransition()) {
03423         // If the use is a division and the transition is on the rhs,
03424         // we cannot promote the operation, otherwise we may create a
03425         // division by zero.
03426         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
03427           return false;
03428         continue;
03429       }
03430       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
03431           !isa<ConstantFP>(Val))
03432         return false;
03433     }
03434     // Check that the resulting operation is legal.
03435     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
03436     if (!ISDOpcode)
03437       return false;
03438     return StressStoreExtract ||
03439            TLI.isOperationLegalOrCustom(
03440                ISDOpcode, TLI.getValueType(getTransitionType(), true));
03441   }
03442 
03443   /// \brief Check whether or not \p Use can be combined
03444   /// with the transition.
03445   /// I.e., is it possible to do Use(Transition) => AnotherUse?
03446   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
03447 
03448   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
03449   void enqueueForPromotion(Instruction *ToBePromoted) {
03450     InstsToBePromoted.push_back(ToBePromoted);
03451   }
03452 
03453   /// \brief Set the instruction that will be combined with the transition.
03454   void recordCombineInstruction(Instruction *ToBeCombined) {
03455     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
03456     CombineInst = ToBeCombined;
03457   }
03458 
03459   /// \brief Promote all the instructions enqueued for promotion if it is
03460   /// is profitable.
03461   /// \return True if the promotion happened, false otherwise.
03462   bool promote() {
03463     // Check if there is something to promote.
03464     // Right now, if we do not have anything to combine with,
03465     // we assume the promotion is not profitable.
03466     if (InstsToBePromoted.empty() || !CombineInst)
03467       return false;
03468 
03469     // Check cost.
03470     if (!StressStoreExtract && !isProfitableToPromote())
03471       return false;
03472 
03473     // Promote.
03474     for (auto &ToBePromoted : InstsToBePromoted)
03475       promoteImpl(ToBePromoted);
03476     InstsToBePromoted.clear();
03477     return true;
03478   }
03479 };
03480 } // End of anonymous namespace.
03481 
03482 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
03483   // At this point, we know that all the operands of ToBePromoted but Def
03484   // can be statically promoted.
03485   // For Def, we need to use its parameter in ToBePromoted:
03486   // b = ToBePromoted ty1 a
03487   // Def = Transition ty1 b to ty2
03488   // Move the transition down.
03489   // 1. Replace all uses of the promoted operation by the transition.
03490   // = ... b => = ... Def.
03491   assert(ToBePromoted->getType() == Transition->getType() &&
03492          "The type of the result of the transition does not match "
03493          "the final type");
03494   ToBePromoted->replaceAllUsesWith(Transition);
03495   // 2. Update the type of the uses.
03496   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
03497   Type *TransitionTy = getTransitionType();
03498   ToBePromoted->mutateType(TransitionTy);
03499   // 3. Update all the operands of the promoted operation with promoted
03500   // operands.
03501   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
03502   for (Use &U : ToBePromoted->operands()) {
03503     Value *Val = U.get();
03504     Value *NewVal = nullptr;
03505     if (Val == Transition)
03506       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
03507     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
03508              isa<ConstantFP>(Val)) {
03509       // Use a splat constant if it is not safe to use undef.
03510       NewVal = getConstantVector(
03511           cast<Constant>(Val),
03512           isa<UndefValue>(Val) ||
03513               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
03514     } else
03515       assert(0 && "Did you modified shouldPromote and forgot to update this?");
03516     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
03517   }
03518   Transition->removeFromParent();
03519   Transition->insertAfter(ToBePromoted);
03520   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
03521 }
03522 
03523 /// Some targets can do store(extractelement) with one instruction.
03524 /// Try to push the extractelement towards the stores when the target
03525 /// has this feature and this is profitable.
03526 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
03527   unsigned CombineCost = UINT_MAX;
03528   if (DisableStoreExtract || !TLI ||
03529       (!StressStoreExtract &&
03530        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
03531                                        Inst->getOperand(1), CombineCost)))
03532     return false;
03533 
03534   // At this point we know that Inst is a vector to scalar transition.
03535   // Try to move it down the def-use chain, until:
03536   // - We can combine the transition with its single use
03537   //   => we got rid of the transition.
03538   // - We escape the current basic block
03539   //   => we would need to check that we are moving it at a cheaper place and
03540   //      we do not do that for now.
03541   BasicBlock *Parent = Inst->getParent();
03542   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
03543   VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
03544   // If the transition has more than one use, assume this is not going to be
03545   // beneficial.
03546   while (Inst->hasOneUse()) {
03547     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
03548     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
03549 
03550     if (ToBePromoted->getParent() != Parent) {
03551       DEBUG(dbgs() << "Instruction to promote is in a different block ("
03552                    << ToBePromoted->getParent()->getName()
03553                    << ") than the transition (" << Parent->getName() << ").\n");
03554       return false;
03555     }
03556 
03557     if (VPH.canCombine(ToBePromoted)) {
03558       DEBUG(dbgs() << "Assume " << *Inst << '\n'
03559                    << "will be combined with: " << *ToBePromoted << '\n');
03560       VPH.recordCombineInstruction(ToBePromoted);
03561       bool Changed = VPH.promote();
03562       NumStoreExtractExposed += Changed;
03563       return Changed;
03564     }
03565 
03566     DEBUG(dbgs() << "Try promoting.\n");
03567     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
03568       return false;
03569 
03570     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
03571 
03572     VPH.enqueueForPromotion(ToBePromoted);
03573     Inst = ToBePromoted;
03574   }
03575   return false;
03576 }
03577 
03578 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
03579   if (PHINode *P = dyn_cast<PHINode>(I)) {
03580     // It is possible for very late stage optimizations (such as SimplifyCFG)
03581     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
03582     // trivial PHI, go ahead and zap it here.
03583     if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
03584                                        TLInfo, DT)) {
03585       P->replaceAllUsesWith(V);
03586       P->eraseFromParent();
03587       ++NumPHIsElim;
03588       return true;
03589     }
03590     return false;
03591   }
03592 
03593   if (CastInst *CI = dyn_cast<CastInst>(I)) {
03594     // If the source of the cast is a constant, then this should have
03595     // already been constant folded.  The only reason NOT to constant fold
03596     // it is if something (e.g. LSR) was careful to place the constant
03597     // evaluation in a block other than then one that uses it (e.g. to hoist
03598     // the address of globals out of a loop).  If this is the case, we don't
03599     // want to forward-subst the cast.
03600     if (isa<Constant>(CI->getOperand(0)))
03601       return false;
03602 
03603     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
03604       return true;
03605 
03606     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
03607       /// Sink a zext or sext into its user blocks if the target type doesn't
03608       /// fit in one register
03609       if (TLI && TLI->getTypeAction(CI->getContext(),
03610                                     TLI->getValueType(CI->getType())) ==
03611                      TargetLowering::TypeExpandInteger) {
03612         return SinkCast(CI);
03613       } else {
03614         bool MadeChange = MoveExtToFormExtLoad(I);
03615         return MadeChange | OptimizeExtUses(I);
03616       }
03617     }
03618     return false;
03619   }
03620 
03621   if (CmpInst *CI = dyn_cast<CmpInst>(I))
03622     if (!TLI || !TLI->hasMultipleConditionRegisters())
03623       return OptimizeCmpExpression(CI);
03624 
03625   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
03626     if (TLI)
03627       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
03628     return false;
03629   }
03630 
03631   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
03632     if (TLI)
03633       return OptimizeMemoryInst(I, SI->getOperand(1),
03634                                 SI->getOperand(0)->getType());
03635     return false;
03636   }
03637 
03638   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
03639 
03640   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
03641                 BinOp->getOpcode() == Instruction::LShr)) {
03642     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
03643     if (TLI && CI && TLI->hasExtractBitsInsn())
03644       return OptimizeExtractBits(BinOp, CI, *TLI);
03645 
03646     return false;
03647   }
03648 
03649   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
03650     if (GEPI->hasAllZeroIndices()) {
03651       /// The GEP operand must be a pointer, so must its result -> BitCast
03652       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
03653                                         GEPI->getName(), GEPI);
03654       GEPI->replaceAllUsesWith(NC);
03655       GEPI->eraseFromParent();
03656       ++NumGEPsElim;
03657       OptimizeInst(NC);
03658       return true;
03659     }
03660     return false;
03661   }
03662 
03663   if (CallInst *CI = dyn_cast<CallInst>(I))
03664     return OptimizeCallInst(CI);
03665 
03666   if (SelectInst *SI = dyn_cast<SelectInst>(I))
03667     return OptimizeSelectInst(SI);
03668 
03669   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
03670     return OptimizeShuffleVectorInst(SVI);
03671 
03672   if (isa<ExtractElementInst>(I))
03673     return OptimizeExtractElementInst(I);
03674 
03675   return false;
03676 }
03677 
03678 // In this pass we look for GEP and cast instructions that are used
03679 // across basic blocks and rewrite them to improve basic-block-at-a-time
03680 // selection.
03681 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
03682   SunkAddrs.clear();
03683   bool MadeChange = false;
03684 
03685   CurInstIterator = BB.begin();
03686   while (CurInstIterator != BB.end())
03687     MadeChange |= OptimizeInst(CurInstIterator++);
03688 
03689   MadeChange |= DupRetToEnableTailCallOpts(&BB);
03690 
03691   return MadeChange;
03692 }
03693 
03694 // llvm.dbg.value is far away from the value then iSel may not be able
03695 // handle it properly. iSel will drop llvm.dbg.value if it can not
03696 // find a node corresponding to the value.
03697 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
03698   bool MadeChange = false;
03699   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
03700     Instruction *PrevNonDbgInst = nullptr;
03701     for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
03702       Instruction *Insn = BI; ++BI;
03703       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
03704       // Leave dbg.values that refer to an alloca alone. These
03705       // instrinsics describe the address of a variable (= the alloca)
03706       // being taken.  They should not be moved next to the alloca
03707       // (and to the beginning of the scope), but rather stay close to
03708       // where said address is used.
03709       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
03710         PrevNonDbgInst = Insn;
03711         continue;
03712       }
03713 
03714       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
03715       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
03716         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
03717         DVI->removeFromParent();
03718         if (isa<PHINode>(VI))
03719           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
03720         else
03721           DVI->insertAfter(VI);
03722         MadeChange = true;
03723         ++NumDbgValueMoved;
03724       }
03725     }
03726   }
03727   return MadeChange;
03728 }
03729 
03730 // If there is a sequence that branches based on comparing a single bit
03731 // against zero that can be combined into a single instruction, and the
03732 // target supports folding these into a single instruction, sink the
03733 // mask and compare into the branch uses. Do this before OptimizeBlock ->
03734 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
03735 // searched for.
03736 bool CodeGenPrepare::sinkAndCmp(Function &F) {
03737   if (!EnableAndCmpSinking)
03738     return false;
03739   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
03740     return false;
03741   bool MadeChange = false;
03742   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
03743     BasicBlock *BB = I++;
03744 
03745     // Does this BB end with the following?
03746     //   %andVal = and %val, #single-bit-set
03747     //   %icmpVal = icmp %andResult, 0
03748     //   br i1 %cmpVal label %dest1, label %dest2"
03749     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
03750     if (!Brcc || !Brcc->isConditional())
03751       continue;
03752     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
03753     if (!Cmp || Cmp->getParent() != BB)
03754       continue;
03755     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
03756     if (!Zero || !Zero->isZero())
03757       continue;
03758     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
03759     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
03760       continue;
03761     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
03762     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
03763       continue;
03764     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
03765 
03766     // Push the "and; icmp" for any users that are conditional branches.
03767     // Since there can only be one branch use per BB, we don't need to keep
03768     // track of which BBs we insert into.
03769     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
03770          UI != E; ) {
03771       Use &TheUse = *UI;
03772       // Find brcc use.
03773       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
03774       ++UI;
03775       if (!BrccUser || !BrccUser->isConditional())
03776         continue;
03777       BasicBlock *UserBB = BrccUser->getParent();
03778       if (UserBB == BB) continue;
03779       DEBUG(dbgs() << "found Brcc use\n");
03780 
03781       // Sink the "and; icmp" to use.
03782       MadeChange = true;
03783       BinaryOperator *NewAnd =
03784         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
03785                                   BrccUser);
03786       CmpInst *NewCmp =
03787         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
03788                         "", BrccUser);
03789       TheUse = NewCmp;
03790       ++NumAndCmpsMoved;
03791       DEBUG(BrccUser->getParent()->dump());
03792     }
03793   }
03794   return MadeChange;
03795 }