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