wrap OptSize and MinSize attributes for easier and consistent access (NFCI)
[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 typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
113 typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
114 class TypePromotionTransaction;
115
116   class CodeGenPrepare : public FunctionPass {
117     /// TLI - Keep a pointer of a TargetLowering to consult for determining
118     /// transformation profitability.
119     const TargetMachine *TM;
120     const TargetLowering *TLI;
121     const TargetTransformInfo *TTI;
122     const TargetLibraryInfo *TLInfo;
123
124     /// CurInstIterator - As we scan instructions optimizing them, this is the
125     /// next instruction to optimize.  Xforms that can invalidate this should
126     /// update it.
127     BasicBlock::iterator CurInstIterator;
128
129     /// Keeps track of non-local addresses that have been sunk into a block.
130     /// This allows us to avoid inserting duplicate code for blocks with
131     /// multiple load/stores of the same address.
132     ValueMap<Value*, Value*> SunkAddrs;
133
134     /// Keeps track of all instructions inserted for the current function.
135     SetOfInstrs InsertedInsts;
136     /// Keeps track of the type of the related instruction before their
137     /// promotion for the current function.
138     InstrToOrigTy PromotedInsts;
139
140     /// ModifiedDT - If CFG is modified in anyway.
141     bool ModifiedDT;
142
143     /// OptSize - True if optimizing for size.
144     bool OptSize;
145
146     /// DataLayout for the Function being processed.
147     const DataLayout *DL;
148
149   public:
150     static char ID; // Pass identification, replacement for typeid
151     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
152         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr), DL(nullptr) {
153         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
154       }
155     bool runOnFunction(Function &F) override;
156
157     const char *getPassName() const override { return "CodeGen Prepare"; }
158
159     void getAnalysisUsage(AnalysisUsage &AU) const override {
160       AU.addPreserved<DominatorTreeWrapperPass>();
161       AU.addRequired<TargetLibraryInfoWrapperPass>();
162       AU.addRequired<TargetTransformInfoWrapperPass>();
163     }
164
165   private:
166     bool EliminateFallThrough(Function &F);
167     bool EliminateMostlyEmptyBlocks(Function &F);
168     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
169     void EliminateMostlyEmptyBlock(BasicBlock *BB);
170     bool OptimizeBlock(BasicBlock &BB, bool& ModifiedDT);
171     bool OptimizeInst(Instruction *I, bool& ModifiedDT);
172     bool OptimizeMemoryInst(Instruction *I, Value *Addr,
173                             Type *AccessTy, unsigned AS);
174     bool OptimizeInlineAsmInst(CallInst *CS);
175     bool OptimizeCallInst(CallInst *CI, bool& ModifiedDT);
176     bool MoveExtToFormExtLoad(Instruction *&I);
177     bool OptimizeExtUses(Instruction *I);
178     bool OptimizeSelectInst(SelectInst *SI);
179     bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
180     bool OptimizeExtractElementInst(Instruction *Inst);
181     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
182     bool PlaceDbgValues(Function &F);
183     bool sinkAndCmp(Function &F);
184     bool ExtLdPromotion(TypePromotionTransaction &TPT, LoadInst *&LI,
185                         Instruction *&Inst,
186                         const SmallVectorImpl<Instruction *> &Exts,
187                         unsigned CreatedInstCost);
188     bool splitBranchCondition(Function &F);
189     bool simplifyOffsetableRelocate(Instruction &I);
190   };
191 }
192
193 char CodeGenPrepare::ID = 0;
194 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
195                    "Optimize for code generation", false, false)
196
197 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
198   return new CodeGenPrepare(TM);
199 }
200
201 bool CodeGenPrepare::runOnFunction(Function &F) {
202   if (skipOptnoneFunction(F))
203     return false;
204
205   DL = &F.getParent()->getDataLayout();
206
207   bool EverMadeChange = false;
208   // Clear per function information.
209   InsertedInsts.clear();
210   PromotedInsts.clear();
211
212   ModifiedDT = false;
213   if (TM)
214     TLI = TM->getSubtargetImpl(F)->getTargetLowering();
215   TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
216   TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
217   // FIXME: Use Function::optForSize().
218   OptSize = F.hasFnAttribute(Attribute::OptimizeForSize);
219
220   /// This optimization identifies DIV instructions that can be
221   /// profitably bypassed and carried out with a shorter, faster divide.
222   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
223     const DenseMap<unsigned int, unsigned int> &BypassWidths =
224        TLI->getBypassSlowDivWidths();
225     for (Function::iterator I = F.begin(); I != F.end(); I++)
226       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
227   }
228
229   // Eliminate blocks that contain only PHI nodes and an
230   // unconditional branch.
231   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
232
233   // llvm.dbg.value is far away from the value then iSel may not be able
234   // handle it properly. iSel will drop llvm.dbg.value if it can not
235   // find a node corresponding to the value.
236   EverMadeChange |= PlaceDbgValues(F);
237
238   // If there is a mask, compare against zero, and branch that can be combined
239   // into a single target instruction, push the mask and compare into branch
240   // users. Do this before OptimizeBlock -> OptimizeInst ->
241   // OptimizeCmpExpression, which perturbs the pattern being searched for.
242   if (!DisableBranchOpts) {
243     EverMadeChange |= sinkAndCmp(F);
244     EverMadeChange |= splitBranchCondition(F);
245   }
246
247   bool MadeChange = true;
248   while (MadeChange) {
249     MadeChange = false;
250     for (Function::iterator I = F.begin(); I != F.end(); ) {
251       BasicBlock *BB = I++;
252       bool ModifiedDTOnIteration = false;
253       MadeChange |= OptimizeBlock(*BB, ModifiedDTOnIteration);
254
255       // Restart BB iteration if the dominator tree of the Function was changed
256       if (ModifiedDTOnIteration)
257         break;
258     }
259     EverMadeChange |= MadeChange;
260   }
261
262   SunkAddrs.clear();
263
264   if (!DisableBranchOpts) {
265     MadeChange = false;
266     SmallPtrSet<BasicBlock*, 8> WorkList;
267     for (BasicBlock &BB : F) {
268       SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
269       MadeChange |= ConstantFoldTerminator(&BB, true);
270       if (!MadeChange) continue;
271
272       for (SmallVectorImpl<BasicBlock*>::iterator
273              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
274         if (pred_begin(*II) == pred_end(*II))
275           WorkList.insert(*II);
276     }
277
278     // Delete the dead blocks and any of their dead successors.
279     MadeChange |= !WorkList.empty();
280     while (!WorkList.empty()) {
281       BasicBlock *BB = *WorkList.begin();
282       WorkList.erase(BB);
283       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
284
285       DeleteDeadBlock(BB);
286
287       for (SmallVectorImpl<BasicBlock*>::iterator
288              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
289         if (pred_begin(*II) == pred_end(*II))
290           WorkList.insert(*II);
291     }
292
293     // Merge pairs of basic blocks with unconditional branches, connected by
294     // a single edge.
295     if (EverMadeChange || MadeChange)
296       MadeChange |= EliminateFallThrough(F);
297
298     EverMadeChange |= MadeChange;
299   }
300
301   if (!DisableGCOpts) {
302     SmallVector<Instruction *, 2> Statepoints;
303     for (BasicBlock &BB : F)
304       for (Instruction &I : BB)
305         if (isStatepoint(I))
306           Statepoints.push_back(&I);
307     for (auto &I : Statepoints)
308       EverMadeChange |= simplifyOffsetableRelocate(*I);
309   }
310
311   return EverMadeChange;
312 }
313
314 /// EliminateFallThrough - Merge basic blocks which are connected
315 /// by a single edge, where one of the basic blocks has a single successor
316 /// pointing to the other basic block, which has a single predecessor.
317 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
318   bool Changed = false;
319   // Scan all of the blocks in the function, except for the entry block.
320   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
321     BasicBlock *BB = I++;
322     // If the destination block has a single pred, then this is a trivial
323     // edge, just collapse it.
324     BasicBlock *SinglePred = BB->getSinglePredecessor();
325
326     // Don't merge if BB's address is taken.
327     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
328
329     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
330     if (Term && !Term->isConditional()) {
331       Changed = true;
332       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
333       // Remember if SinglePred was the entry block of the function.
334       // If so, we will need to move BB back to the entry position.
335       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
336       MergeBasicBlockIntoOnlyPred(BB, nullptr);
337
338       if (isEntry && BB != &BB->getParent()->getEntryBlock())
339         BB->moveBefore(&BB->getParent()->getEntryBlock());
340
341       // We have erased a block. Update the iterator.
342       I = BB;
343     }
344   }
345   return Changed;
346 }
347
348 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
349 /// debug info directives, and an unconditional branch.  Passes before isel
350 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
351 /// isel.  Start by eliminating these blocks so we can split them the way we
352 /// want them.
353 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
354   bool MadeChange = false;
355   // Note that this intentionally skips the entry block.
356   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
357     BasicBlock *BB = I++;
358
359     // If this block doesn't end with an uncond branch, ignore it.
360     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
361     if (!BI || !BI->isUnconditional())
362       continue;
363
364     // If the instruction before the branch (skipping debug info) isn't a phi
365     // node, then other stuff is happening here.
366     BasicBlock::iterator BBI = BI;
367     if (BBI != BB->begin()) {
368       --BBI;
369       while (isa<DbgInfoIntrinsic>(BBI)) {
370         if (BBI == BB->begin())
371           break;
372         --BBI;
373       }
374       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
375         continue;
376     }
377
378     // Do not break infinite loops.
379     BasicBlock *DestBB = BI->getSuccessor(0);
380     if (DestBB == BB)
381       continue;
382
383     if (!CanMergeBlocks(BB, DestBB))
384       continue;
385
386     EliminateMostlyEmptyBlock(BB);
387     MadeChange = true;
388   }
389   return MadeChange;
390 }
391
392 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
393 /// single uncond branch between them, and BB contains no other non-phi
394 /// instructions.
395 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
396                                     const BasicBlock *DestBB) const {
397   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
398   // the successor.  If there are more complex condition (e.g. preheaders),
399   // don't mess around with them.
400   BasicBlock::const_iterator BBI = BB->begin();
401   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
402     for (const User *U : PN->users()) {
403       const Instruction *UI = cast<Instruction>(U);
404       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
405         return false;
406       // If User is inside DestBB block and it is a PHINode then check
407       // incoming value. If incoming value is not from BB then this is
408       // a complex condition (e.g. preheaders) we want to avoid here.
409       if (UI->getParent() == DestBB) {
410         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
411           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
412             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
413             if (Insn && Insn->getParent() == BB &&
414                 Insn->getParent() != UPN->getIncomingBlock(I))
415               return false;
416           }
417       }
418     }
419   }
420
421   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
422   // and DestBB may have conflicting incoming values for the block.  If so, we
423   // can't merge the block.
424   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
425   if (!DestBBPN) return true;  // no conflict.
426
427   // Collect the preds of BB.
428   SmallPtrSet<const BasicBlock*, 16> BBPreds;
429   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
430     // It is faster to get preds from a PHI than with pred_iterator.
431     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
432       BBPreds.insert(BBPN->getIncomingBlock(i));
433   } else {
434     BBPreds.insert(pred_begin(BB), pred_end(BB));
435   }
436
437   // Walk the preds of DestBB.
438   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
439     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
440     if (BBPreds.count(Pred)) {   // Common predecessor?
441       BBI = DestBB->begin();
442       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
443         const Value *V1 = PN->getIncomingValueForBlock(Pred);
444         const Value *V2 = PN->getIncomingValueForBlock(BB);
445
446         // If V2 is a phi node in BB, look up what the mapped value will be.
447         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
448           if (V2PN->getParent() == BB)
449             V2 = V2PN->getIncomingValueForBlock(Pred);
450
451         // If there is a conflict, bail out.
452         if (V1 != V2) return false;
453       }
454     }
455   }
456
457   return true;
458 }
459
460
461 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
462 /// an unconditional branch in it.
463 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
464   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
465   BasicBlock *DestBB = BI->getSuccessor(0);
466
467   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
468
469   // If the destination block has a single pred, then this is a trivial edge,
470   // just collapse it.
471   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
472     if (SinglePred != DestBB) {
473       // Remember if SinglePred was the entry block of the function.  If so, we
474       // will need to move BB back to the entry position.
475       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
476       MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
477
478       if (isEntry && BB != &BB->getParent()->getEntryBlock())
479         BB->moveBefore(&BB->getParent()->getEntryBlock());
480
481       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
482       return;
483     }
484   }
485
486   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
487   // to handle the new incoming edges it is about to have.
488   PHINode *PN;
489   for (BasicBlock::iterator BBI = DestBB->begin();
490        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
491     // Remove the incoming value for BB, and remember it.
492     Value *InVal = PN->removeIncomingValue(BB, false);
493
494     // Two options: either the InVal is a phi node defined in BB or it is some
495     // value that dominates BB.
496     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
497     if (InValPhi && InValPhi->getParent() == BB) {
498       // Add all of the input values of the input PHI as inputs of this phi.
499       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
500         PN->addIncoming(InValPhi->getIncomingValue(i),
501                         InValPhi->getIncomingBlock(i));
502     } else {
503       // Otherwise, add one instance of the dominating value for each edge that
504       // we will be adding.
505       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
506         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
507           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
508       } else {
509         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
510           PN->addIncoming(InVal, *PI);
511       }
512     }
513   }
514
515   // The PHIs are now updated, change everything that refers to BB to use
516   // DestBB and remove BB.
517   BB->replaceAllUsesWith(DestBB);
518   BB->eraseFromParent();
519   ++NumBlocksElim;
520
521   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
522 }
523
524 // Computes a map of base pointer relocation instructions to corresponding
525 // derived pointer relocation instructions given a vector of all relocate calls
526 static void computeBaseDerivedRelocateMap(
527     const SmallVectorImpl<User *> &AllRelocateCalls,
528     DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> &
529         RelocateInstMap) {
530   // Collect information in two maps: one primarily for locating the base object
531   // while filling the second map; the second map is the final structure holding
532   // a mapping between Base and corresponding Derived relocate calls
533   DenseMap<std::pair<unsigned, unsigned>, IntrinsicInst *> RelocateIdxMap;
534   for (auto &U : AllRelocateCalls) {
535     GCRelocateOperands ThisRelocate(U);
536     IntrinsicInst *I = cast<IntrinsicInst>(U);
537     auto K = std::make_pair(ThisRelocate.getBasePtrIndex(),
538                             ThisRelocate.getDerivedPtrIndex());
539     RelocateIdxMap.insert(std::make_pair(K, I));
540   }
541   for (auto &Item : RelocateIdxMap) {
542     std::pair<unsigned, unsigned> Key = Item.first;
543     if (Key.first == Key.second)
544       // Base relocation: nothing to insert
545       continue;
546
547     IntrinsicInst *I = Item.second;
548     auto BaseKey = std::make_pair(Key.first, Key.first);
549
550     // We're iterating over RelocateIdxMap so we cannot modify it.
551     auto MaybeBase = RelocateIdxMap.find(BaseKey);
552     if (MaybeBase == RelocateIdxMap.end())
553       // TODO: We might want to insert a new base object relocate and gep off
554       // that, if there are enough derived object relocates.
555       continue;
556
557     RelocateInstMap[MaybeBase->second].push_back(I);
558   }
559 }
560
561 // Accepts a GEP and extracts the operands into a vector provided they're all
562 // small integer constants
563 static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
564                                           SmallVectorImpl<Value *> &OffsetV) {
565   for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
566     // Only accept small constant integer operands
567     auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
568     if (!Op || Op->getZExtValue() > 20)
569       return false;
570   }
571
572   for (unsigned i = 1; i < GEP->getNumOperands(); i++)
573     OffsetV.push_back(GEP->getOperand(i));
574   return true;
575 }
576
577 // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
578 // replace, computes a replacement, and affects it.
579 static bool
580 simplifyRelocatesOffABase(IntrinsicInst *RelocatedBase,
581                           const SmallVectorImpl<IntrinsicInst *> &Targets) {
582   bool MadeChange = false;
583   for (auto &ToReplace : Targets) {
584     GCRelocateOperands MasterRelocate(RelocatedBase);
585     GCRelocateOperands ThisRelocate(ToReplace);
586
587     assert(ThisRelocate.getBasePtrIndex() == MasterRelocate.getBasePtrIndex() &&
588            "Not relocating a derived object of the original base object");
589     if (ThisRelocate.getBasePtrIndex() == ThisRelocate.getDerivedPtrIndex()) {
590       // A duplicate relocate call. TODO: coalesce duplicates.
591       continue;
592     }
593
594     Value *Base = ThisRelocate.getBasePtr();
595     auto Derived = dyn_cast<GetElementPtrInst>(ThisRelocate.getDerivedPtr());
596     if (!Derived || Derived->getPointerOperand() != Base)
597       continue;
598
599     SmallVector<Value *, 2> OffsetV;
600     if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
601       continue;
602
603     // Create a Builder and replace the target callsite with a gep
604     assert(RelocatedBase->getNextNode() && "Should always have one since it's not a terminator");
605
606     // Insert after RelocatedBase
607     IRBuilder<> Builder(RelocatedBase->getNextNode());
608     Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
609
610     // If gc_relocate does not match the actual type, cast it to the right type.
611     // In theory, there must be a bitcast after gc_relocate if the type does not
612     // match, and we should reuse it to get the derived pointer. But it could be
613     // cases like this:
614     // bb1:
615     //  ...
616     //  %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
617     //  br label %merge
618     //
619     // bb2:
620     //  ...
621     //  %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
622     //  br label %merge
623     //
624     // merge:
625     //  %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
626     //  %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
627     //
628     // In this case, we can not find the bitcast any more. So we insert a new bitcast
629     // no matter there is already one or not. In this way, we can handle all cases, and
630     // the extra bitcast should be optimized away in later passes.
631     Instruction *ActualRelocatedBase = RelocatedBase;
632     if (RelocatedBase->getType() != Base->getType()) {
633       ActualRelocatedBase =
634           cast<Instruction>(Builder.CreateBitCast(RelocatedBase, Base->getType()));
635     }
636     Value *Replacement = Builder.CreateGEP(
637         Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
638     Instruction *ReplacementInst = cast<Instruction>(Replacement);
639     Replacement->takeName(ToReplace);
640     // If the newly generated derived pointer's type does not match the original derived
641     // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
642     Instruction *ActualReplacement = ReplacementInst;
643     if (ReplacementInst->getType() != ToReplace->getType()) {
644       ActualReplacement =
645           cast<Instruction>(Builder.CreateBitCast(ReplacementInst, ToReplace->getType()));
646     }
647     ToReplace->replaceAllUsesWith(ActualReplacement);
648     ToReplace->eraseFromParent();
649
650     MadeChange = true;
651   }
652   return MadeChange;
653 }
654
655 // Turns this:
656 //
657 // %base = ...
658 // %ptr = gep %base + 15
659 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
660 // %base' = relocate(%tok, i32 4, i32 4)
661 // %ptr' = relocate(%tok, i32 4, i32 5)
662 // %val = load %ptr'
663 //
664 // into this:
665 //
666 // %base = ...
667 // %ptr = gep %base + 15
668 // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
669 // %base' = gc.relocate(%tok, i32 4, i32 4)
670 // %ptr' = gep %base' + 15
671 // %val = load %ptr'
672 bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
673   bool MadeChange = false;
674   SmallVector<User *, 2> AllRelocateCalls;
675
676   for (auto *U : I.users())
677     if (isGCRelocate(dyn_cast<Instruction>(U)))
678       // Collect all the relocate calls associated with a statepoint
679       AllRelocateCalls.push_back(U);
680
681   // We need atleast one base pointer relocation + one derived pointer
682   // relocation to mangle
683   if (AllRelocateCalls.size() < 2)
684     return false;
685
686   // RelocateInstMap is a mapping from the base relocate instruction to the
687   // corresponding derived relocate instructions
688   DenseMap<IntrinsicInst *, SmallVector<IntrinsicInst *, 2>> RelocateInstMap;
689   computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
690   if (RelocateInstMap.empty())
691     return false;
692
693   for (auto &Item : RelocateInstMap)
694     // Item.first is the RelocatedBase to offset against
695     // Item.second is the vector of Targets to replace
696     MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
697   return MadeChange;
698 }
699
700 /// SinkCast - Sink the specified cast instruction into its user blocks
701 static bool SinkCast(CastInst *CI) {
702   BasicBlock *DefBB = CI->getParent();
703
704   /// InsertedCasts - Only insert a cast in each block once.
705   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
706
707   bool MadeChange = false;
708   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
709        UI != E; ) {
710     Use &TheUse = UI.getUse();
711     Instruction *User = cast<Instruction>(*UI);
712
713     // Figure out which BB this cast is used in.  For PHI's this is the
714     // appropriate predecessor block.
715     BasicBlock *UserBB = User->getParent();
716     if (PHINode *PN = dyn_cast<PHINode>(User)) {
717       UserBB = PN->getIncomingBlock(TheUse);
718     }
719
720     // Preincrement use iterator so we don't invalidate it.
721     ++UI;
722
723     // If this user is in the same block as the cast, don't change the cast.
724     if (UserBB == DefBB) continue;
725
726     // If we have already inserted a cast into this block, use it.
727     CastInst *&InsertedCast = InsertedCasts[UserBB];
728
729     if (!InsertedCast) {
730       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
731       InsertedCast =
732         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
733                          InsertPt);
734     }
735
736     // Replace a use of the cast with a use of the new cast.
737     TheUse = InsertedCast;
738     MadeChange = true;
739     ++NumCastUses;
740   }
741
742   // If we removed all uses, nuke the cast.
743   if (CI->use_empty()) {
744     CI->eraseFromParent();
745     MadeChange = true;
746   }
747
748   return MadeChange;
749 }
750
751 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
752 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
753 /// sink it into user blocks to reduce the number of virtual
754 /// registers that must be created and coalesced.
755 ///
756 /// Return true if any changes are made.
757 ///
758 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
759                                        const DataLayout &DL) {
760   // If this is a noop copy,
761   EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
762   EVT DstVT = TLI.getValueType(DL, CI->getType());
763
764   // This is an fp<->int conversion?
765   if (SrcVT.isInteger() != DstVT.isInteger())
766     return false;
767
768   // If this is an extension, it will be a zero or sign extension, which
769   // isn't a noop.
770   if (SrcVT.bitsLT(DstVT)) return false;
771
772   // If these values will be promoted, find out what they will be promoted
773   // to.  This helps us consider truncates on PPC as noop copies when they
774   // are.
775   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
776       TargetLowering::TypePromoteInteger)
777     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
778   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
779       TargetLowering::TypePromoteInteger)
780     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
781
782   // If, after promotion, these are the same types, this is a noop copy.
783   if (SrcVT != DstVT)
784     return false;
785
786   return SinkCast(CI);
787 }
788
789 /// CombineUAddWithOverflow - try to combine CI into a call to the
790 /// llvm.uadd.with.overflow intrinsic if possible.
791 ///
792 /// Return true if any changes were made.
793 static bool CombineUAddWithOverflow(CmpInst *CI) {
794   Value *A, *B;
795   Instruction *AddI;
796   if (!match(CI,
797              m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
798     return false;
799
800   Type *Ty = AddI->getType();
801   if (!isa<IntegerType>(Ty))
802     return false;
803
804   // We don't want to move around uses of condition values this late, so we we
805   // check if it is legal to create the call to the intrinsic in the basic
806   // block containing the icmp:
807
808   if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
809     return false;
810
811 #ifndef NDEBUG
812   // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
813   // for now:
814   if (AddI->hasOneUse())
815     assert(*AddI->user_begin() == CI && "expected!");
816 #endif
817
818   Module *M = CI->getParent()->getParent()->getParent();
819   Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
820
821   auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
822
823   auto *UAddWithOverflow =
824       CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
825   auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
826   auto *Overflow =
827       ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
828
829   CI->replaceAllUsesWith(Overflow);
830   AddI->replaceAllUsesWith(UAdd);
831   CI->eraseFromParent();
832   AddI->eraseFromParent();
833   return true;
834 }
835
836 /// SinkCmpExpression - Sink the given CmpInst into user blocks to reduce
837 /// the number of virtual registers that must be created and coalesced.  This is
838 /// a clear win except on targets with multiple condition code registers
839 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
840 ///
841 /// Return true if any changes are made.
842 static bool SinkCmpExpression(CmpInst *CI) {
843   BasicBlock *DefBB = CI->getParent();
844
845   /// InsertedCmp - Only insert a cmp in each block once.
846   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
847
848   bool MadeChange = false;
849   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
850        UI != E; ) {
851     Use &TheUse = UI.getUse();
852     Instruction *User = cast<Instruction>(*UI);
853
854     // Preincrement use iterator so we don't invalidate it.
855     ++UI;
856
857     // Don't bother for PHI nodes.
858     if (isa<PHINode>(User))
859       continue;
860
861     // Figure out which BB this cmp is used in.
862     BasicBlock *UserBB = User->getParent();
863
864     // If this user is in the same block as the cmp, don't change the cmp.
865     if (UserBB == DefBB) continue;
866
867     // If we have already inserted a cmp into this block, use it.
868     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
869
870     if (!InsertedCmp) {
871       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
872       InsertedCmp =
873         CmpInst::Create(CI->getOpcode(),
874                         CI->getPredicate(),  CI->getOperand(0),
875                         CI->getOperand(1), "", InsertPt);
876     }
877
878     // Replace a use of the cmp with a use of the new cmp.
879     TheUse = InsertedCmp;
880     MadeChange = true;
881     ++NumCmpUses;
882   }
883
884   // If we removed all uses, nuke the cmp.
885   if (CI->use_empty()) {
886     CI->eraseFromParent();
887     MadeChange = true;
888   }
889
890   return MadeChange;
891 }
892
893 static bool OptimizeCmpExpression(CmpInst *CI) {
894   if (SinkCmpExpression(CI))
895     return true;
896
897   if (CombineUAddWithOverflow(CI))
898     return true;
899
900   return false;
901 }
902
903 /// isExtractBitsCandidateUse - Check if the candidates could
904 /// be combined with shift instruction, which includes:
905 /// 1. Truncate instruction
906 /// 2. And instruction and the imm is a mask of the low bits:
907 /// imm & (imm+1) == 0
908 static bool isExtractBitsCandidateUse(Instruction *User) {
909   if (!isa<TruncInst>(User)) {
910     if (User->getOpcode() != Instruction::And ||
911         !isa<ConstantInt>(User->getOperand(1)))
912       return false;
913
914     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
915
916     if ((Cimm & (Cimm + 1)).getBoolValue())
917       return false;
918   }
919   return true;
920 }
921
922 /// SinkShiftAndTruncate - sink both shift and truncate instruction
923 /// to the use of truncate's BB.
924 static bool
925 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
926                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
927                      const TargetLowering &TLI, const DataLayout &DL) {
928   BasicBlock *UserBB = User->getParent();
929   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
930   TruncInst *TruncI = dyn_cast<TruncInst>(User);
931   bool MadeChange = false;
932
933   for (Value::user_iterator TruncUI = TruncI->user_begin(),
934                             TruncE = TruncI->user_end();
935        TruncUI != TruncE;) {
936
937     Use &TruncTheUse = TruncUI.getUse();
938     Instruction *TruncUser = cast<Instruction>(*TruncUI);
939     // Preincrement use iterator so we don't invalidate it.
940
941     ++TruncUI;
942
943     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
944     if (!ISDOpcode)
945       continue;
946
947     // If the use is actually a legal node, there will not be an
948     // implicit truncate.
949     // FIXME: always querying the result type is just an
950     // approximation; some nodes' legality is determined by the
951     // operand or other means. There's no good way to find out though.
952     if (TLI.isOperationLegalOrCustom(
953             ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
954       continue;
955
956     // Don't bother for PHI nodes.
957     if (isa<PHINode>(TruncUser))
958       continue;
959
960     BasicBlock *TruncUserBB = TruncUser->getParent();
961
962     if (UserBB == TruncUserBB)
963       continue;
964
965     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
966     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
967
968     if (!InsertedShift && !InsertedTrunc) {
969       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
970       // Sink the shift
971       if (ShiftI->getOpcode() == Instruction::AShr)
972         InsertedShift =
973             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
974       else
975         InsertedShift =
976             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
977
978       // Sink the trunc
979       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
980       TruncInsertPt++;
981
982       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
983                                        TruncI->getType(), "", TruncInsertPt);
984
985       MadeChange = true;
986
987       TruncTheUse = InsertedTrunc;
988     }
989   }
990   return MadeChange;
991 }
992
993 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
994 /// the uses could potentially be combined with this shift instruction and
995 /// generate BitExtract instruction. It will only be applied if the architecture
996 /// supports BitExtract instruction. Here is an example:
997 /// BB1:
998 ///   %x.extract.shift = lshr i64 %arg1, 32
999 /// BB2:
1000 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
1001 /// ==>
1002 ///
1003 /// BB2:
1004 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
1005 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
1006 ///
1007 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
1008 /// instruction.
1009 /// Return true if any changes are made.
1010 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
1011                                 const TargetLowering &TLI,
1012                                 const DataLayout &DL) {
1013   BasicBlock *DefBB = ShiftI->getParent();
1014
1015   /// Only insert instructions in each block once.
1016   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
1017
1018   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
1019
1020   bool MadeChange = false;
1021   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
1022        UI != E;) {
1023     Use &TheUse = UI.getUse();
1024     Instruction *User = cast<Instruction>(*UI);
1025     // Preincrement use iterator so we don't invalidate it.
1026     ++UI;
1027
1028     // Don't bother for PHI nodes.
1029     if (isa<PHINode>(User))
1030       continue;
1031
1032     if (!isExtractBitsCandidateUse(User))
1033       continue;
1034
1035     BasicBlock *UserBB = User->getParent();
1036
1037     if (UserBB == DefBB) {
1038       // If the shift and truncate instruction are in the same BB. The use of
1039       // the truncate(TruncUse) may still introduce another truncate if not
1040       // legal. In this case, we would like to sink both shift and truncate
1041       // instruction to the BB of TruncUse.
1042       // for example:
1043       // BB1:
1044       // i64 shift.result = lshr i64 opnd, imm
1045       // trunc.result = trunc shift.result to i16
1046       //
1047       // BB2:
1048       //   ----> We will have an implicit truncate here if the architecture does
1049       //   not have i16 compare.
1050       // cmp i16 trunc.result, opnd2
1051       //
1052       if (isa<TruncInst>(User) && shiftIsLegal
1053           // If the type of the truncate is legal, no trucate will be
1054           // introduced in other basic blocks.
1055           &&
1056           (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
1057         MadeChange =
1058             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
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(DL, 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(DL, 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,
2269                                        const DataLayout &DL, Value *Val) {
2270   Instruction *PromotedInst = dyn_cast<Instruction>(Val);
2271   if (!PromotedInst)
2272     return false;
2273   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2274   // If the ISDOpcode is undefined, it was undefined before the promotion.
2275   if (!ISDOpcode)
2276     return true;
2277   // Otherwise, check if the promoted instruction is legal or not.
2278   return TLI.isOperationLegalOrCustom(
2279       ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
2280 }
2281
2282 /// \brief Hepler class to perform type promotion.
2283 class TypePromotionHelper {
2284   /// \brief Utility function to check whether or not a sign or zero extension
2285   /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
2286   /// either using the operands of \p Inst or promoting \p Inst.
2287   /// The type of the extension is defined by \p IsSExt.
2288   /// In other words, check if:
2289   /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
2290   /// #1 Promotion applies:
2291   /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
2292   /// #2 Operand reuses:
2293   /// ext opnd1 to ConsideredExtType.
2294   /// \p PromotedInsts maps the instructions to their type before promotion.
2295   static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
2296                             const InstrToOrigTy &PromotedInsts, bool IsSExt);
2297
2298   /// \brief Utility function to determine if \p OpIdx should be promoted when
2299   /// promoting \p Inst.
2300   static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
2301     if (isa<SelectInst>(Inst) && OpIdx == 0)
2302       return false;
2303     return true;
2304   }
2305
2306   /// \brief Utility function to promote the operand of \p Ext when this
2307   /// operand is a promotable trunc or sext or zext.
2308   /// \p PromotedInsts maps the instructions to their type before promotion.
2309   /// \p CreatedInstsCost[out] contains the cost of all instructions
2310   /// created to promote the operand of Ext.
2311   /// Newly added extensions are inserted in \p Exts.
2312   /// Newly added truncates are inserted in \p Truncs.
2313   /// Should never be called directly.
2314   /// \return The promoted value which is used instead of Ext.
2315   static Value *promoteOperandForTruncAndAnyExt(
2316       Instruction *Ext, TypePromotionTransaction &TPT,
2317       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2318       SmallVectorImpl<Instruction *> *Exts,
2319       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
2320
2321   /// \brief Utility function to promote the operand of \p Ext when this
2322   /// operand is promotable and is not a supported trunc or sext.
2323   /// \p PromotedInsts maps the instructions to their type before promotion.
2324   /// \p CreatedInstsCost[out] contains the cost of all the instructions
2325   /// created to promote the operand of Ext.
2326   /// Newly added extensions are inserted in \p Exts.
2327   /// Newly added truncates are inserted in \p Truncs.
2328   /// Should never be called directly.
2329   /// \return The promoted value which is used instead of Ext.
2330   static Value *promoteOperandForOther(Instruction *Ext,
2331                                        TypePromotionTransaction &TPT,
2332                                        InstrToOrigTy &PromotedInsts,
2333                                        unsigned &CreatedInstsCost,
2334                                        SmallVectorImpl<Instruction *> *Exts,
2335                                        SmallVectorImpl<Instruction *> *Truncs,
2336                                        const TargetLowering &TLI, bool IsSExt);
2337
2338   /// \see promoteOperandForOther.
2339   static Value *signExtendOperandForOther(
2340       Instruction *Ext, TypePromotionTransaction &TPT,
2341       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2342       SmallVectorImpl<Instruction *> *Exts,
2343       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2344     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2345                                   Exts, Truncs, TLI, true);
2346   }
2347
2348   /// \see promoteOperandForOther.
2349   static Value *zeroExtendOperandForOther(
2350       Instruction *Ext, TypePromotionTransaction &TPT,
2351       InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2352       SmallVectorImpl<Instruction *> *Exts,
2353       SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2354     return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
2355                                   Exts, Truncs, TLI, false);
2356   }
2357
2358 public:
2359   /// Type for the utility function that promotes the operand of Ext.
2360   typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
2361                            InstrToOrigTy &PromotedInsts,
2362                            unsigned &CreatedInstsCost,
2363                            SmallVectorImpl<Instruction *> *Exts,
2364                            SmallVectorImpl<Instruction *> *Truncs,
2365                            const TargetLowering &TLI);
2366   /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
2367   /// action to promote the operand of \p Ext instead of using Ext.
2368   /// \return NULL if no promotable action is possible with the current
2369   /// sign extension.
2370   /// \p InsertedInsts keeps track of all the instructions inserted by the
2371   /// other CodeGenPrepare optimizations. This information is important
2372   /// because we do not want to promote these instructions as CodeGenPrepare
2373   /// will reinsert them later. Thus creating an infinite loop: create/remove.
2374   /// \p PromotedInsts maps the instructions to their type before promotion.
2375   static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
2376                           const TargetLowering &TLI,
2377                           const InstrToOrigTy &PromotedInsts);
2378 };
2379
2380 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
2381                                         Type *ConsideredExtType,
2382                                         const InstrToOrigTy &PromotedInsts,
2383                                         bool IsSExt) {
2384   // The promotion helper does not know how to deal with vector types yet.
2385   // To be able to fix that, we would need to fix the places where we
2386   // statically extend, e.g., constants and such.
2387   if (Inst->getType()->isVectorTy())
2388     return false;
2389
2390   // We can always get through zext.
2391   if (isa<ZExtInst>(Inst))
2392     return true;
2393
2394   // sext(sext) is ok too.
2395   if (IsSExt && isa<SExtInst>(Inst))
2396     return true;
2397
2398   // We can get through binary operator, if it is legal. In other words, the
2399   // binary operator must have a nuw or nsw flag.
2400   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
2401   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
2402       ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
2403        (IsSExt && BinOp->hasNoSignedWrap())))
2404     return true;
2405
2406   // Check if we can do the following simplification.
2407   // ext(trunc(opnd)) --> ext(opnd)
2408   if (!isa<TruncInst>(Inst))
2409     return false;
2410
2411   Value *OpndVal = Inst->getOperand(0);
2412   // Check if we can use this operand in the extension.
2413   // If the type is larger than the result type of the extension,
2414   // we cannot.
2415   if (!OpndVal->getType()->isIntegerTy() ||
2416       OpndVal->getType()->getIntegerBitWidth() >
2417           ConsideredExtType->getIntegerBitWidth())
2418     return false;
2419
2420   // If the operand of the truncate is not an instruction, we will not have
2421   // any information on the dropped bits.
2422   // (Actually we could for constant but it is not worth the extra logic).
2423   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
2424   if (!Opnd)
2425     return false;
2426
2427   // Check if the source of the type is narrow enough.
2428   // I.e., check that trunc just drops extended bits of the same kind of
2429   // the extension.
2430   // #1 get the type of the operand and check the kind of the extended bits.
2431   const Type *OpndType;
2432   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
2433   if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
2434     OpndType = It->second.getPointer();
2435   else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
2436     OpndType = Opnd->getOperand(0)->getType();
2437   else
2438     return false;
2439
2440   // #2 check that the truncate just drop extended bits.
2441   if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
2442     return true;
2443
2444   return false;
2445 }
2446
2447 TypePromotionHelper::Action TypePromotionHelper::getAction(
2448     Instruction *Ext, const SetOfInstrs &InsertedInsts,
2449     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
2450   assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
2451          "Unexpected instruction type");
2452   Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
2453   Type *ExtTy = Ext->getType();
2454   bool IsSExt = isa<SExtInst>(Ext);
2455   // If the operand of the extension is not an instruction, we cannot
2456   // get through.
2457   // If it, check we can get through.
2458   if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
2459     return nullptr;
2460
2461   // Do not promote if the operand has been added by codegenprepare.
2462   // Otherwise, it means we are undoing an optimization that is likely to be
2463   // redone, thus causing potential infinite loop.
2464   if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
2465     return nullptr;
2466
2467   // SExt or Trunc instructions.
2468   // Return the related handler.
2469   if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
2470       isa<ZExtInst>(ExtOpnd))
2471     return promoteOperandForTruncAndAnyExt;
2472
2473   // Regular instruction.
2474   // Abort early if we will have to insert non-free instructions.
2475   if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
2476     return nullptr;
2477   return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
2478 }
2479
2480 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
2481     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
2482     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2483     SmallVectorImpl<Instruction *> *Exts,
2484     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
2485   // By construction, the operand of SExt is an instruction. Otherwise we cannot
2486   // get through it and this method should not be called.
2487   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
2488   Value *ExtVal = SExt;
2489   bool HasMergedNonFreeExt = false;
2490   if (isa<ZExtInst>(SExtOpnd)) {
2491     // Replace s|zext(zext(opnd))
2492     // => zext(opnd).
2493     HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
2494     Value *ZExt =
2495         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
2496     TPT.replaceAllUsesWith(SExt, ZExt);
2497     TPT.eraseInstruction(SExt);
2498     ExtVal = ZExt;
2499   } else {
2500     // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
2501     // => z|sext(opnd).
2502     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
2503   }
2504   CreatedInstsCost = 0;
2505
2506   // Remove dead code.
2507   if (SExtOpnd->use_empty())
2508     TPT.eraseInstruction(SExtOpnd);
2509
2510   // Check if the extension is still needed.
2511   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
2512   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
2513     if (ExtInst) {
2514       if (Exts)
2515         Exts->push_back(ExtInst);
2516       CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
2517     }
2518     return ExtVal;
2519   }
2520
2521   // At this point we have: ext ty opnd to ty.
2522   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
2523   Value *NextVal = ExtInst->getOperand(0);
2524   TPT.eraseInstruction(ExtInst, NextVal);
2525   return NextVal;
2526 }
2527
2528 Value *TypePromotionHelper::promoteOperandForOther(
2529     Instruction *Ext, TypePromotionTransaction &TPT,
2530     InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
2531     SmallVectorImpl<Instruction *> *Exts,
2532     SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
2533     bool IsSExt) {
2534   // By construction, the operand of Ext is an instruction. Otherwise we cannot
2535   // get through it and this method should not be called.
2536   Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
2537   CreatedInstsCost = 0;
2538   if (!ExtOpnd->hasOneUse()) {
2539     // ExtOpnd will be promoted.
2540     // All its uses, but Ext, will need to use a truncated value of the
2541     // promoted version.
2542     // Create the truncate now.
2543     Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
2544     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
2545       ITrunc->removeFromParent();
2546       // Insert it just after the definition.
2547       ITrunc->insertAfter(ExtOpnd);
2548       if (Truncs)
2549         Truncs->push_back(ITrunc);
2550     }
2551
2552     TPT.replaceAllUsesWith(ExtOpnd, Trunc);
2553     // Restore the operand of Ext (which has been replace by the previous call
2554     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
2555     TPT.setOperand(Ext, 0, ExtOpnd);
2556   }
2557
2558   // Get through the Instruction:
2559   // 1. Update its type.
2560   // 2. Replace the uses of Ext by Inst.
2561   // 3. Extend each operand that needs to be extended.
2562
2563   // Remember the original type of the instruction before promotion.
2564   // This is useful to know that the high bits are sign extended bits.
2565   PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
2566       ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
2567   // Step #1.
2568   TPT.mutateType(ExtOpnd, Ext->getType());
2569   // Step #2.
2570   TPT.replaceAllUsesWith(Ext, ExtOpnd);
2571   // Step #3.
2572   Instruction *ExtForOpnd = Ext;
2573
2574   DEBUG(dbgs() << "Propagate Ext to operands\n");
2575   for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
2576        ++OpIdx) {
2577     DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
2578     if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
2579         !shouldExtOperand(ExtOpnd, OpIdx)) {
2580       DEBUG(dbgs() << "No need to propagate\n");
2581       continue;
2582     }
2583     // Check if we can statically extend the operand.
2584     Value *Opnd = ExtOpnd->getOperand(OpIdx);
2585     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
2586       DEBUG(dbgs() << "Statically extend\n");
2587       unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
2588       APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
2589                             : Cst->getValue().zext(BitWidth);
2590       TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
2591       continue;
2592     }
2593     // UndefValue are typed, so we have to statically sign extend them.
2594     if (isa<UndefValue>(Opnd)) {
2595       DEBUG(dbgs() << "Statically extend\n");
2596       TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
2597       continue;
2598     }
2599
2600     // Otherwise we have to explicity sign extend the operand.
2601     // Check if Ext was reused to extend an operand.
2602     if (!ExtForOpnd) {
2603       // If yes, create a new one.
2604       DEBUG(dbgs() << "More operands to ext\n");
2605       Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
2606         : TPT.createZExt(Ext, Opnd, Ext->getType());
2607       if (!isa<Instruction>(ValForExtOpnd)) {
2608         TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
2609         continue;
2610       }
2611       ExtForOpnd = cast<Instruction>(ValForExtOpnd);
2612     }
2613     if (Exts)
2614       Exts->push_back(ExtForOpnd);
2615     TPT.setOperand(ExtForOpnd, 0, Opnd);
2616
2617     // Move the sign extension before the insertion point.
2618     TPT.moveBefore(ExtForOpnd, ExtOpnd);
2619     TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
2620     CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
2621     // If more sext are required, new instructions will have to be created.
2622     ExtForOpnd = nullptr;
2623   }
2624   if (ExtForOpnd == Ext) {
2625     DEBUG(dbgs() << "Extension is useless now\n");
2626     TPT.eraseInstruction(Ext);
2627   }
2628   return ExtOpnd;
2629 }
2630
2631 /// IsPromotionProfitable - Check whether or not promoting an instruction
2632 /// to a wider type was profitable.
2633 /// \p NewCost gives the cost of extension instructions created by the
2634 /// promotion.
2635 /// \p OldCost gives the cost of extension instructions before the promotion
2636 /// plus the number of instructions that have been
2637 /// matched in the addressing mode the promotion.
2638 /// \p PromotedOperand is the value that has been promoted.
2639 /// \return True if the promotion is profitable, false otherwise.
2640 bool AddressingModeMatcher::IsPromotionProfitable(
2641     unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
2642   DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
2643   // The cost of the new extensions is greater than the cost of the
2644   // old extension plus what we folded.
2645   // This is not profitable.
2646   if (NewCost > OldCost)
2647     return false;
2648   if (NewCost < OldCost)
2649     return true;
2650   // The promotion is neutral but it may help folding the sign extension in
2651   // loads for instance.
2652   // Check that we did not create an illegal instruction.
2653   return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
2654 }
2655
2656 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
2657 /// fold the operation into the addressing mode.  If so, update the addressing
2658 /// mode and return true, otherwise return false without modifying AddrMode.
2659 /// If \p MovedAway is not NULL, it contains the information of whether or
2660 /// not AddrInst has to be folded into the addressing mode on success.
2661 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2662 /// because it has been moved away.
2663 /// Thus AddrInst must not be added in the matched instructions.
2664 /// This state can happen when AddrInst is a sext, since it may be moved away.
2665 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
2666 /// not be referenced anymore.
2667 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
2668                                                unsigned Depth,
2669                                                bool *MovedAway) {
2670   // Avoid exponential behavior on extremely deep expression trees.
2671   if (Depth >= 5) return false;
2672
2673   // By default, all matched instructions stay in place.
2674   if (MovedAway)
2675     *MovedAway = false;
2676
2677   switch (Opcode) {
2678   case Instruction::PtrToInt:
2679     // PtrToInt is always a noop, as we know that the int type is pointer sized.
2680     return MatchAddr(AddrInst->getOperand(0), Depth);
2681   case Instruction::IntToPtr: {
2682     auto AS = AddrInst->getType()->getPointerAddressSpace();
2683     auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
2684     // This inttoptr is a no-op if the integer type is pointer sized.
2685     if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
2686       return MatchAddr(AddrInst->getOperand(0), Depth);
2687     return false;
2688   }
2689   case Instruction::BitCast:
2690     // BitCast is always a noop, and we can handle it as long as it is
2691     // int->int or pointer->pointer (we don't want int<->fp or something).
2692     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2693          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2694         // Don't touch identity bitcasts.  These were probably put here by LSR,
2695         // and we don't want to mess around with them.  Assume it knows what it
2696         // is doing.
2697         AddrInst->getOperand(0)->getType() != AddrInst->getType())
2698       return MatchAddr(AddrInst->getOperand(0), Depth);
2699     return false;
2700   case Instruction::AddrSpaceCast: {
2701     unsigned SrcAS
2702       = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
2703     unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
2704     if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
2705       return MatchAddr(AddrInst->getOperand(0), Depth);
2706     return false;
2707   }
2708   case Instruction::Add: {
2709     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
2710     ExtAddrMode BackupAddrMode = AddrMode;
2711     unsigned OldSize = AddrModeInsts.size();
2712     // Start a transaction at this point.
2713     // The LHS may match but not the RHS.
2714     // Therefore, we need a higher level restoration point to undo partially
2715     // matched operation.
2716     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2717         TPT.getRestorationPoint();
2718
2719     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2720         MatchAddr(AddrInst->getOperand(0), Depth+1))
2721       return true;
2722
2723     // Restore the old addr mode info.
2724     AddrMode = BackupAddrMode;
2725     AddrModeInsts.resize(OldSize);
2726     TPT.rollback(LastKnownGood);
2727
2728     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
2729     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2730         MatchAddr(AddrInst->getOperand(1), Depth+1))
2731       return true;
2732
2733     // Otherwise we definitely can't merge the ADD in.
2734     AddrMode = BackupAddrMode;
2735     AddrModeInsts.resize(OldSize);
2736     TPT.rollback(LastKnownGood);
2737     break;
2738   }
2739   //case Instruction::Or:
2740   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2741   //break;
2742   case Instruction::Mul:
2743   case Instruction::Shl: {
2744     // Can only handle X*C and X << C.
2745     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2746     if (!RHS)
2747       return false;
2748     int64_t Scale = RHS->getSExtValue();
2749     if (Opcode == Instruction::Shl)
2750       Scale = 1LL << Scale;
2751
2752     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2753   }
2754   case Instruction::GetElementPtr: {
2755     // Scan the GEP.  We check it if it contains constant offsets and at most
2756     // one variable offset.
2757     int VariableOperand = -1;
2758     unsigned VariableScale = 0;
2759
2760     int64_t ConstantOffset = 0;
2761     gep_type_iterator GTI = gep_type_begin(AddrInst);
2762     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2763       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2764         const StructLayout *SL = DL.getStructLayout(STy);
2765         unsigned Idx =
2766           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2767         ConstantOffset += SL->getElementOffset(Idx);
2768       } else {
2769         uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
2770         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2771           ConstantOffset += CI->getSExtValue()*TypeSize;
2772         } else if (TypeSize) {  // Scales of zero don't do anything.
2773           // We only allow one variable index at the moment.
2774           if (VariableOperand != -1)
2775             return false;
2776
2777           // Remember the variable index.
2778           VariableOperand = i;
2779           VariableScale = TypeSize;
2780         }
2781       }
2782     }
2783
2784     // A common case is for the GEP to only do a constant offset.  In this case,
2785     // just add it to the disp field and check validity.
2786     if (VariableOperand == -1) {
2787       AddrMode.BaseOffs += ConstantOffset;
2788       if (ConstantOffset == 0 ||
2789           TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
2790         // Check to see if we can fold the base pointer in too.
2791         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2792           return true;
2793       }
2794       AddrMode.BaseOffs -= ConstantOffset;
2795       return false;
2796     }
2797
2798     // Save the valid addressing mode in case we can't match.
2799     ExtAddrMode BackupAddrMode = AddrMode;
2800     unsigned OldSize = AddrModeInsts.size();
2801
2802     // See if the scale and offset amount is valid for this target.
2803     AddrMode.BaseOffs += ConstantOffset;
2804
2805     // Match the base operand of the GEP.
2806     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2807       // If it couldn't be matched, just stuff the value in a register.
2808       if (AddrMode.HasBaseReg) {
2809         AddrMode = BackupAddrMode;
2810         AddrModeInsts.resize(OldSize);
2811         return false;
2812       }
2813       AddrMode.HasBaseReg = true;
2814       AddrMode.BaseReg = AddrInst->getOperand(0);
2815     }
2816
2817     // Match the remaining variable portion of the GEP.
2818     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2819                           Depth)) {
2820       // If it couldn't be matched, try stuffing the base into a register
2821       // instead of matching it, and retrying the match of the scale.
2822       AddrMode = BackupAddrMode;
2823       AddrModeInsts.resize(OldSize);
2824       if (AddrMode.HasBaseReg)
2825         return false;
2826       AddrMode.HasBaseReg = true;
2827       AddrMode.BaseReg = AddrInst->getOperand(0);
2828       AddrMode.BaseOffs += ConstantOffset;
2829       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2830                             VariableScale, Depth)) {
2831         // If even that didn't work, bail.
2832         AddrMode = BackupAddrMode;
2833         AddrModeInsts.resize(OldSize);
2834         return false;
2835       }
2836     }
2837
2838     return true;
2839   }
2840   case Instruction::SExt:
2841   case Instruction::ZExt: {
2842     Instruction *Ext = dyn_cast<Instruction>(AddrInst);
2843     if (!Ext)
2844       return false;
2845
2846     // Try to move this ext out of the way of the addressing mode.
2847     // Ask for a method for doing so.
2848     TypePromotionHelper::Action TPH =
2849         TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
2850     if (!TPH)
2851       return false;
2852
2853     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2854         TPT.getRestorationPoint();
2855     unsigned CreatedInstsCost = 0;
2856     unsigned ExtCost = !TLI.isExtFree(Ext);
2857     Value *PromotedOperand =
2858         TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
2859     // SExt has been moved away.
2860     // Thus either it will be rematched later in the recursive calls or it is
2861     // gone. Anyway, we must not fold it into the addressing mode at this point.
2862     // E.g.,
2863     // op = add opnd, 1
2864     // idx = ext op
2865     // addr = gep base, idx
2866     // is now:
2867     // promotedOpnd = ext opnd            <- no match here
2868     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
2869     // addr = gep base, op                <- match
2870     if (MovedAway)
2871       *MovedAway = true;
2872
2873     assert(PromotedOperand &&
2874            "TypePromotionHelper should have filtered out those cases");
2875
2876     ExtAddrMode BackupAddrMode = AddrMode;
2877     unsigned OldSize = AddrModeInsts.size();
2878
2879     if (!MatchAddr(PromotedOperand, Depth) ||
2880         // The total of the new cost is equals to the cost of the created
2881         // instructions.
2882         // The total of the old cost is equals to the cost of the extension plus
2883         // what we have saved in the addressing mode.
2884         !IsPromotionProfitable(CreatedInstsCost,
2885                                ExtCost + (AddrModeInsts.size() - OldSize),
2886                                PromotedOperand)) {
2887       AddrMode = BackupAddrMode;
2888       AddrModeInsts.resize(OldSize);
2889       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2890       TPT.rollback(LastKnownGood);
2891       return false;
2892     }
2893     return true;
2894   }
2895   }
2896   return false;
2897 }
2898
2899 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2900 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
2901 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
2902 /// or intptr_t for the target.
2903 ///
2904 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2905   // Start a transaction at this point that we will rollback if the matching
2906   // fails.
2907   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2908       TPT.getRestorationPoint();
2909   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2910     // Fold in immediates if legal for the target.
2911     AddrMode.BaseOffs += CI->getSExtValue();
2912     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
2913       return true;
2914     AddrMode.BaseOffs -= CI->getSExtValue();
2915   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2916     // If this is a global variable, try to fold it into the addressing mode.
2917     if (!AddrMode.BaseGV) {
2918       AddrMode.BaseGV = GV;
2919       if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
2920         return true;
2921       AddrMode.BaseGV = nullptr;
2922     }
2923   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2924     ExtAddrMode BackupAddrMode = AddrMode;
2925     unsigned OldSize = AddrModeInsts.size();
2926
2927     // Check to see if it is possible to fold this operation.
2928     bool MovedAway = false;
2929     if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2930       // This instruction may have been move away. If so, there is nothing
2931       // to check here.
2932       if (MovedAway)
2933         return true;
2934       // Okay, it's possible to fold this.  Check to see if it is actually
2935       // *profitable* to do so.  We use a simple cost model to avoid increasing
2936       // register pressure too much.
2937       if (I->hasOneUse() ||
2938           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2939         AddrModeInsts.push_back(I);
2940         return true;
2941       }
2942
2943       // It isn't profitable to do this, roll back.
2944       //cerr << "NOT FOLDING: " << *I;
2945       AddrMode = BackupAddrMode;
2946       AddrModeInsts.resize(OldSize);
2947       TPT.rollback(LastKnownGood);
2948     }
2949   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2950     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2951       return true;
2952     TPT.rollback(LastKnownGood);
2953   } else if (isa<ConstantPointerNull>(Addr)) {
2954     // Null pointer gets folded without affecting the addressing mode.
2955     return true;
2956   }
2957
2958   // Worse case, the target should support [reg] addressing modes. :)
2959   if (!AddrMode.HasBaseReg) {
2960     AddrMode.HasBaseReg = true;
2961     AddrMode.BaseReg = Addr;
2962     // Still check for legality in case the target supports [imm] but not [i+r].
2963     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
2964       return true;
2965     AddrMode.HasBaseReg = false;
2966     AddrMode.BaseReg = nullptr;
2967   }
2968
2969   // If the base register is already taken, see if we can do [r+r].
2970   if (AddrMode.Scale == 0) {
2971     AddrMode.Scale = 1;
2972     AddrMode.ScaledReg = Addr;
2973     if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
2974       return true;
2975     AddrMode.Scale = 0;
2976     AddrMode.ScaledReg = nullptr;
2977   }
2978   // Couldn't match.
2979   TPT.rollback(LastKnownGood);
2980   return false;
2981 }
2982
2983 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2984 /// inline asm call are due to memory operands.  If so, return true, otherwise
2985 /// return false.
2986 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2987                                     const TargetMachine &TM) {
2988   const Function *F = CI->getParent()->getParent();
2989   const TargetLowering *TLI = TM.getSubtargetImpl(*F)->getTargetLowering();
2990   const TargetRegisterInfo *TRI = TM.getSubtargetImpl(*F)->getRegisterInfo();
2991   TargetLowering::AsmOperandInfoVector TargetConstraints =
2992       TLI->ParseConstraints(F->getParent()->getDataLayout(), TRI,
2993                             ImmutableCallSite(CI));
2994   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2995     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2996
2997     // Compute the constraint code and ConstraintType to use.
2998     TLI->ComputeConstraintToUse(OpInfo, SDValue());
2999
3000     // If this asm operand is our Value*, and if it isn't an indirect memory
3001     // operand, we can't fold it!
3002     if (OpInfo.CallOperandVal == OpVal &&
3003         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
3004          !OpInfo.isIndirect))
3005       return false;
3006   }
3007
3008   return true;
3009 }
3010
3011 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
3012 /// memory use.  If we find an obviously non-foldable instruction, return true.
3013 /// Add the ultimately found memory instructions to MemoryUses.
3014 static bool FindAllMemoryUses(
3015     Instruction *I,
3016     SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
3017     SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetMachine &TM) {
3018   // If we already considered this instruction, we're done.
3019   if (!ConsideredInsts.insert(I).second)
3020     return false;
3021
3022   // If this is an obviously unfoldable instruction, bail out.
3023   if (!MightBeFoldableInst(I))
3024     return true;
3025
3026   // Loop over all the uses, recursively processing them.
3027   for (Use &U : I->uses()) {
3028     Instruction *UserI = cast<Instruction>(U.getUser());
3029
3030     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
3031       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
3032       continue;
3033     }
3034
3035     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
3036       unsigned opNo = U.getOperandNo();
3037       if (opNo == 0) return true; // Storing addr, not into addr.
3038       MemoryUses.push_back(std::make_pair(SI, opNo));
3039       continue;
3040     }
3041
3042     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
3043       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
3044       if (!IA) return true;
3045
3046       // If this is a memory operand, we're cool, otherwise bail out.
3047       if (!IsOperandAMemoryOperand(CI, IA, I, TM))
3048         return true;
3049       continue;
3050     }
3051
3052     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TM))
3053       return true;
3054   }
3055
3056   return false;
3057 }
3058
3059 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
3060 /// the use site that we're folding it into.  If so, there is no cost to
3061 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
3062 /// that we know are live at the instruction already.
3063 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
3064                                                    Value *KnownLive2) {
3065   // If Val is either of the known-live values, we know it is live!
3066   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
3067     return true;
3068
3069   // All values other than instructions and arguments (e.g. constants) are live.
3070   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
3071
3072   // If Val is a constant sized alloca in the entry block, it is live, this is
3073   // true because it is just a reference to the stack/frame pointer, which is
3074   // live for the whole function.
3075   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
3076     if (AI->isStaticAlloca())
3077       return true;
3078
3079   // Check to see if this value is already used in the memory instruction's
3080   // block.  If so, it's already live into the block at the very least, so we
3081   // can reasonably fold it.
3082   return Val->isUsedInBasicBlock(MemoryInst->getParent());
3083 }
3084
3085 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
3086 /// mode of the machine to fold the specified instruction into a load or store
3087 /// that ultimately uses it.  However, the specified instruction has multiple
3088 /// uses.  Given this, it may actually increase register pressure to fold it
3089 /// into the load.  For example, consider this code:
3090 ///
3091 ///     X = ...
3092 ///     Y = X+1
3093 ///     use(Y)   -> nonload/store
3094 ///     Z = Y+1
3095 ///     load Z
3096 ///
3097 /// In this case, Y has multiple uses, and can be folded into the load of Z
3098 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
3099 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
3100 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
3101 /// number of computations either.
3102 ///
3103 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
3104 /// X was live across 'load Z' for other reasons, we actually *would* want to
3105 /// fold the addressing mode in the Z case.  This would make Y die earlier.
3106 bool AddressingModeMatcher::
3107 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
3108                                      ExtAddrMode &AMAfter) {
3109   if (IgnoreProfitability) return true;
3110
3111   // AMBefore is the addressing mode before this instruction was folded into it,
3112   // and AMAfter is the addressing mode after the instruction was folded.  Get
3113   // the set of registers referenced by AMAfter and subtract out those
3114   // referenced by AMBefore: this is the set of values which folding in this
3115   // address extends the lifetime of.
3116   //
3117   // Note that there are only two potential values being referenced here,
3118   // BaseReg and ScaleReg (global addresses are always available, as are any
3119   // folded immediates).
3120   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
3121
3122   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
3123   // lifetime wasn't extended by adding this instruction.
3124   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
3125     BaseReg = nullptr;
3126   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
3127     ScaledReg = nullptr;
3128
3129   // If folding this instruction (and it's subexprs) didn't extend any live
3130   // ranges, we're ok with it.
3131   if (!BaseReg && !ScaledReg)
3132     return true;
3133
3134   // If all uses of this instruction are ultimately load/store/inlineasm's,
3135   // check to see if their addressing modes will include this instruction.  If
3136   // so, we can fold it into all uses, so it doesn't matter if it has multiple
3137   // uses.
3138   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
3139   SmallPtrSet<Instruction*, 16> ConsideredInsts;
3140   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TM))
3141     return false;  // Has a non-memory, non-foldable use!
3142
3143   // Now that we know that all uses of this instruction are part of a chain of
3144   // computation involving only operations that could theoretically be folded
3145   // into a memory use, loop over each of these uses and see if they could
3146   // *actually* fold the instruction.
3147   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
3148   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
3149     Instruction *User = MemoryUses[i].first;
3150     unsigned OpNo = MemoryUses[i].second;
3151
3152     // Get the access type of this use.  If the use isn't a pointer, we don't
3153     // know what it accesses.
3154     Value *Address = User->getOperand(OpNo);
3155     PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
3156     if (!AddrTy)
3157       return false;
3158     Type *AddressAccessTy = AddrTy->getElementType();
3159     unsigned AS = AddrTy->getAddressSpace();
3160
3161     // Do a match against the root of this address, ignoring profitability. This
3162     // will tell us if the addressing mode for the memory operation will
3163     // *actually* cover the shared instruction.
3164     ExtAddrMode Result;
3165     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3166         TPT.getRestorationPoint();
3167     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TM, AddressAccessTy, AS,
3168                                   MemoryInst, Result, InsertedInsts,
3169                                   PromotedInsts, TPT);
3170     Matcher.IgnoreProfitability = true;
3171     bool Success = Matcher.MatchAddr(Address, 0);
3172     (void)Success; assert(Success && "Couldn't select *anything*?");
3173
3174     // The match was to check the profitability, the changes made are not
3175     // part of the original matcher. Therefore, they should be dropped
3176     // otherwise the original matcher will not present the right state.
3177     TPT.rollback(LastKnownGood);
3178
3179     // If the match didn't cover I, then it won't be shared by it.
3180     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
3181                   I) == MatchedAddrModeInsts.end())
3182       return false;
3183
3184     MatchedAddrModeInsts.clear();
3185   }
3186
3187   return true;
3188 }
3189
3190 } // end anonymous namespace
3191
3192 /// IsNonLocalValue - Return true if the specified values are defined in a
3193 /// different basic block than BB.
3194 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
3195   if (Instruction *I = dyn_cast<Instruction>(V))
3196     return I->getParent() != BB;
3197   return false;
3198 }
3199
3200 /// OptimizeMemoryInst - Load and Store Instructions often have
3201 /// addressing modes that can do significant amounts of computation.  As such,
3202 /// instruction selection will try to get the load or store to do as much
3203 /// computation as possible for the program.  The problem is that isel can only
3204 /// see within a single block.  As such, we sink as much legal addressing mode
3205 /// stuff into the block as possible.
3206 ///
3207 /// This method is used to optimize both load/store and inline asms with memory
3208 /// operands.
3209 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
3210                                         Type *AccessTy, unsigned AddrSpace) {
3211   Value *Repl = Addr;
3212
3213   // Try to collapse single-value PHI nodes.  This is necessary to undo
3214   // unprofitable PRE transformations.
3215   SmallVector<Value*, 8> worklist;
3216   SmallPtrSet<Value*, 16> Visited;
3217   worklist.push_back(Addr);
3218
3219   // Use a worklist to iteratively look through PHI nodes, and ensure that
3220   // the addressing mode obtained from the non-PHI roots of the graph
3221   // are equivalent.
3222   Value *Consensus = nullptr;
3223   unsigned NumUsesConsensus = 0;
3224   bool IsNumUsesConsensusValid = false;
3225   SmallVector<Instruction*, 16> AddrModeInsts;
3226   ExtAddrMode AddrMode;
3227   TypePromotionTransaction TPT;
3228   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3229       TPT.getRestorationPoint();
3230   while (!worklist.empty()) {
3231     Value *V = worklist.back();
3232     worklist.pop_back();
3233
3234     // Break use-def graph loops.
3235     if (!Visited.insert(V).second) {
3236       Consensus = nullptr;
3237       break;
3238     }
3239
3240     // For a PHI node, push all of its incoming values.
3241     if (PHINode *P = dyn_cast<PHINode>(V)) {
3242       for (Value *IncValue : P->incoming_values())
3243         worklist.push_back(IncValue);
3244       continue;
3245     }
3246
3247     // For non-PHIs, determine the addressing mode being computed.
3248     SmallVector<Instruction*, 16> NewAddrModeInsts;
3249     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
3250       V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TM,
3251       InsertedInsts, PromotedInsts, TPT);
3252
3253     // This check is broken into two cases with very similar code to avoid using
3254     // getNumUses() as much as possible. Some values have a lot of uses, so
3255     // calling getNumUses() unconditionally caused a significant compile-time
3256     // regression.
3257     if (!Consensus) {
3258       Consensus = V;
3259       AddrMode = NewAddrMode;
3260       AddrModeInsts = NewAddrModeInsts;
3261       continue;
3262     } else if (NewAddrMode == AddrMode) {
3263       if (!IsNumUsesConsensusValid) {
3264         NumUsesConsensus = Consensus->getNumUses();
3265         IsNumUsesConsensusValid = true;
3266       }
3267
3268       // Ensure that the obtained addressing mode is equivalent to that obtained
3269       // for all other roots of the PHI traversal.  Also, when choosing one
3270       // such root as representative, select the one with the most uses in order
3271       // to keep the cost modeling heuristics in AddressingModeMatcher
3272       // applicable.
3273       unsigned NumUses = V->getNumUses();
3274       if (NumUses > NumUsesConsensus) {
3275         Consensus = V;
3276         NumUsesConsensus = NumUses;
3277         AddrModeInsts = NewAddrModeInsts;
3278       }
3279       continue;
3280     }
3281
3282     Consensus = nullptr;
3283     break;
3284   }
3285
3286   // If the addressing mode couldn't be determined, or if multiple different
3287   // ones were determined, bail out now.
3288   if (!Consensus) {
3289     TPT.rollback(LastKnownGood);
3290     return false;
3291   }
3292   TPT.commit();
3293
3294   // Check to see if any of the instructions supersumed by this addr mode are
3295   // non-local to I's BB.
3296   bool AnyNonLocal = false;
3297   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
3298     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
3299       AnyNonLocal = true;
3300       break;
3301     }
3302   }
3303
3304   // If all the instructions matched are already in this BB, don't do anything.
3305   if (!AnyNonLocal) {
3306     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
3307     return false;
3308   }
3309
3310   // Insert this computation right after this user.  Since our caller is
3311   // scanning from the top of the BB to the bottom, reuse of the expr are
3312   // guaranteed to happen later.
3313   IRBuilder<> Builder(MemoryInst);
3314
3315   // Now that we determined the addressing expression we want to use and know
3316   // that we have to sink it into this block.  Check to see if we have already
3317   // done this for some other load/store instr in this block.  If so, reuse the
3318   // computation.
3319   Value *&SunkAddr = SunkAddrs[Addr];
3320   if (SunkAddr) {
3321     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
3322                  << *MemoryInst << "\n");
3323     if (SunkAddr->getType() != Addr->getType())
3324       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3325   } else if (AddrSinkUsingGEPs ||
3326              (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
3327               TM->getSubtargetImpl(*MemoryInst->getParent()->getParent())
3328                   ->useAA())) {
3329     // By default, we use the GEP-based method when AA is used later. This
3330     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
3331     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
3332                  << *MemoryInst << "\n");
3333     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
3334     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
3335
3336     // First, find the pointer.
3337     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
3338       ResultPtr = AddrMode.BaseReg;
3339       AddrMode.BaseReg = nullptr;
3340     }
3341
3342     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
3343       // We can't add more than one pointer together, nor can we scale a
3344       // pointer (both of which seem meaningless).
3345       if (ResultPtr || AddrMode.Scale != 1)
3346         return false;
3347
3348       ResultPtr = AddrMode.ScaledReg;
3349       AddrMode.Scale = 0;
3350     }
3351
3352     if (AddrMode.BaseGV) {
3353       if (ResultPtr)
3354         return false;
3355
3356       ResultPtr = AddrMode.BaseGV;
3357     }
3358
3359     // If the real base value actually came from an inttoptr, then the matcher
3360     // will look through it and provide only the integer value. In that case,
3361     // use it here.
3362     if (!ResultPtr && AddrMode.BaseReg) {
3363       ResultPtr =
3364         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
3365       AddrMode.BaseReg = nullptr;
3366     } else if (!ResultPtr && AddrMode.Scale == 1) {
3367       ResultPtr =
3368         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
3369       AddrMode.Scale = 0;
3370     }
3371
3372     if (!ResultPtr &&
3373         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
3374       SunkAddr = Constant::getNullValue(Addr->getType());
3375     } else if (!ResultPtr) {
3376       return false;
3377     } else {
3378       Type *I8PtrTy =
3379           Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
3380       Type *I8Ty = Builder.getInt8Ty();
3381
3382       // Start with the base register. Do this first so that subsequent address
3383       // matching finds it last, which will prevent it from trying to match it
3384       // as the scaled value in case it happens to be a mul. That would be
3385       // problematic if we've sunk a different mul for the scale, because then
3386       // we'd end up sinking both muls.
3387       if (AddrMode.BaseReg) {
3388         Value *V = AddrMode.BaseReg;
3389         if (V->getType() != IntPtrTy)
3390           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3391
3392         ResultIndex = V;
3393       }
3394
3395       // Add the scale value.
3396       if (AddrMode.Scale) {
3397         Value *V = AddrMode.ScaledReg;
3398         if (V->getType() == IntPtrTy) {
3399           // done.
3400         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3401                    cast<IntegerType>(V->getType())->getBitWidth()) {
3402           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3403         } else {
3404           // It is only safe to sign extend the BaseReg if we know that the math
3405           // required to create it did not overflow before we extend it. Since
3406           // the original IR value was tossed in favor of a constant back when
3407           // the AddrMode was created we need to bail out gracefully if widths
3408           // do not match instead of extending it.
3409           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
3410           if (I && (ResultIndex != AddrMode.BaseReg))
3411             I->eraseFromParent();
3412           return false;
3413         }
3414
3415         if (AddrMode.Scale != 1)
3416           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3417                                 "sunkaddr");
3418         if (ResultIndex)
3419           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
3420         else
3421           ResultIndex = V;
3422       }
3423
3424       // Add in the Base Offset if present.
3425       if (AddrMode.BaseOffs) {
3426         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3427         if (ResultIndex) {
3428           // We need to add this separately from the scale above to help with
3429           // SDAG consecutive load/store merging.
3430           if (ResultPtr->getType() != I8PtrTy)
3431             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3432           ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
3433         }
3434
3435         ResultIndex = V;
3436       }
3437
3438       if (!ResultIndex) {
3439         SunkAddr = ResultPtr;
3440       } else {
3441         if (ResultPtr->getType() != I8PtrTy)
3442           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
3443         SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
3444       }
3445
3446       if (SunkAddr->getType() != Addr->getType())
3447         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
3448     }
3449   } else {
3450     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
3451                  << *MemoryInst << "\n");
3452     Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
3453     Value *Result = nullptr;
3454
3455     // Start with the base register. Do this first so that subsequent address
3456     // matching finds it last, which will prevent it from trying to match it
3457     // as the scaled value in case it happens to be a mul. That would be
3458     // problematic if we've sunk a different mul for the scale, because then
3459     // we'd end up sinking both muls.
3460     if (AddrMode.BaseReg) {
3461       Value *V = AddrMode.BaseReg;
3462       if (V->getType()->isPointerTy())
3463         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
3464       if (V->getType() != IntPtrTy)
3465         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
3466       Result = V;
3467     }
3468
3469     // Add the scale value.
3470     if (AddrMode.Scale) {
3471       Value *V = AddrMode.ScaledReg;
3472       if (V->getType() == IntPtrTy) {
3473         // done.
3474       } else if (V->getType()->isPointerTy()) {
3475         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
3476       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
3477                  cast<IntegerType>(V->getType())->getBitWidth()) {
3478         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
3479       } else {
3480         // It is only safe to sign extend the BaseReg if we know that the math
3481         // required to create it did not overflow before we extend it. Since
3482         // the original IR value was tossed in favor of a constant back when
3483         // the AddrMode was created we need to bail out gracefully if widths
3484         // do not match instead of extending it.
3485         Instruction *I = dyn_cast_or_null<Instruction>(Result);
3486         if (I && (Result != AddrMode.BaseReg))
3487           I->eraseFromParent();
3488         return false;
3489       }
3490       if (AddrMode.Scale != 1)
3491         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
3492                               "sunkaddr");
3493       if (Result)
3494         Result = Builder.CreateAdd(Result, V, "sunkaddr");
3495       else
3496         Result = V;
3497     }
3498
3499     // Add in the BaseGV if present.
3500     if (AddrMode.BaseGV) {
3501       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
3502       if (Result)
3503         Result = Builder.CreateAdd(Result, V, "sunkaddr");
3504       else
3505         Result = V;
3506     }
3507
3508     // Add in the Base Offset if present.
3509     if (AddrMode.BaseOffs) {
3510       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
3511       if (Result)
3512         Result = Builder.CreateAdd(Result, V, "sunkaddr");
3513       else
3514         Result = V;
3515     }
3516
3517     if (!Result)
3518       SunkAddr = Constant::getNullValue(Addr->getType());
3519     else
3520       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
3521   }
3522
3523   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
3524
3525   // If we have no uses, recursively delete the value and all dead instructions
3526   // using it.
3527   if (Repl->use_empty()) {
3528     // This can cause recursive deletion, which can invalidate our iterator.
3529     // Use a WeakVH to hold onto it in case this happens.
3530     WeakVH IterHandle(CurInstIterator);
3531     BasicBlock *BB = CurInstIterator->getParent();
3532
3533     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
3534
3535     if (IterHandle != CurInstIterator) {
3536       // If the iterator instruction was recursively deleted, start over at the
3537       // start of the block.
3538       CurInstIterator = BB->begin();
3539       SunkAddrs.clear();
3540     }
3541   }
3542   ++NumMemoryInsts;
3543   return true;
3544 }
3545
3546 /// OptimizeInlineAsmInst - If there are any memory operands, use
3547 /// OptimizeMemoryInst to sink their address computing into the block when
3548 /// possible / profitable.
3549 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
3550   bool MadeChange = false;
3551
3552   const TargetRegisterInfo *TRI =
3553       TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
3554   TargetLowering::AsmOperandInfoVector TargetConstraints =
3555       TLI->ParseConstraints(*DL, TRI, CS);
3556   unsigned ArgNo = 0;
3557   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
3558     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
3559
3560     // Compute the constraint code and ConstraintType to use.
3561     TLI->ComputeConstraintToUse(OpInfo, SDValue());
3562
3563     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
3564         OpInfo.isIndirect) {
3565       Value *OpVal = CS->getArgOperand(ArgNo++);
3566       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
3567     } else if (OpInfo.Type == InlineAsm::isInput)
3568       ArgNo++;
3569   }
3570
3571   return MadeChange;
3572 }
3573
3574 /// \brief Check if all the uses of \p Inst are equivalent (or free) zero or
3575 /// sign extensions.
3576 static bool hasSameExtUse(Instruction *Inst, const TargetLowering &TLI) {
3577   assert(!Inst->use_empty() && "Input must have at least one use");
3578   const Instruction *FirstUser = cast<Instruction>(*Inst->user_begin());
3579   bool IsSExt = isa<SExtInst>(FirstUser);
3580   Type *ExtTy = FirstUser->getType();
3581   for (const User *U : Inst->users()) {
3582     const Instruction *UI = cast<Instruction>(U);
3583     if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
3584       return false;
3585     Type *CurTy = UI->getType();
3586     // Same input and output types: Same instruction after CSE.
3587     if (CurTy == ExtTy)
3588       continue;
3589
3590     // If IsSExt is true, we are in this situation:
3591     // a = Inst
3592     // b = sext ty1 a to ty2
3593     // c = sext ty1 a to ty3
3594     // Assuming ty2 is shorter than ty3, this could be turned into:
3595     // a = Inst
3596     // b = sext ty1 a to ty2
3597     // c = sext ty2 b to ty3
3598     // However, the last sext is not free.
3599     if (IsSExt)
3600       return false;
3601
3602     // This is a ZExt, maybe this is free to extend from one type to another.
3603     // In that case, we would not account for a different use.
3604     Type *NarrowTy;
3605     Type *LargeTy;
3606     if (ExtTy->getScalarType()->getIntegerBitWidth() >
3607         CurTy->getScalarType()->getIntegerBitWidth()) {
3608       NarrowTy = CurTy;
3609       LargeTy = ExtTy;
3610     } else {
3611       NarrowTy = ExtTy;
3612       LargeTy = CurTy;
3613     }
3614
3615     if (!TLI.isZExtFree(NarrowTy, LargeTy))
3616       return false;
3617   }
3618   // All uses are the same or can be derived from one another for free.
3619   return true;
3620 }
3621
3622 /// \brief Try to form ExtLd by promoting \p Exts until they reach a
3623 /// load instruction.
3624 /// If an ext(load) can be formed, it is returned via \p LI for the load
3625 /// and \p Inst for the extension.
3626 /// Otherwise LI == nullptr and Inst == nullptr.
3627 /// When some promotion happened, \p TPT contains the proper state to
3628 /// revert them.
3629 ///
3630 /// \return true when promoting was necessary to expose the ext(load)
3631 /// opportunity, false otherwise.
3632 ///
3633 /// Example:
3634 /// \code
3635 /// %ld = load i32* %addr
3636 /// %add = add nuw i32 %ld, 4
3637 /// %zext = zext i32 %add to i64
3638 /// \endcode
3639 /// =>
3640 /// \code
3641 /// %ld = load i32* %addr
3642 /// %zext = zext i32 %ld to i64
3643 /// %add = add nuw i64 %zext, 4
3644 /// \encode
3645 /// Thanks to the promotion, we can match zext(load i32*) to i64.
3646 bool CodeGenPrepare::ExtLdPromotion(TypePromotionTransaction &TPT,
3647                                     LoadInst *&LI, Instruction *&Inst,
3648                                     const SmallVectorImpl<Instruction *> &Exts,
3649                                     unsigned CreatedInstsCost = 0) {
3650   // Iterate over all the extensions to see if one form an ext(load).
3651   for (auto I : Exts) {
3652     // Check if we directly have ext(load).
3653     if ((LI = dyn_cast<LoadInst>(I->getOperand(0)))) {
3654       Inst = I;
3655       // No promotion happened here.
3656       return false;
3657     }
3658     // Check whether or not we want to do any promotion.
3659     if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
3660       continue;
3661     // Get the action to perform the promotion.
3662     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
3663         I, InsertedInsts, *TLI, PromotedInsts);
3664     // Check if we can promote.
3665     if (!TPH)
3666       continue;
3667     // Save the current state.
3668     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3669         TPT.getRestorationPoint();
3670     SmallVector<Instruction *, 4> NewExts;
3671     unsigned NewCreatedInstsCost = 0;
3672     unsigned ExtCost = !TLI->isExtFree(I);
3673     // Promote.
3674     Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
3675                              &NewExts, nullptr, *TLI);
3676     assert(PromotedVal &&
3677            "TypePromotionHelper should have filtered out those cases");
3678
3679     // We would be able to merge only one extension in a load.
3680     // Therefore, if we have more than 1 new extension we heuristically
3681     // cut this search path, because it means we degrade the code quality.
3682     // With exactly 2, the transformation is neutral, because we will merge
3683     // one extension but leave one. However, we optimistically keep going,
3684     // because the new extension may be removed too.
3685     long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
3686     TotalCreatedInstsCost -= ExtCost;
3687     if (!StressExtLdPromotion &&
3688         (TotalCreatedInstsCost > 1 ||
3689          !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
3690       // The promotion is not profitable, rollback to the previous state.
3691       TPT.rollback(LastKnownGood);
3692       continue;
3693     }
3694     // The promotion is profitable.
3695     // Check if it exposes an ext(load).
3696     (void)ExtLdPromotion(TPT, LI, Inst, NewExts, TotalCreatedInstsCost);
3697     if (LI && (StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
3698                // If we have created a new extension, i.e., now we have two
3699                // extensions. We must make sure one of them is merged with
3700                // the load, otherwise we may degrade the code quality.
3701                (LI->hasOneUse() || hasSameExtUse(LI, *TLI))))
3702       // Promotion happened.
3703       return true;
3704     // If this does not help to expose an ext(load) then, rollback.
3705     TPT.rollback(LastKnownGood);
3706   }
3707   // None of the extension can form an ext(load).
3708   LI = nullptr;
3709   Inst = nullptr;
3710   return false;
3711 }
3712
3713 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
3714 /// basic block as the load, unless conditions are unfavorable. This allows
3715 /// SelectionDAG to fold the extend into the load.
3716 /// \p I[in/out] the extension may be modified during the process if some
3717 /// promotions apply.
3718 ///
3719 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *&I) {
3720   // Try to promote a chain of computation if it allows to form
3721   // an extended load.
3722   TypePromotionTransaction TPT;
3723   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
3724     TPT.getRestorationPoint();
3725   SmallVector<Instruction *, 1> Exts;
3726   Exts.push_back(I);
3727   // Look for a load being extended.
3728   LoadInst *LI = nullptr;
3729   Instruction *OldExt = I;
3730   bool HasPromoted = ExtLdPromotion(TPT, LI, I, Exts);
3731   if (!LI || !I) {
3732     assert(!HasPromoted && !LI && "If we did not match any load instruction "
3733                                   "the code must remain the same");
3734     I = OldExt;
3735     return false;
3736   }
3737
3738   // If they're already in the same block, there's nothing to do.
3739   // Make the cheap checks first if we did not promote.
3740   // If we promoted, we need to check if it is indeed profitable.
3741   if (!HasPromoted && LI->getParent() == I->getParent())
3742     return false;
3743
3744   EVT VT = TLI->getValueType(*DL, I->getType());
3745   EVT LoadVT = TLI->getValueType(*DL, LI->getType());
3746
3747   // If the load has other users and the truncate is not free, this probably
3748   // isn't worthwhile.
3749   if (!LI->hasOneUse() && TLI &&
3750       (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
3751       !TLI->isTruncateFree(I->getType(), LI->getType())) {
3752     I = OldExt;
3753     TPT.rollback(LastKnownGood);
3754     return false;
3755   }
3756
3757   // Check whether the target supports casts folded into loads.
3758   unsigned LType;
3759   if (isa<ZExtInst>(I))
3760     LType = ISD::ZEXTLOAD;
3761   else {
3762     assert(isa<SExtInst>(I) && "Unexpected ext type!");
3763     LType = ISD::SEXTLOAD;
3764   }
3765   if (TLI && !TLI->isLoadExtLegal(LType, VT, LoadVT)) {
3766     I = OldExt;
3767     TPT.rollback(LastKnownGood);
3768     return false;
3769   }
3770
3771   // Move the extend into the same block as the load, so that SelectionDAG
3772   // can fold it.
3773   TPT.commit();
3774   I->removeFromParent();
3775   I->insertAfter(LI);
3776   ++NumExtsMoved;
3777   return true;
3778 }
3779
3780 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
3781   BasicBlock *DefBB = I->getParent();
3782
3783   // If the result of a {s|z}ext and its source are both live out, rewrite all
3784   // other uses of the source with result of extension.
3785   Value *Src = I->getOperand(0);
3786   if (Src->hasOneUse())
3787     return false;
3788
3789   // Only do this xform if truncating is free.
3790   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
3791     return false;
3792
3793   // Only safe to perform the optimization if the source is also defined in
3794   // this block.
3795   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
3796     return false;
3797
3798   bool DefIsLiveOut = false;
3799   for (User *U : I->users()) {
3800     Instruction *UI = cast<Instruction>(U);
3801
3802     // Figure out which BB this ext is used in.
3803     BasicBlock *UserBB = UI->getParent();
3804     if (UserBB == DefBB) continue;
3805     DefIsLiveOut = true;
3806     break;
3807   }
3808   if (!DefIsLiveOut)
3809     return false;
3810
3811   // Make sure none of the uses are PHI nodes.
3812   for (User *U : Src->users()) {
3813     Instruction *UI = cast<Instruction>(U);
3814     BasicBlock *UserBB = UI->getParent();
3815     if (UserBB == DefBB) continue;
3816     // Be conservative. We don't want this xform to end up introducing
3817     // reloads just before load / store instructions.
3818     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
3819       return false;
3820   }
3821
3822   // InsertedTruncs - Only insert one trunc in each block once.
3823   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3824
3825   bool MadeChange = false;
3826   for (Use &U : Src->uses()) {
3827     Instruction *User = cast<Instruction>(U.getUser());
3828
3829     // Figure out which BB this ext is used in.
3830     BasicBlock *UserBB = User->getParent();
3831     if (UserBB == DefBB) continue;
3832
3833     // Both src and def are live in this block. Rewrite the use.
3834     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3835
3836     if (!InsertedTrunc) {
3837       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3838       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
3839       InsertedInsts.insert(InsertedTrunc);
3840     }
3841
3842     // Replace a use of the {s|z}ext source with a use of the result.
3843     U = InsertedTrunc;
3844     ++NumExtUses;
3845     MadeChange = true;
3846   }
3847
3848   return MadeChange;
3849 }
3850
3851 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3852 /// turned into an explicit branch.
3853 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3854   // FIXME: This should use the same heuristics as IfConversion to determine
3855   // whether a select is better represented as a branch.  This requires that
3856   // branch probability metadata is preserved for the select, which is not the
3857   // case currently.
3858
3859   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3860
3861   // If the branch is predicted right, an out of order CPU can avoid blocking on
3862   // the compare.  Emit cmovs on compares with a memory operand as branches to
3863   // avoid stalls on the load from memory.  If the compare has more than one use
3864   // there's probably another cmov or setcc around so it's not worth emitting a
3865   // branch.
3866   if (!Cmp)
3867     return false;
3868
3869   Value *CmpOp0 = Cmp->getOperand(0);
3870   Value *CmpOp1 = Cmp->getOperand(1);
3871
3872   // We check that the memory operand has one use to avoid uses of the loaded
3873   // value directly after the compare, making branches unprofitable.
3874   return Cmp->hasOneUse() &&
3875          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3876           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3877 }
3878
3879
3880 /// If we have a SelectInst that will likely profit from branch prediction,
3881 /// turn it into a branch.
3882 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
3883   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3884
3885   // Can we convert the 'select' to CF ?
3886   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
3887     return false;
3888
3889   TargetLowering::SelectSupportKind SelectKind;
3890   if (VectorCond)
3891     SelectKind = TargetLowering::VectorMaskSelect;
3892   else if (SI->getType()->isVectorTy())
3893     SelectKind = TargetLowering::ScalarCondVectorVal;
3894   else
3895     SelectKind = TargetLowering::ScalarValSelect;
3896
3897   // Do we have efficient codegen support for this kind of 'selects' ?
3898   if (TLI->isSelectSupported(SelectKind)) {
3899     // We have efficient codegen support for the select instruction.
3900     // Check if it is profitable to keep this 'select'.
3901     if (!TLI->isPredictableSelectExpensive() ||
3902         !isFormingBranchFromSelectProfitable(SI))
3903       return false;
3904   }
3905
3906   ModifiedDT = true;
3907
3908   // First, we split the block containing the select into 2 blocks.
3909   BasicBlock *StartBlock = SI->getParent();
3910   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3911   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3912
3913   // Create a new block serving as the landing pad for the branch.
3914   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3915                                              NextBlock->getParent(), NextBlock);
3916
3917   // Move the unconditional branch from the block with the select in it into our
3918   // landing pad block.
3919   StartBlock->getTerminator()->eraseFromParent();
3920   BranchInst::Create(NextBlock, SmallBlock);
3921
3922   // Insert the real conditional branch based on the original condition.
3923   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3924
3925   // The select itself is replaced with a PHI Node.
3926   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3927   PN->takeName(SI);
3928   PN->addIncoming(SI->getTrueValue(), StartBlock);
3929   PN->addIncoming(SI->getFalseValue(), SmallBlock);
3930   SI->replaceAllUsesWith(PN);
3931   SI->eraseFromParent();
3932
3933   // Instruct OptimizeBlock to skip to the next block.
3934   CurInstIterator = StartBlock->end();
3935   ++NumSelectsExpanded;
3936   return true;
3937 }
3938
3939 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3940   SmallVector<int, 16> Mask(SVI->getShuffleMask());
3941   int SplatElem = -1;
3942   for (unsigned i = 0; i < Mask.size(); ++i) {
3943     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3944       return false;
3945     SplatElem = Mask[i];
3946   }
3947
3948   return true;
3949 }
3950
3951 /// Some targets have expensive vector shifts if the lanes aren't all the same
3952 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3953 /// it's often worth sinking a shufflevector splat down to its use so that
3954 /// codegen can spot all lanes are identical.
3955 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3956   BasicBlock *DefBB = SVI->getParent();
3957
3958   // Only do this xform if variable vector shifts are particularly expensive.
3959   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3960     return false;
3961
3962   // We only expect better codegen by sinking a shuffle if we can recognise a
3963   // constant splat.
3964   if (!isBroadcastShuffle(SVI))
3965     return false;
3966
3967   // InsertedShuffles - Only insert a shuffle in each block once.
3968   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3969
3970   bool MadeChange = false;
3971   for (User *U : SVI->users()) {
3972     Instruction *UI = cast<Instruction>(U);
3973
3974     // Figure out which BB this ext is used in.
3975     BasicBlock *UserBB = UI->getParent();
3976     if (UserBB == DefBB) continue;
3977
3978     // For now only apply this when the splat is used by a shift instruction.
3979     if (!UI->isShift()) continue;
3980
3981     // Everything checks out, sink the shuffle if the user's block doesn't
3982     // already have a copy.
3983     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3984
3985     if (!InsertedShuffle) {
3986       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3987       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3988                                               SVI->getOperand(1),
3989                                               SVI->getOperand(2), "", InsertPt);
3990     }
3991
3992     UI->replaceUsesOfWith(SVI, InsertedShuffle);
3993     MadeChange = true;
3994   }
3995
3996   // If we removed all uses, nuke the shuffle.
3997   if (SVI->use_empty()) {
3998     SVI->eraseFromParent();
3999     MadeChange = true;
4000   }
4001
4002   return MadeChange;
4003 }
4004
4005 namespace {
4006 /// \brief Helper class to promote a scalar operation to a vector one.
4007 /// This class is used to move downward extractelement transition.
4008 /// E.g.,
4009 /// a = vector_op <2 x i32>
4010 /// b = extractelement <2 x i32> a, i32 0
4011 /// c = scalar_op b
4012 /// store c
4013 ///
4014 /// =>
4015 /// a = vector_op <2 x i32>
4016 /// c = vector_op a (equivalent to scalar_op on the related lane)
4017 /// * d = extractelement <2 x i32> c, i32 0
4018 /// * store d
4019 /// Assuming both extractelement and store can be combine, we get rid of the
4020 /// transition.
4021 class VectorPromoteHelper {
4022   /// DataLayout associated with the current module.
4023   const DataLayout &DL;
4024
4025   /// Used to perform some checks on the legality of vector operations.
4026   const TargetLowering &TLI;
4027
4028   /// Used to estimated the cost of the promoted chain.
4029   const TargetTransformInfo &TTI;
4030
4031   /// The transition being moved downwards.
4032   Instruction *Transition;
4033   /// The sequence of instructions to be promoted.
4034   SmallVector<Instruction *, 4> InstsToBePromoted;
4035   /// Cost of combining a store and an extract.
4036   unsigned StoreExtractCombineCost;
4037   /// Instruction that will be combined with the transition.
4038   Instruction *CombineInst;
4039
4040   /// \brief The instruction that represents the current end of the transition.
4041   /// Since we are faking the promotion until we reach the end of the chain
4042   /// of computation, we need a way to get the current end of the transition.
4043   Instruction *getEndOfTransition() const {
4044     if (InstsToBePromoted.empty())
4045       return Transition;
4046     return InstsToBePromoted.back();
4047   }
4048
4049   /// \brief Return the index of the original value in the transition.
4050   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
4051   /// c, is at index 0.
4052   unsigned getTransitionOriginalValueIdx() const {
4053     assert(isa<ExtractElementInst>(Transition) &&
4054            "Other kind of transitions are not supported yet");
4055     return 0;
4056   }
4057
4058   /// \brief Return the index of the index in the transition.
4059   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
4060   /// is at index 1.
4061   unsigned getTransitionIdx() const {
4062     assert(isa<ExtractElementInst>(Transition) &&
4063            "Other kind of transitions are not supported yet");
4064     return 1;
4065   }
4066
4067   /// \brief Get the type of the transition.
4068   /// This is the type of the original value.
4069   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
4070   /// transition is <2 x i32>.
4071   Type *getTransitionType() const {
4072     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
4073   }
4074
4075   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
4076   /// I.e., we have the following sequence:
4077   /// Def = Transition <ty1> a to <ty2>
4078   /// b = ToBePromoted <ty2> Def, ...
4079   /// =>
4080   /// b = ToBePromoted <ty1> a, ...
4081   /// Def = Transition <ty1> ToBePromoted to <ty2>
4082   void promoteImpl(Instruction *ToBePromoted);
4083
4084   /// \brief Check whether or not it is profitable to promote all the
4085   /// instructions enqueued to be promoted.
4086   bool isProfitableToPromote() {
4087     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
4088     unsigned Index = isa<ConstantInt>(ValIdx)
4089                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
4090                          : -1;
4091     Type *PromotedType = getTransitionType();
4092
4093     StoreInst *ST = cast<StoreInst>(CombineInst);
4094     unsigned AS = ST->getPointerAddressSpace();
4095     unsigned Align = ST->getAlignment();
4096     // Check if this store is supported.
4097     if (!TLI.allowsMisalignedMemoryAccesses(
4098             TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
4099             Align)) {
4100       // If this is not supported, there is no way we can combine
4101       // the extract with the store.
4102       return false;
4103     }
4104
4105     // The scalar chain of computation has to pay for the transition
4106     // scalar to vector.
4107     // The vector chain has to account for the combining cost.
4108     uint64_t ScalarCost =
4109         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
4110     uint64_t VectorCost = StoreExtractCombineCost;
4111     for (const auto &Inst : InstsToBePromoted) {
4112       // Compute the cost.
4113       // By construction, all instructions being promoted are arithmetic ones.
4114       // Moreover, one argument is a constant that can be viewed as a splat
4115       // constant.
4116       Value *Arg0 = Inst->getOperand(0);
4117       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
4118                             isa<ConstantFP>(Arg0);
4119       TargetTransformInfo::OperandValueKind Arg0OVK =
4120           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4121                          : TargetTransformInfo::OK_AnyValue;
4122       TargetTransformInfo::OperandValueKind Arg1OVK =
4123           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
4124                           : TargetTransformInfo::OK_AnyValue;
4125       ScalarCost += TTI.getArithmeticInstrCost(
4126           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
4127       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
4128                                                Arg0OVK, Arg1OVK);
4129     }
4130     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
4131                  << ScalarCost << "\nVector: " << VectorCost << '\n');
4132     return ScalarCost > VectorCost;
4133   }
4134
4135   /// \brief Generate a constant vector with \p Val with the same
4136   /// number of elements as the transition.
4137   /// \p UseSplat defines whether or not \p Val should be replicated
4138   /// accross the whole vector.
4139   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
4140   /// otherwise we generate a vector with as many undef as possible:
4141   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
4142   /// used at the index of the extract.
4143   Value *getConstantVector(Constant *Val, bool UseSplat) const {
4144     unsigned ExtractIdx = UINT_MAX;
4145     if (!UseSplat) {
4146       // If we cannot determine where the constant must be, we have to
4147       // use a splat constant.
4148       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
4149       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
4150         ExtractIdx = CstVal->getSExtValue();
4151       else
4152         UseSplat = true;
4153     }
4154
4155     unsigned End = getTransitionType()->getVectorNumElements();
4156     if (UseSplat)
4157       return ConstantVector::getSplat(End, Val);
4158
4159     SmallVector<Constant *, 4> ConstVec;
4160     UndefValue *UndefVal = UndefValue::get(Val->getType());
4161     for (unsigned Idx = 0; Idx != End; ++Idx) {
4162       if (Idx == ExtractIdx)
4163         ConstVec.push_back(Val);
4164       else
4165         ConstVec.push_back(UndefVal);
4166     }
4167     return ConstantVector::get(ConstVec);
4168   }
4169
4170   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
4171   /// in \p Use can trigger undefined behavior.
4172   static bool canCauseUndefinedBehavior(const Instruction *Use,
4173                                         unsigned OperandIdx) {
4174     // This is not safe to introduce undef when the operand is on
4175     // the right hand side of a division-like instruction.
4176     if (OperandIdx != 1)
4177       return false;
4178     switch (Use->getOpcode()) {
4179     default:
4180       return false;
4181     case Instruction::SDiv:
4182     case Instruction::UDiv:
4183     case Instruction::SRem:
4184     case Instruction::URem:
4185       return true;
4186     case Instruction::FDiv:
4187     case Instruction::FRem:
4188       return !Use->hasNoNaNs();
4189     }
4190     llvm_unreachable(nullptr);
4191   }
4192
4193 public:
4194   VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
4195                       const TargetTransformInfo &TTI, Instruction *Transition,
4196                       unsigned CombineCost)
4197       : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
4198         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
4199     assert(Transition && "Do not know how to promote null");
4200   }
4201
4202   /// \brief Check if we can promote \p ToBePromoted to \p Type.
4203   bool canPromote(const Instruction *ToBePromoted) const {
4204     // We could support CastInst too.
4205     return isa<BinaryOperator>(ToBePromoted);
4206   }
4207
4208   /// \brief Check if it is profitable to promote \p ToBePromoted
4209   /// by moving downward the transition through.
4210   bool shouldPromote(const Instruction *ToBePromoted) const {
4211     // Promote only if all the operands can be statically expanded.
4212     // Indeed, we do not want to introduce any new kind of transitions.
4213     for (const Use &U : ToBePromoted->operands()) {
4214       const Value *Val = U.get();
4215       if (Val == getEndOfTransition()) {
4216         // If the use is a division and the transition is on the rhs,
4217         // we cannot promote the operation, otherwise we may create a
4218         // division by zero.
4219         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
4220           return false;
4221         continue;
4222       }
4223       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
4224           !isa<ConstantFP>(Val))
4225         return false;
4226     }
4227     // Check that the resulting operation is legal.
4228     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
4229     if (!ISDOpcode)
4230       return false;
4231     return StressStoreExtract ||
4232            TLI.isOperationLegalOrCustom(
4233                ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
4234   }
4235
4236   /// \brief Check whether or not \p Use can be combined
4237   /// with the transition.
4238   /// I.e., is it possible to do Use(Transition) => AnotherUse?
4239   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
4240
4241   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
4242   void enqueueForPromotion(Instruction *ToBePromoted) {
4243     InstsToBePromoted.push_back(ToBePromoted);
4244   }
4245
4246   /// \brief Set the instruction that will be combined with the transition.
4247   void recordCombineInstruction(Instruction *ToBeCombined) {
4248     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
4249     CombineInst = ToBeCombined;
4250   }
4251
4252   /// \brief Promote all the instructions enqueued for promotion if it is
4253   /// is profitable.
4254   /// \return True if the promotion happened, false otherwise.
4255   bool promote() {
4256     // Check if there is something to promote.
4257     // Right now, if we do not have anything to combine with,
4258     // we assume the promotion is not profitable.
4259     if (InstsToBePromoted.empty() || !CombineInst)
4260       return false;
4261
4262     // Check cost.
4263     if (!StressStoreExtract && !isProfitableToPromote())
4264       return false;
4265
4266     // Promote.
4267     for (auto &ToBePromoted : InstsToBePromoted)
4268       promoteImpl(ToBePromoted);
4269     InstsToBePromoted.clear();
4270     return true;
4271   }
4272 };
4273 } // End of anonymous namespace.
4274
4275 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
4276   // At this point, we know that all the operands of ToBePromoted but Def
4277   // can be statically promoted.
4278   // For Def, we need to use its parameter in ToBePromoted:
4279   // b = ToBePromoted ty1 a
4280   // Def = Transition ty1 b to ty2
4281   // Move the transition down.
4282   // 1. Replace all uses of the promoted operation by the transition.
4283   // = ... b => = ... Def.
4284   assert(ToBePromoted->getType() == Transition->getType() &&
4285          "The type of the result of the transition does not match "
4286          "the final type");
4287   ToBePromoted->replaceAllUsesWith(Transition);
4288   // 2. Update the type of the uses.
4289   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
4290   Type *TransitionTy = getTransitionType();
4291   ToBePromoted->mutateType(TransitionTy);
4292   // 3. Update all the operands of the promoted operation with promoted
4293   // operands.
4294   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
4295   for (Use &U : ToBePromoted->operands()) {
4296     Value *Val = U.get();
4297     Value *NewVal = nullptr;
4298     if (Val == Transition)
4299       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
4300     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
4301              isa<ConstantFP>(Val)) {
4302       // Use a splat constant if it is not safe to use undef.
4303       NewVal = getConstantVector(
4304           cast<Constant>(Val),
4305           isa<UndefValue>(Val) ||
4306               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
4307     } else
4308       llvm_unreachable("Did you modified shouldPromote and forgot to update "
4309                        "this?");
4310     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
4311   }
4312   Transition->removeFromParent();
4313   Transition->insertAfter(ToBePromoted);
4314   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
4315 }
4316
4317 /// Some targets can do store(extractelement) with one instruction.
4318 /// Try to push the extractelement towards the stores when the target
4319 /// has this feature and this is profitable.
4320 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
4321   unsigned CombineCost = UINT_MAX;
4322   if (DisableStoreExtract || !TLI ||
4323       (!StressStoreExtract &&
4324        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
4325                                        Inst->getOperand(1), CombineCost)))
4326     return false;
4327
4328   // At this point we know that Inst is a vector to scalar transition.
4329   // Try to move it down the def-use chain, until:
4330   // - We can combine the transition with its single use
4331   //   => we got rid of the transition.
4332   // - We escape the current basic block
4333   //   => we would need to check that we are moving it at a cheaper place and
4334   //      we do not do that for now.
4335   BasicBlock *Parent = Inst->getParent();
4336   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
4337   VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
4338   // If the transition has more than one use, assume this is not going to be
4339   // beneficial.
4340   while (Inst->hasOneUse()) {
4341     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
4342     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
4343
4344     if (ToBePromoted->getParent() != Parent) {
4345       DEBUG(dbgs() << "Instruction to promote is in a different block ("
4346                    << ToBePromoted->getParent()->getName()
4347                    << ") than the transition (" << Parent->getName() << ").\n");
4348       return false;
4349     }
4350
4351     if (VPH.canCombine(ToBePromoted)) {
4352       DEBUG(dbgs() << "Assume " << *Inst << '\n'
4353                    << "will be combined with: " << *ToBePromoted << '\n');
4354       VPH.recordCombineInstruction(ToBePromoted);
4355       bool Changed = VPH.promote();
4356       NumStoreExtractExposed += Changed;
4357       return Changed;
4358     }
4359
4360     DEBUG(dbgs() << "Try promoting.\n");
4361     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
4362       return false;
4363
4364     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
4365
4366     VPH.enqueueForPromotion(ToBePromoted);
4367     Inst = ToBePromoted;
4368   }
4369   return false;
4370 }
4371
4372 bool CodeGenPrepare::OptimizeInst(Instruction *I, bool& ModifiedDT) {
4373   // Bail out if we inserted the instruction to prevent optimizations from
4374   // stepping on each other's toes.
4375   if (InsertedInsts.count(I))
4376     return false;
4377
4378   if (PHINode *P = dyn_cast<PHINode>(I)) {
4379     // It is possible for very late stage optimizations (such as SimplifyCFG)
4380     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
4381     // trivial PHI, go ahead and zap it here.
4382     if (Value *V = SimplifyInstruction(P, *DL, TLInfo, nullptr)) {
4383       P->replaceAllUsesWith(V);
4384       P->eraseFromParent();
4385       ++NumPHIsElim;
4386       return true;
4387     }
4388     return false;
4389   }
4390
4391   if (CastInst *CI = dyn_cast<CastInst>(I)) {
4392     // If the source of the cast is a constant, then this should have
4393     // already been constant folded.  The only reason NOT to constant fold
4394     // it is if something (e.g. LSR) was careful to place the constant
4395     // evaluation in a block other than then one that uses it (e.g. to hoist
4396     // the address of globals out of a loop).  If this is the case, we don't
4397     // want to forward-subst the cast.
4398     if (isa<Constant>(CI->getOperand(0)))
4399       return false;
4400
4401     if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
4402       return true;
4403
4404     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
4405       /// Sink a zext or sext into its user blocks if the target type doesn't
4406       /// fit in one register
4407       if (TLI &&
4408           TLI->getTypeAction(CI->getContext(),
4409                              TLI->getValueType(*DL, CI->getType())) ==
4410               TargetLowering::TypeExpandInteger) {
4411         return SinkCast(CI);
4412       } else {
4413         bool MadeChange = MoveExtToFormExtLoad(I);
4414         return MadeChange | OptimizeExtUses(I);
4415       }
4416     }
4417     return false;
4418   }
4419
4420   if (CmpInst *CI = dyn_cast<CmpInst>(I))
4421     if (!TLI || !TLI->hasMultipleConditionRegisters())
4422       return OptimizeCmpExpression(CI);
4423
4424   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
4425     if (TLI) {
4426       unsigned AS = LI->getPointerAddressSpace();
4427       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
4428     }
4429     return false;
4430   }
4431
4432   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
4433     if (TLI) {
4434       unsigned AS = SI->getPointerAddressSpace();
4435       return OptimizeMemoryInst(I, SI->getOperand(1),
4436                                 SI->getOperand(0)->getType(), AS);
4437     }
4438     return false;
4439   }
4440
4441   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
4442
4443   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
4444                 BinOp->getOpcode() == Instruction::LShr)) {
4445     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
4446     if (TLI && CI && TLI->hasExtractBitsInsn())
4447       return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
4448
4449     return false;
4450   }
4451
4452   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
4453     if (GEPI->hasAllZeroIndices()) {
4454       /// The GEP operand must be a pointer, so must its result -> BitCast
4455       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
4456                                         GEPI->getName(), GEPI);
4457       GEPI->replaceAllUsesWith(NC);
4458       GEPI->eraseFromParent();
4459       ++NumGEPsElim;
4460       OptimizeInst(NC, ModifiedDT);
4461       return true;
4462     }
4463     return false;
4464   }
4465
4466   if (CallInst *CI = dyn_cast<CallInst>(I))
4467     return OptimizeCallInst(CI, ModifiedDT);
4468
4469   if (SelectInst *SI = dyn_cast<SelectInst>(I))
4470     return OptimizeSelectInst(SI);
4471
4472   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
4473     return OptimizeShuffleVectorInst(SVI);
4474
4475   if (isa<ExtractElementInst>(I))
4476     return OptimizeExtractElementInst(I);
4477
4478   return false;
4479 }
4480
4481 // In this pass we look for GEP and cast instructions that are used
4482 // across basic blocks and rewrite them to improve basic-block-at-a-time
4483 // selection.
4484 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
4485   SunkAddrs.clear();
4486   bool MadeChange = false;
4487
4488   CurInstIterator = BB.begin();
4489   while (CurInstIterator != BB.end()) {
4490     MadeChange |= OptimizeInst(CurInstIterator++, ModifiedDT);
4491     if (ModifiedDT)
4492       return true;
4493   }
4494   MadeChange |= DupRetToEnableTailCallOpts(&BB);
4495
4496   return MadeChange;
4497 }
4498
4499 // llvm.dbg.value is far away from the value then iSel may not be able
4500 // handle it properly. iSel will drop llvm.dbg.value if it can not
4501 // find a node corresponding to the value.
4502 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
4503   bool MadeChange = false;
4504   for (BasicBlock &BB : F) {
4505     Instruction *PrevNonDbgInst = nullptr;
4506     for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
4507       Instruction *Insn = BI++;
4508       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
4509       // Leave dbg.values that refer to an alloca alone. These
4510       // instrinsics describe the address of a variable (= the alloca)
4511       // being taken.  They should not be moved next to the alloca
4512       // (and to the beginning of the scope), but rather stay close to
4513       // where said address is used.
4514       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
4515         PrevNonDbgInst = Insn;
4516         continue;
4517       }
4518
4519       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
4520       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
4521         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
4522         DVI->removeFromParent();
4523         if (isa<PHINode>(VI))
4524           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
4525         else
4526           DVI->insertAfter(VI);
4527         MadeChange = true;
4528         ++NumDbgValueMoved;
4529       }
4530     }
4531   }
4532   return MadeChange;
4533 }
4534
4535 // If there is a sequence that branches based on comparing a single bit
4536 // against zero that can be combined into a single instruction, and the
4537 // target supports folding these into a single instruction, sink the
4538 // mask and compare into the branch uses. Do this before OptimizeBlock ->
4539 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
4540 // searched for.
4541 bool CodeGenPrepare::sinkAndCmp(Function &F) {
4542   if (!EnableAndCmpSinking)
4543     return false;
4544   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
4545     return false;
4546   bool MadeChange = false;
4547   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
4548     BasicBlock *BB = I++;
4549
4550     // Does this BB end with the following?
4551     //   %andVal = and %val, #single-bit-set
4552     //   %icmpVal = icmp %andResult, 0
4553     //   br i1 %cmpVal label %dest1, label %dest2"
4554     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
4555     if (!Brcc || !Brcc->isConditional())
4556       continue;
4557     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
4558     if (!Cmp || Cmp->getParent() != BB)
4559       continue;
4560     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
4561     if (!Zero || !Zero->isZero())
4562       continue;
4563     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
4564     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
4565       continue;
4566     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
4567     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
4568       continue;
4569     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
4570
4571     // Push the "and; icmp" for any users that are conditional branches.
4572     // Since there can only be one branch use per BB, we don't need to keep
4573     // track of which BBs we insert into.
4574     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
4575          UI != E; ) {
4576       Use &TheUse = *UI;
4577       // Find brcc use.
4578       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
4579       ++UI;
4580       if (!BrccUser || !BrccUser->isConditional())
4581         continue;
4582       BasicBlock *UserBB = BrccUser->getParent();
4583       if (UserBB == BB) continue;
4584       DEBUG(dbgs() << "found Brcc use\n");
4585
4586       // Sink the "and; icmp" to use.
4587       MadeChange = true;
4588       BinaryOperator *NewAnd =
4589         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
4590                                   BrccUser);
4591       CmpInst *NewCmp =
4592         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
4593                         "", BrccUser);
4594       TheUse = NewCmp;
4595       ++NumAndCmpsMoved;
4596       DEBUG(BrccUser->getParent()->dump());
4597     }
4598   }
4599   return MadeChange;
4600 }
4601
4602 /// \brief Retrieve the probabilities of a conditional branch. Returns true on
4603 /// success, or returns false if no or invalid metadata was found.
4604 static bool extractBranchMetadata(BranchInst *BI,
4605                                   uint64_t &ProbTrue, uint64_t &ProbFalse) {
4606   assert(BI->isConditional() &&
4607          "Looking for probabilities on unconditional branch?");
4608   auto *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
4609   if (!ProfileData || ProfileData->getNumOperands() != 3)
4610     return false;
4611
4612   const auto *CITrue =
4613       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
4614   const auto *CIFalse =
4615       mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
4616   if (!CITrue || !CIFalse)
4617     return false;
4618
4619   ProbTrue = CITrue->getValue().getZExtValue();
4620   ProbFalse = CIFalse->getValue().getZExtValue();
4621
4622   return true;
4623 }
4624
4625 /// \brief Scale down both weights to fit into uint32_t.
4626 static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
4627   uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
4628   uint32_t Scale = (NewMax / UINT32_MAX) + 1;
4629   NewTrue = NewTrue / Scale;
4630   NewFalse = NewFalse / Scale;
4631 }
4632
4633 /// \brief Some targets prefer to split a conditional branch like:
4634 /// \code
4635 ///   %0 = icmp ne i32 %a, 0
4636 ///   %1 = icmp ne i32 %b, 0
4637 ///   %or.cond = or i1 %0, %1
4638 ///   br i1 %or.cond, label %TrueBB, label %FalseBB
4639 /// \endcode
4640 /// into multiple branch instructions like:
4641 /// \code
4642 ///   bb1:
4643 ///     %0 = icmp ne i32 %a, 0
4644 ///     br i1 %0, label %TrueBB, label %bb2
4645 ///   bb2:
4646 ///     %1 = icmp ne i32 %b, 0
4647 ///     br i1 %1, label %TrueBB, label %FalseBB
4648 /// \endcode
4649 /// This usually allows instruction selection to do even further optimizations
4650 /// and combine the compare with the branch instruction. Currently this is
4651 /// applied for targets which have "cheap" jump instructions.
4652 ///
4653 /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
4654 ///
4655 bool CodeGenPrepare::splitBranchCondition(Function &F) {
4656   if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
4657     return false;
4658
4659   bool MadeChange = false;
4660   for (auto &BB : F) {
4661     // Does this BB end with the following?
4662     //   %cond1 = icmp|fcmp|binary instruction ...
4663     //   %cond2 = icmp|fcmp|binary instruction ...
4664     //   %cond.or = or|and i1 %cond1, cond2
4665     //   br i1 %cond.or label %dest1, label %dest2"
4666     BinaryOperator *LogicOp;
4667     BasicBlock *TBB, *FBB;
4668     if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
4669       continue;
4670
4671     unsigned Opc;
4672     Value *Cond1, *Cond2;
4673     if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
4674                              m_OneUse(m_Value(Cond2)))))
4675       Opc = Instruction::And;
4676     else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
4677                                  m_OneUse(m_Value(Cond2)))))
4678       Opc = Instruction::Or;
4679     else
4680       continue;
4681
4682     if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
4683         !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp()))   )
4684       continue;
4685
4686     DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
4687
4688     // Create a new BB.
4689     auto *InsertBefore = std::next(Function::iterator(BB))
4690         .getNodePtrUnchecked();
4691     auto TmpBB = BasicBlock::Create(BB.getContext(),
4692                                     BB.getName() + ".cond.split",
4693                                     BB.getParent(), InsertBefore);
4694
4695     // Update original basic block by using the first condition directly by the
4696     // branch instruction and removing the no longer needed and/or instruction.
4697     auto *Br1 = cast<BranchInst>(BB.getTerminator());
4698     Br1->setCondition(Cond1);
4699     LogicOp->eraseFromParent();
4700
4701     // Depending on the conditon we have to either replace the true or the false
4702     // successor of the original branch instruction.
4703     if (Opc == Instruction::And)
4704       Br1->setSuccessor(0, TmpBB);
4705     else
4706       Br1->setSuccessor(1, TmpBB);
4707
4708     // Fill in the new basic block.
4709     auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
4710     if (auto *I = dyn_cast<Instruction>(Cond2)) {
4711       I->removeFromParent();
4712       I->insertBefore(Br2);
4713     }
4714
4715     // Update PHI nodes in both successors. The original BB needs to be
4716     // replaced in one succesor's PHI nodes, because the branch comes now from
4717     // the newly generated BB (NewBB). In the other successor we need to add one
4718     // incoming edge to the PHI nodes, because both branch instructions target
4719     // now the same successor. Depending on the original branch condition
4720     // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
4721     // we perfrom the correct update for the PHI nodes.
4722     // This doesn't change the successor order of the just created branch
4723     // instruction (or any other instruction).
4724     if (Opc == Instruction::Or)
4725       std::swap(TBB, FBB);
4726
4727     // Replace the old BB with the new BB.
4728     for (auto &I : *TBB) {
4729       PHINode *PN = dyn_cast<PHINode>(&I);
4730       if (!PN)
4731         break;
4732       int i;
4733       while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
4734         PN->setIncomingBlock(i, TmpBB);
4735     }
4736
4737     // Add another incoming edge form the new BB.
4738     for (auto &I : *FBB) {
4739       PHINode *PN = dyn_cast<PHINode>(&I);
4740       if (!PN)
4741         break;
4742       auto *Val = PN->getIncomingValueForBlock(&BB);
4743       PN->addIncoming(Val, TmpBB);
4744     }
4745
4746     // Update the branch weights (from SelectionDAGBuilder::
4747     // FindMergedConditions).
4748     if (Opc == Instruction::Or) {
4749       // Codegen X | Y as:
4750       // BB1:
4751       //   jmp_if_X TBB
4752       //   jmp TmpBB
4753       // TmpBB:
4754       //   jmp_if_Y TBB
4755       //   jmp FBB
4756       //
4757
4758       // We have flexibility in setting Prob for BB1 and Prob for NewBB.
4759       // The requirement is that
4760       //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
4761       //     = TrueProb for orignal BB.
4762       // Assuming the orignal weights are A and B, one choice is to set BB1's
4763       // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
4764       // assumes that
4765       //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
4766       // Another choice is to assume TrueProb for BB1 equals to TrueProb for
4767       // TmpBB, but the math is more complicated.
4768       uint64_t TrueWeight, FalseWeight;
4769       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4770         uint64_t NewTrueWeight = TrueWeight;
4771         uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
4772         scaleWeights(NewTrueWeight, NewFalseWeight);
4773         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4774                          .createBranchWeights(TrueWeight, FalseWeight));
4775
4776         NewTrueWeight = TrueWeight;
4777         NewFalseWeight = 2 * FalseWeight;
4778         scaleWeights(NewTrueWeight, NewFalseWeight);
4779         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4780                          .createBranchWeights(TrueWeight, FalseWeight));
4781       }
4782     } else {
4783       // Codegen X & Y as:
4784       // BB1:
4785       //   jmp_if_X TmpBB
4786       //   jmp FBB
4787       // TmpBB:
4788       //   jmp_if_Y TBB
4789       //   jmp FBB
4790       //
4791       //  This requires creation of TmpBB after CurBB.
4792
4793       // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
4794       // The requirement is that
4795       //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
4796       //     = FalseProb for orignal BB.
4797       // Assuming the orignal weights are A and B, one choice is to set BB1's
4798       // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
4799       // assumes that
4800       //   FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
4801       uint64_t TrueWeight, FalseWeight;
4802       if (extractBranchMetadata(Br1, TrueWeight, FalseWeight)) {
4803         uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
4804         uint64_t NewFalseWeight = FalseWeight;
4805         scaleWeights(NewTrueWeight, NewFalseWeight);
4806         Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
4807                          .createBranchWeights(TrueWeight, FalseWeight));
4808
4809         NewTrueWeight = 2 * TrueWeight;
4810         NewFalseWeight = FalseWeight;
4811         scaleWeights(NewTrueWeight, NewFalseWeight);
4812         Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
4813                          .createBranchWeights(TrueWeight, FalseWeight));
4814       }
4815     }
4816
4817     // Note: No point in getting fancy here, since the DT info is never
4818     // available to CodeGenPrepare.
4819     ModifiedDT = true;
4820
4821     MadeChange = true;
4822
4823     DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
4824           TmpBB->dump());
4825   }
4826   return MadeChange;
4827 }