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