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