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