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