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