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