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