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