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