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