Sink DwarfUnit::LabelBegin down into DwarfCompileUnit since that's the only place...
[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/TargetTransformInfo.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/IRBuilder.h"
30 #include "llvm/IR/InlineAsm.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/IntrinsicInst.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/IR/ValueMap.h"
36 #include "llvm/Pass.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetLibraryInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetSubtargetInfo.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/BuildLibCalls.h"
45 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 using namespace llvm;
48 using namespace llvm::PatternMatch;
49
50 #define DEBUG_TYPE "codegenprepare"
51
52 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
53 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
54 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
55 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
56                       "sunken Cmps");
57 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
58                        "of sunken Casts");
59 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
60                           "computations were sunk");
61 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
62 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
63 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
64 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
65 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
66 STATISTIC(NumAndCmpsMoved, "Number of and/cmp's pushed into branches");
67 STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
68
69 static cl::opt<bool> DisableBranchOpts(
70   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
71   cl::desc("Disable branch optimizations in CodeGenPrepare"));
72
73 static cl::opt<bool> DisableSelectToBranch(
74   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
75   cl::desc("Disable select to branch conversion."));
76
77 static cl::opt<bool> AddrSinkUsingGEPs(
78   "addr-sink-using-gep", cl::Hidden, cl::init(false),
79   cl::desc("Address sinking in CGP using GEPs."));
80
81 static cl::opt<bool> EnableAndCmpSinking(
82    "enable-andcmp-sinking", cl::Hidden, cl::init(true),
83    cl::desc("Enable sinkinig and/cmp into branches."));
84
85 static cl::opt<bool> DisableStoreExtract(
86     "disable-cgp-store-extract", cl::Hidden, cl::init(false),
87     cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
88
89 static cl::opt<bool> StressStoreExtract(
90     "stress-cgp-store-extract", cl::Hidden, cl::init(false),
91     cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
92
93 namespace {
94 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
95 typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
96
97   class CodeGenPrepare : public FunctionPass {
98     /// TLI - Keep a pointer of a TargetLowering to consult for determining
99     /// transformation profitability.
100     const TargetMachine *TM;
101     const TargetLowering *TLI;
102     const TargetTransformInfo *TTI;
103     const TargetLibraryInfo *TLInfo;
104     DominatorTree *DT;
105
106     /// CurInstIterator - As we scan instructions optimizing them, this is the
107     /// next instruction to optimize.  Xforms that can invalidate this should
108     /// update it.
109     BasicBlock::iterator CurInstIterator;
110
111     /// Keeps track of non-local addresses that have been sunk into a block.
112     /// This allows us to avoid inserting duplicate code for blocks with
113     /// multiple load/stores of the same address.
114     ValueMap<Value*, Value*> SunkAddrs;
115
116     /// Keeps track of all truncates inserted for the current function.
117     SetOfInstrs InsertedTruncsSet;
118     /// Keeps track of the type of the related instruction before their
119     /// promotion for the current function.
120     InstrToOrigTy PromotedInsts;
121
122     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
123     /// be updated.
124     bool ModifiedDT;
125
126     /// OptSize - True if optimizing for size.
127     bool OptSize;
128
129   public:
130     static char ID; // Pass identification, replacement for typeid
131     explicit CodeGenPrepare(const TargetMachine *TM = nullptr)
132         : FunctionPass(ID), TM(TM), TLI(nullptr), TTI(nullptr) {
133         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
134       }
135     bool runOnFunction(Function &F) override;
136
137     const char *getPassName() const override { return "CodeGen Prepare"; }
138
139     void getAnalysisUsage(AnalysisUsage &AU) const override {
140       AU.addPreserved<DominatorTreeWrapperPass>();
141       AU.addRequired<TargetLibraryInfo>();
142       AU.addRequired<TargetTransformInfo>();
143     }
144
145   private:
146     bool EliminateFallThrough(Function &F);
147     bool EliminateMostlyEmptyBlocks(Function &F);
148     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
149     void EliminateMostlyEmptyBlock(BasicBlock *BB);
150     bool OptimizeBlock(BasicBlock &BB);
151     bool OptimizeInst(Instruction *I);
152     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
153     bool OptimizeInlineAsmInst(CallInst *CS);
154     bool OptimizeCallInst(CallInst *CI);
155     bool MoveExtToFormExtLoad(Instruction *I);
156     bool OptimizeExtUses(Instruction *I);
157     bool OptimizeSelectInst(SelectInst *SI);
158     bool OptimizeShuffleVectorInst(ShuffleVectorInst *SI);
159     bool OptimizeExtractElementInst(Instruction *Inst);
160     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
161     bool PlaceDbgValues(Function &F);
162     bool sinkAndCmp(Function &F);
163   };
164 }
165
166 char CodeGenPrepare::ID = 0;
167 INITIALIZE_TM_PASS(CodeGenPrepare, "codegenprepare",
168                    "Optimize for code generation", false, false)
169
170 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
171   return new CodeGenPrepare(TM);
172 }
173
174 bool CodeGenPrepare::runOnFunction(Function &F) {
175   if (skipOptnoneFunction(F))
176     return false;
177
178   bool EverMadeChange = false;
179   // Clear per function information.
180   InsertedTruncsSet.clear();
181   PromotedInsts.clear();
182
183   ModifiedDT = false;
184   if (TM)
185     TLI = TM->getSubtargetImpl()->getTargetLowering();
186   TLInfo = &getAnalysis<TargetLibraryInfo>();
187   TTI = &getAnalysis<TargetTransformInfo>();
188   DominatorTreeWrapperPass *DTWP =
189       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
190   DT = DTWP ? &DTWP->getDomTree() : nullptr;
191   OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
192                                            Attribute::OptimizeForSize);
193
194   /// This optimization identifies DIV instructions that can be
195   /// profitably bypassed and carried out with a shorter, faster divide.
196   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
197     const DenseMap<unsigned int, unsigned int> &BypassWidths =
198        TLI->getBypassSlowDivWidths();
199     for (Function::iterator I = F.begin(); I != F.end(); I++)
200       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
201   }
202
203   // Eliminate blocks that contain only PHI nodes and an
204   // unconditional branch.
205   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
206
207   // llvm.dbg.value is far away from the value then iSel may not be able
208   // handle it properly. iSel will drop llvm.dbg.value if it can not
209   // find a node corresponding to the value.
210   EverMadeChange |= PlaceDbgValues(F);
211
212   // If there is a mask, compare against zero, and branch that can be combined
213   // into a single target instruction, push the mask and compare into branch
214   // users. Do this before OptimizeBlock -> OptimizeInst ->
215   // OptimizeCmpExpression, which perturbs the pattern being searched for.
216   if (!DisableBranchOpts)
217     EverMadeChange |= sinkAndCmp(F);
218
219   bool MadeChange = true;
220   while (MadeChange) {
221     MadeChange = false;
222     for (Function::iterator I = F.begin(); I != F.end(); ) {
223       BasicBlock *BB = I++;
224       MadeChange |= OptimizeBlock(*BB);
225     }
226     EverMadeChange |= MadeChange;
227   }
228
229   SunkAddrs.clear();
230
231   if (!DisableBranchOpts) {
232     MadeChange = false;
233     SmallPtrSet<BasicBlock*, 8> WorkList;
234     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
235       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
236       MadeChange |= ConstantFoldTerminator(BB, true);
237       if (!MadeChange) continue;
238
239       for (SmallVectorImpl<BasicBlock*>::iterator
240              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
241         if (pred_begin(*II) == pred_end(*II))
242           WorkList.insert(*II);
243     }
244
245     // Delete the dead blocks and any of their dead successors.
246     MadeChange |= !WorkList.empty();
247     while (!WorkList.empty()) {
248       BasicBlock *BB = *WorkList.begin();
249       WorkList.erase(BB);
250       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
251
252       DeleteDeadBlock(BB);
253
254       for (SmallVectorImpl<BasicBlock*>::iterator
255              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
256         if (pred_begin(*II) == pred_end(*II))
257           WorkList.insert(*II);
258     }
259
260     // Merge pairs of basic blocks with unconditional branches, connected by
261     // a single edge.
262     if (EverMadeChange || MadeChange)
263       MadeChange |= EliminateFallThrough(F);
264
265     if (MadeChange)
266       ModifiedDT = true;
267     EverMadeChange |= MadeChange;
268   }
269
270   if (ModifiedDT && DT)
271     DT->recalculate(F);
272
273   return EverMadeChange;
274 }
275
276 /// EliminateFallThrough - Merge basic blocks which are connected
277 /// by a single edge, where one of the basic blocks has a single successor
278 /// pointing to the other basic block, which has a single predecessor.
279 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
280   bool Changed = false;
281   // Scan all of the blocks in the function, except for the entry block.
282   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
283     BasicBlock *BB = I++;
284     // If the destination block has a single pred, then this is a trivial
285     // edge, just collapse it.
286     BasicBlock *SinglePred = BB->getSinglePredecessor();
287
288     // Don't merge if BB's address is taken.
289     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
290
291     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
292     if (Term && !Term->isConditional()) {
293       Changed = true;
294       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
295       // Remember if SinglePred was the entry block of the function.
296       // If so, we will need to move BB back to the entry position.
297       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
298       MergeBasicBlockIntoOnlyPred(BB, this);
299
300       if (isEntry && BB != &BB->getParent()->getEntryBlock())
301         BB->moveBefore(&BB->getParent()->getEntryBlock());
302
303       // We have erased a block. Update the iterator.
304       I = BB;
305     }
306   }
307   return Changed;
308 }
309
310 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
311 /// debug info directives, and an unconditional branch.  Passes before isel
312 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
313 /// isel.  Start by eliminating these blocks so we can split them the way we
314 /// want them.
315 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
316   bool MadeChange = false;
317   // Note that this intentionally skips the entry block.
318   for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
319     BasicBlock *BB = I++;
320
321     // If this block doesn't end with an uncond branch, ignore it.
322     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
323     if (!BI || !BI->isUnconditional())
324       continue;
325
326     // If the instruction before the branch (skipping debug info) isn't a phi
327     // node, then other stuff is happening here.
328     BasicBlock::iterator BBI = BI;
329     if (BBI != BB->begin()) {
330       --BBI;
331       while (isa<DbgInfoIntrinsic>(BBI)) {
332         if (BBI == BB->begin())
333           break;
334         --BBI;
335       }
336       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
337         continue;
338     }
339
340     // Do not break infinite loops.
341     BasicBlock *DestBB = BI->getSuccessor(0);
342     if (DestBB == BB)
343       continue;
344
345     if (!CanMergeBlocks(BB, DestBB))
346       continue;
347
348     EliminateMostlyEmptyBlock(BB);
349     MadeChange = true;
350   }
351   return MadeChange;
352 }
353
354 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
355 /// single uncond branch between them, and BB contains no other non-phi
356 /// instructions.
357 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
358                                     const BasicBlock *DestBB) const {
359   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
360   // the successor.  If there are more complex condition (e.g. preheaders),
361   // don't mess around with them.
362   BasicBlock::const_iterator BBI = BB->begin();
363   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
364     for (const User *U : PN->users()) {
365       const Instruction *UI = cast<Instruction>(U);
366       if (UI->getParent() != DestBB || !isa<PHINode>(UI))
367         return false;
368       // If User is inside DestBB block and it is a PHINode then check
369       // incoming value. If incoming value is not from BB then this is
370       // a complex condition (e.g. preheaders) we want to avoid here.
371       if (UI->getParent() == DestBB) {
372         if (const PHINode *UPN = dyn_cast<PHINode>(UI))
373           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
374             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
375             if (Insn && Insn->getParent() == BB &&
376                 Insn->getParent() != UPN->getIncomingBlock(I))
377               return false;
378           }
379       }
380     }
381   }
382
383   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
384   // and DestBB may have conflicting incoming values for the block.  If so, we
385   // can't merge the block.
386   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
387   if (!DestBBPN) return true;  // no conflict.
388
389   // Collect the preds of BB.
390   SmallPtrSet<const BasicBlock*, 16> BBPreds;
391   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
392     // It is faster to get preds from a PHI than with pred_iterator.
393     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
394       BBPreds.insert(BBPN->getIncomingBlock(i));
395   } else {
396     BBPreds.insert(pred_begin(BB), pred_end(BB));
397   }
398
399   // Walk the preds of DestBB.
400   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
401     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
402     if (BBPreds.count(Pred)) {   // Common predecessor?
403       BBI = DestBB->begin();
404       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
405         const Value *V1 = PN->getIncomingValueForBlock(Pred);
406         const Value *V2 = PN->getIncomingValueForBlock(BB);
407
408         // If V2 is a phi node in BB, look up what the mapped value will be.
409         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
410           if (V2PN->getParent() == BB)
411             V2 = V2PN->getIncomingValueForBlock(Pred);
412
413         // If there is a conflict, bail out.
414         if (V1 != V2) return false;
415       }
416     }
417   }
418
419   return true;
420 }
421
422
423 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
424 /// an unconditional branch in it.
425 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
426   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
427   BasicBlock *DestBB = BI->getSuccessor(0);
428
429   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
430
431   // If the destination block has a single pred, then this is a trivial edge,
432   // just collapse it.
433   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
434     if (SinglePred != DestBB) {
435       // Remember if SinglePred was the entry block of the function.  If so, we
436       // will need to move BB back to the entry position.
437       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
438       MergeBasicBlockIntoOnlyPred(DestBB, this);
439
440       if (isEntry && BB != &BB->getParent()->getEntryBlock())
441         BB->moveBefore(&BB->getParent()->getEntryBlock());
442
443       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
444       return;
445     }
446   }
447
448   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
449   // to handle the new incoming edges it is about to have.
450   PHINode *PN;
451   for (BasicBlock::iterator BBI = DestBB->begin();
452        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
453     // Remove the incoming value for BB, and remember it.
454     Value *InVal = PN->removeIncomingValue(BB, false);
455
456     // Two options: either the InVal is a phi node defined in BB or it is some
457     // value that dominates BB.
458     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
459     if (InValPhi && InValPhi->getParent() == BB) {
460       // Add all of the input values of the input PHI as inputs of this phi.
461       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
462         PN->addIncoming(InValPhi->getIncomingValue(i),
463                         InValPhi->getIncomingBlock(i));
464     } else {
465       // Otherwise, add one instance of the dominating value for each edge that
466       // we will be adding.
467       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
468         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
469           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
470       } else {
471         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
472           PN->addIncoming(InVal, *PI);
473       }
474     }
475   }
476
477   // The PHIs are now updated, change everything that refers to BB to use
478   // DestBB and remove BB.
479   BB->replaceAllUsesWith(DestBB);
480   if (DT && !ModifiedDT) {
481     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
482     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
483     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
484     DT->changeImmediateDominator(DestBB, NewIDom);
485     DT->eraseNode(BB);
486   }
487   BB->eraseFromParent();
488   ++NumBlocksElim;
489
490   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
491 }
492
493 /// SinkCast - Sink the specified cast instruction into its user blocks
494 static bool SinkCast(CastInst *CI) {
495   BasicBlock *DefBB = CI->getParent();
496
497   /// InsertedCasts - Only insert a cast in each block once.
498   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
499
500   bool MadeChange = false;
501   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
502        UI != E; ) {
503     Use &TheUse = UI.getUse();
504     Instruction *User = cast<Instruction>(*UI);
505
506     // Figure out which BB this cast is used in.  For PHI's this is the
507     // appropriate predecessor block.
508     BasicBlock *UserBB = User->getParent();
509     if (PHINode *PN = dyn_cast<PHINode>(User)) {
510       UserBB = PN->getIncomingBlock(TheUse);
511     }
512
513     // Preincrement use iterator so we don't invalidate it.
514     ++UI;
515
516     // If this user is in the same block as the cast, don't change the cast.
517     if (UserBB == DefBB) continue;
518
519     // If we have already inserted a cast into this block, use it.
520     CastInst *&InsertedCast = InsertedCasts[UserBB];
521
522     if (!InsertedCast) {
523       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
524       InsertedCast =
525         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
526                          InsertPt);
527       MadeChange = true;
528     }
529
530     // Replace a use of the cast with a use of the new cast.
531     TheUse = InsertedCast;
532     ++NumCastUses;
533   }
534
535   // If we removed all uses, nuke the cast.
536   if (CI->use_empty()) {
537     CI->eraseFromParent();
538     MadeChange = true;
539   }
540
541   return MadeChange;
542 }
543
544 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
545 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
546 /// sink it into user blocks to reduce the number of virtual
547 /// registers that must be created and coalesced.
548 ///
549 /// Return true if any changes are made.
550 ///
551 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
552   // If this is a noop copy,
553   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
554   EVT DstVT = TLI.getValueType(CI->getType());
555
556   // This is an fp<->int conversion?
557   if (SrcVT.isInteger() != DstVT.isInteger())
558     return false;
559
560   // If this is an extension, it will be a zero or sign extension, which
561   // isn't a noop.
562   if (SrcVT.bitsLT(DstVT)) return false;
563
564   // If these values will be promoted, find out what they will be promoted
565   // to.  This helps us consider truncates on PPC as noop copies when they
566   // are.
567   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
568       TargetLowering::TypePromoteInteger)
569     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
570   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
571       TargetLowering::TypePromoteInteger)
572     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
573
574   // If, after promotion, these are the same types, this is a noop copy.
575   if (SrcVT != DstVT)
576     return false;
577
578   return SinkCast(CI);
579 }
580
581 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
582 /// the number of virtual registers that must be created and coalesced.  This is
583 /// a clear win except on targets with multiple condition code registers
584 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
585 ///
586 /// Return true if any changes are made.
587 static bool OptimizeCmpExpression(CmpInst *CI) {
588   BasicBlock *DefBB = CI->getParent();
589
590   /// InsertedCmp - Only insert a cmp in each block once.
591   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
592
593   bool MadeChange = false;
594   for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
595        UI != E; ) {
596     Use &TheUse = UI.getUse();
597     Instruction *User = cast<Instruction>(*UI);
598
599     // Preincrement use iterator so we don't invalidate it.
600     ++UI;
601
602     // Don't bother for PHI nodes.
603     if (isa<PHINode>(User))
604       continue;
605
606     // Figure out which BB this cmp is used in.
607     BasicBlock *UserBB = User->getParent();
608
609     // If this user is in the same block as the cmp, don't change the cmp.
610     if (UserBB == DefBB) continue;
611
612     // If we have already inserted a cmp into this block, use it.
613     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
614
615     if (!InsertedCmp) {
616       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
617       InsertedCmp =
618         CmpInst::Create(CI->getOpcode(),
619                         CI->getPredicate(),  CI->getOperand(0),
620                         CI->getOperand(1), "", InsertPt);
621       MadeChange = true;
622     }
623
624     // Replace a use of the cmp with a use of the new cmp.
625     TheUse = InsertedCmp;
626     ++NumCmpUses;
627   }
628
629   // If we removed all uses, nuke the cmp.
630   if (CI->use_empty())
631     CI->eraseFromParent();
632
633   return MadeChange;
634 }
635
636 /// isExtractBitsCandidateUse - Check if the candidates could
637 /// be combined with shift instruction, which includes:
638 /// 1. Truncate instruction
639 /// 2. And instruction and the imm is a mask of the low bits:
640 /// imm & (imm+1) == 0
641 static bool isExtractBitsCandidateUse(Instruction *User) {
642   if (!isa<TruncInst>(User)) {
643     if (User->getOpcode() != Instruction::And ||
644         !isa<ConstantInt>(User->getOperand(1)))
645       return false;
646
647     const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
648
649     if ((Cimm & (Cimm + 1)).getBoolValue())
650       return false;
651   }
652   return true;
653 }
654
655 /// SinkShiftAndTruncate - sink both shift and truncate instruction
656 /// to the use of truncate's BB.
657 static bool
658 SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
659                      DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
660                      const TargetLowering &TLI) {
661   BasicBlock *UserBB = User->getParent();
662   DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
663   TruncInst *TruncI = dyn_cast<TruncInst>(User);
664   bool MadeChange = false;
665
666   for (Value::user_iterator TruncUI = TruncI->user_begin(),
667                             TruncE = TruncI->user_end();
668        TruncUI != TruncE;) {
669
670     Use &TruncTheUse = TruncUI.getUse();
671     Instruction *TruncUser = cast<Instruction>(*TruncUI);
672     // Preincrement use iterator so we don't invalidate it.
673
674     ++TruncUI;
675
676     int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
677     if (!ISDOpcode)
678       continue;
679
680     // If the use is actually a legal node, there will not be an
681     // implicit truncate.
682     // FIXME: always querying the result type is just an
683     // approximation; some nodes' legality is determined by the
684     // operand or other means. There's no good way to find out though.
685     if (TLI.isOperationLegalOrCustom(ISDOpcode,
686                                      EVT::getEVT(TruncUser->getType(), true)))
687       continue;
688
689     // Don't bother for PHI nodes.
690     if (isa<PHINode>(TruncUser))
691       continue;
692
693     BasicBlock *TruncUserBB = TruncUser->getParent();
694
695     if (UserBB == TruncUserBB)
696       continue;
697
698     BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
699     CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
700
701     if (!InsertedShift && !InsertedTrunc) {
702       BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
703       // Sink the shift
704       if (ShiftI->getOpcode() == Instruction::AShr)
705         InsertedShift =
706             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
707       else
708         InsertedShift =
709             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
710
711       // Sink the trunc
712       BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
713       TruncInsertPt++;
714
715       InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
716                                        TruncI->getType(), "", TruncInsertPt);
717
718       MadeChange = true;
719
720       TruncTheUse = InsertedTrunc;
721     }
722   }
723   return MadeChange;
724 }
725
726 /// OptimizeExtractBits - sink the shift *right* instruction into user blocks if
727 /// the uses could potentially be combined with this shift instruction and
728 /// generate BitExtract instruction. It will only be applied if the architecture
729 /// supports BitExtract instruction. Here is an example:
730 /// BB1:
731 ///   %x.extract.shift = lshr i64 %arg1, 32
732 /// BB2:
733 ///   %x.extract.trunc = trunc i64 %x.extract.shift to i16
734 /// ==>
735 ///
736 /// BB2:
737 ///   %x.extract.shift.1 = lshr i64 %arg1, 32
738 ///   %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
739 ///
740 /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
741 /// instruction.
742 /// Return true if any changes are made.
743 static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
744                                 const TargetLowering &TLI) {
745   BasicBlock *DefBB = ShiftI->getParent();
746
747   /// Only insert instructions in each block once.
748   DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
749
750   bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(ShiftI->getType()));
751
752   bool MadeChange = false;
753   for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
754        UI != E;) {
755     Use &TheUse = UI.getUse();
756     Instruction *User = cast<Instruction>(*UI);
757     // Preincrement use iterator so we don't invalidate it.
758     ++UI;
759
760     // Don't bother for PHI nodes.
761     if (isa<PHINode>(User))
762       continue;
763
764     if (!isExtractBitsCandidateUse(User))
765       continue;
766
767     BasicBlock *UserBB = User->getParent();
768
769     if (UserBB == DefBB) {
770       // If the shift and truncate instruction are in the same BB. The use of
771       // the truncate(TruncUse) may still introduce another truncate if not
772       // legal. In this case, we would like to sink both shift and truncate
773       // instruction to the BB of TruncUse.
774       // for example:
775       // BB1:
776       // i64 shift.result = lshr i64 opnd, imm
777       // trunc.result = trunc shift.result to i16
778       //
779       // BB2:
780       //   ----> We will have an implicit truncate here if the architecture does
781       //   not have i16 compare.
782       // cmp i16 trunc.result, opnd2
783       //
784       if (isa<TruncInst>(User) && shiftIsLegal
785           // If the type of the truncate is legal, no trucate will be
786           // introduced in other basic blocks.
787           && (!TLI.isTypeLegal(TLI.getValueType(User->getType()))))
788         MadeChange =
789             SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI);
790
791       continue;
792     }
793     // If we have already inserted a shift into this block, use it.
794     BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
795
796     if (!InsertedShift) {
797       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
798
799       if (ShiftI->getOpcode() == Instruction::AShr)
800         InsertedShift =
801             BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI, "", InsertPt);
802       else
803         InsertedShift =
804             BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI, "", InsertPt);
805
806       MadeChange = true;
807     }
808
809     // Replace a use of the shift with a use of the new shift.
810     TheUse = InsertedShift;
811   }
812
813   // If we removed all uses, nuke the shift.
814   if (ShiftI->use_empty())
815     ShiftI->eraseFromParent();
816
817   return MadeChange;
818 }
819
820 namespace {
821 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
822 protected:
823   void replaceCall(Value *With) override {
824     CI->replaceAllUsesWith(With);
825     CI->eraseFromParent();
826   }
827   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const override {
828       if (ConstantInt *SizeCI =
829                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
830         return SizeCI->isAllOnesValue();
831     return false;
832   }
833 };
834 } // end anonymous namespace
835
836 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
837   BasicBlock *BB = CI->getParent();
838
839   // Lower inline assembly if we can.
840   // If we found an inline asm expession, and if the target knows how to
841   // lower it to normal LLVM code, do so now.
842   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
843     if (TLI->ExpandInlineAsm(CI)) {
844       // Avoid invalidating the iterator.
845       CurInstIterator = BB->begin();
846       // Avoid processing instructions out of order, which could cause
847       // reuse before a value is defined.
848       SunkAddrs.clear();
849       return true;
850     }
851     // Sink address computing for memory operands into the block.
852     if (OptimizeInlineAsmInst(CI))
853       return true;
854   }
855
856   // Lower all uses of llvm.objectsize.*
857   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
858   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
859     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
860     Type *ReturnTy = CI->getType();
861     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
862
863     // Substituting this can cause recursive simplifications, which can
864     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
865     // happens.
866     WeakVH IterHandle(CurInstIterator);
867
868     replaceAndRecursivelySimplify(CI, RetVal,
869                                   TLI ? TLI->getDataLayout() : nullptr,
870                                   TLInfo, ModifiedDT ? nullptr : DT);
871
872     // If the iterator instruction was recursively deleted, start over at the
873     // start of the block.
874     if (IterHandle != CurInstIterator) {
875       CurInstIterator = BB->begin();
876       SunkAddrs.clear();
877     }
878     return true;
879   }
880
881   if (II && TLI) {
882     SmallVector<Value*, 2> PtrOps;
883     Type *AccessTy;
884     if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
885       while (!PtrOps.empty())
886         if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
887           return true;
888   }
889
890   // From here on out we're working with named functions.
891   if (!CI->getCalledFunction()) return false;
892
893   // We'll need DataLayout from here on out.
894   const DataLayout *TD = TLI ? TLI->getDataLayout() : nullptr;
895   if (!TD) return false;
896
897   // Lower all default uses of _chk calls.  This is very similar
898   // to what InstCombineCalls does, but here we are only lowering calls
899   // that have the default "don't know" as the objectsize.  Anything else
900   // should be left alone.
901   CodeGenPrepareFortifiedLibCalls Simplifier;
902   return Simplifier.fold(CI, TD, TLInfo);
903 }
904
905 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
906 /// instructions to the predecessor to enable tail call optimizations. The
907 /// case it is currently looking for is:
908 /// @code
909 /// bb0:
910 ///   %tmp0 = tail call i32 @f0()
911 ///   br label %return
912 /// bb1:
913 ///   %tmp1 = tail call i32 @f1()
914 ///   br label %return
915 /// bb2:
916 ///   %tmp2 = tail call i32 @f2()
917 ///   br label %return
918 /// return:
919 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
920 ///   ret i32 %retval
921 /// @endcode
922 ///
923 /// =>
924 ///
925 /// @code
926 /// bb0:
927 ///   %tmp0 = tail call i32 @f0()
928 ///   ret i32 %tmp0
929 /// bb1:
930 ///   %tmp1 = tail call i32 @f1()
931 ///   ret i32 %tmp1
932 /// bb2:
933 ///   %tmp2 = tail call i32 @f2()
934 ///   ret i32 %tmp2
935 /// @endcode
936 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
937   if (!TLI)
938     return false;
939
940   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
941   if (!RI)
942     return false;
943
944   PHINode *PN = nullptr;
945   BitCastInst *BCI = nullptr;
946   Value *V = RI->getReturnValue();
947   if (V) {
948     BCI = dyn_cast<BitCastInst>(V);
949     if (BCI)
950       V = BCI->getOperand(0);
951
952     PN = dyn_cast<PHINode>(V);
953     if (!PN)
954       return false;
955   }
956
957   if (PN && PN->getParent() != BB)
958     return false;
959
960   // It's not safe to eliminate the sign / zero extension of the return value.
961   // See llvm::isInTailCallPosition().
962   const Function *F = BB->getParent();
963   AttributeSet CallerAttrs = F->getAttributes();
964   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
965       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
966     return false;
967
968   // Make sure there are no instructions between the PHI and return, or that the
969   // return is the first instruction in the block.
970   if (PN) {
971     BasicBlock::iterator BI = BB->begin();
972     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
973     if (&*BI == BCI)
974       // Also skip over the bitcast.
975       ++BI;
976     if (&*BI != RI)
977       return false;
978   } else {
979     BasicBlock::iterator BI = BB->begin();
980     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
981     if (&*BI != RI)
982       return false;
983   }
984
985   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
986   /// call.
987   SmallVector<CallInst*, 4> TailCalls;
988   if (PN) {
989     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
990       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
991       // Make sure the phi value is indeed produced by the tail call.
992       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
993           TLI->mayBeEmittedAsTailCall(CI))
994         TailCalls.push_back(CI);
995     }
996   } else {
997     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
998     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
999       if (!VisitedBBs.insert(*PI))
1000         continue;
1001
1002       BasicBlock::InstListType &InstList = (*PI)->getInstList();
1003       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
1004       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
1005       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
1006       if (RI == RE)
1007         continue;
1008
1009       CallInst *CI = dyn_cast<CallInst>(&*RI);
1010       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
1011         TailCalls.push_back(CI);
1012     }
1013   }
1014
1015   bool Changed = false;
1016   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
1017     CallInst *CI = TailCalls[i];
1018     CallSite CS(CI);
1019
1020     // Conservatively require the attributes of the call to match those of the
1021     // return. Ignore noalias because it doesn't affect the call sequence.
1022     AttributeSet CalleeAttrs = CS.getAttributes();
1023     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1024           removeAttribute(Attribute::NoAlias) !=
1025         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
1026           removeAttribute(Attribute::NoAlias))
1027       continue;
1028
1029     // Make sure the call instruction is followed by an unconditional branch to
1030     // the return block.
1031     BasicBlock *CallBB = CI->getParent();
1032     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
1033     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
1034       continue;
1035
1036     // Duplicate the return into CallBB.
1037     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
1038     ModifiedDT = Changed = true;
1039     ++NumRetsDup;
1040   }
1041
1042   // If we eliminated all predecessors of the block, delete the block now.
1043   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
1044     BB->eraseFromParent();
1045
1046   return Changed;
1047 }
1048
1049 //===----------------------------------------------------------------------===//
1050 // Memory Optimization
1051 //===----------------------------------------------------------------------===//
1052
1053 namespace {
1054
1055 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
1056 /// which holds actual Value*'s for register values.
1057 struct ExtAddrMode : public TargetLowering::AddrMode {
1058   Value *BaseReg;
1059   Value *ScaledReg;
1060   ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
1061   void print(raw_ostream &OS) const;
1062   void dump() const;
1063
1064   bool operator==(const ExtAddrMode& O) const {
1065     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
1066            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
1067            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
1068   }
1069 };
1070
1071 #ifndef NDEBUG
1072 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
1073   AM.print(OS);
1074   return OS;
1075 }
1076 #endif
1077
1078 void ExtAddrMode::print(raw_ostream &OS) const {
1079   bool NeedPlus = false;
1080   OS << "[";
1081   if (BaseGV) {
1082     OS << (NeedPlus ? " + " : "")
1083        << "GV:";
1084     BaseGV->printAsOperand(OS, /*PrintType=*/false);
1085     NeedPlus = true;
1086   }
1087
1088   if (BaseOffs) {
1089     OS << (NeedPlus ? " + " : "")
1090        << BaseOffs;
1091     NeedPlus = true;
1092   }
1093
1094   if (BaseReg) {
1095     OS << (NeedPlus ? " + " : "")
1096        << "Base:";
1097     BaseReg->printAsOperand(OS, /*PrintType=*/false);
1098     NeedPlus = true;
1099   }
1100   if (Scale) {
1101     OS << (NeedPlus ? " + " : "")
1102        << Scale << "*";
1103     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
1104   }
1105
1106   OS << ']';
1107 }
1108
1109 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1110 void ExtAddrMode::dump() const {
1111   print(dbgs());
1112   dbgs() << '\n';
1113 }
1114 #endif
1115
1116 /// \brief This class provides transaction based operation on the IR.
1117 /// Every change made through this class is recorded in the internal state and
1118 /// can be undone (rollback) until commit is called.
1119 class TypePromotionTransaction {
1120
1121   /// \brief This represents the common interface of the individual transaction.
1122   /// Each class implements the logic for doing one specific modification on
1123   /// the IR via the TypePromotionTransaction.
1124   class TypePromotionAction {
1125   protected:
1126     /// The Instruction modified.
1127     Instruction *Inst;
1128
1129   public:
1130     /// \brief Constructor of the action.
1131     /// The constructor performs the related action on the IR.
1132     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
1133
1134     virtual ~TypePromotionAction() {}
1135
1136     /// \brief Undo the modification done by this action.
1137     /// When this method is called, the IR must be in the same state as it was
1138     /// before this action was applied.
1139     /// \pre Undoing the action works if and only if the IR is in the exact same
1140     /// state as it was directly after this action was applied.
1141     virtual void undo() = 0;
1142
1143     /// \brief Advocate every change made by this action.
1144     /// When the results on the IR of the action are to be kept, it is important
1145     /// to call this function, otherwise hidden information may be kept forever.
1146     virtual void commit() {
1147       // Nothing to be done, this action is not doing anything.
1148     }
1149   };
1150
1151   /// \brief Utility to remember the position of an instruction.
1152   class InsertionHandler {
1153     /// Position of an instruction.
1154     /// Either an instruction:
1155     /// - Is the first in a basic block: BB is used.
1156     /// - Has a previous instructon: PrevInst is used.
1157     union {
1158       Instruction *PrevInst;
1159       BasicBlock *BB;
1160     } Point;
1161     /// Remember whether or not the instruction had a previous instruction.
1162     bool HasPrevInstruction;
1163
1164   public:
1165     /// \brief Record the position of \p Inst.
1166     InsertionHandler(Instruction *Inst) {
1167       BasicBlock::iterator It = Inst;
1168       HasPrevInstruction = (It != (Inst->getParent()->begin()));
1169       if (HasPrevInstruction)
1170         Point.PrevInst = --It;
1171       else
1172         Point.BB = Inst->getParent();
1173     }
1174
1175     /// \brief Insert \p Inst at the recorded position.
1176     void insert(Instruction *Inst) {
1177       if (HasPrevInstruction) {
1178         if (Inst->getParent())
1179           Inst->removeFromParent();
1180         Inst->insertAfter(Point.PrevInst);
1181       } else {
1182         Instruction *Position = Point.BB->getFirstInsertionPt();
1183         if (Inst->getParent())
1184           Inst->moveBefore(Position);
1185         else
1186           Inst->insertBefore(Position);
1187       }
1188     }
1189   };
1190
1191   /// \brief Move an instruction before another.
1192   class InstructionMoveBefore : public TypePromotionAction {
1193     /// Original position of the instruction.
1194     InsertionHandler Position;
1195
1196   public:
1197     /// \brief Move \p Inst before \p Before.
1198     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
1199         : TypePromotionAction(Inst), Position(Inst) {
1200       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
1201       Inst->moveBefore(Before);
1202     }
1203
1204     /// \brief Move the instruction back to its original position.
1205     void undo() override {
1206       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
1207       Position.insert(Inst);
1208     }
1209   };
1210
1211   /// \brief Set the operand of an instruction with a new value.
1212   class OperandSetter : public TypePromotionAction {
1213     /// Original operand of the instruction.
1214     Value *Origin;
1215     /// Index of the modified instruction.
1216     unsigned Idx;
1217
1218   public:
1219     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1220     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1221         : TypePromotionAction(Inst), Idx(Idx) {
1222       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1223                    << "for:" << *Inst << "\n"
1224                    << "with:" << *NewVal << "\n");
1225       Origin = Inst->getOperand(Idx);
1226       Inst->setOperand(Idx, NewVal);
1227     }
1228
1229     /// \brief Restore the original value of the instruction.
1230     void undo() override {
1231       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1232                    << "for: " << *Inst << "\n"
1233                    << "with: " << *Origin << "\n");
1234       Inst->setOperand(Idx, Origin);
1235     }
1236   };
1237
1238   /// \brief Hide the operands of an instruction.
1239   /// Do as if this instruction was not using any of its operands.
1240   class OperandsHider : public TypePromotionAction {
1241     /// The list of original operands.
1242     SmallVector<Value *, 4> OriginalValues;
1243
1244   public:
1245     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1246     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1247       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1248       unsigned NumOpnds = Inst->getNumOperands();
1249       OriginalValues.reserve(NumOpnds);
1250       for (unsigned It = 0; It < NumOpnds; ++It) {
1251         // Save the current operand.
1252         Value *Val = Inst->getOperand(It);
1253         OriginalValues.push_back(Val);
1254         // Set a dummy one.
1255         // We could use OperandSetter here, but that would implied an overhead
1256         // that we are not willing to pay.
1257         Inst->setOperand(It, UndefValue::get(Val->getType()));
1258       }
1259     }
1260
1261     /// \brief Restore the original list of uses.
1262     void undo() override {
1263       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1264       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1265         Inst->setOperand(It, OriginalValues[It]);
1266     }
1267   };
1268
1269   /// \brief Build a truncate instruction.
1270   class TruncBuilder : public TypePromotionAction {
1271     Value *Val;
1272   public:
1273     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1274     /// result.
1275     /// trunc Opnd to Ty.
1276     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1277       IRBuilder<> Builder(Opnd);
1278       Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
1279       DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
1280     }
1281
1282     /// \brief Get the built value.
1283     Value *getBuiltValue() { return Val; }
1284
1285     /// \brief Remove the built instruction.
1286     void undo() override {
1287       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
1288       if (Instruction *IVal = dyn_cast<Instruction>(Val))
1289         IVal->eraseFromParent();
1290     }
1291   };
1292
1293   /// \brief Build a sign extension instruction.
1294   class SExtBuilder : public TypePromotionAction {
1295     Value *Val;
1296   public:
1297     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1298     /// result.
1299     /// sext Opnd to Ty.
1300     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1301         : TypePromotionAction(InsertPt) {
1302       IRBuilder<> Builder(InsertPt);
1303       Val = Builder.CreateSExt(Opnd, Ty, "promoted");
1304       DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
1305     }
1306
1307     /// \brief Get the built value.
1308     Value *getBuiltValue() { return Val; }
1309
1310     /// \brief Remove the built instruction.
1311     void undo() override {
1312       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
1313       if (Instruction *IVal = dyn_cast<Instruction>(Val))
1314         IVal->eraseFromParent();
1315     }
1316   };
1317
1318   /// \brief Build a zero extension instruction.
1319   class ZExtBuilder : public TypePromotionAction {
1320     Value *Val;
1321   public:
1322     /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
1323     /// result.
1324     /// zext Opnd to Ty.
1325     ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1326         : TypePromotionAction(InsertPt) {
1327       IRBuilder<> Builder(InsertPt);
1328       Val = Builder.CreateZExt(Opnd, Ty, "promoted");
1329       DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
1330     }
1331
1332     /// \brief Get the built value.
1333     Value *getBuiltValue() { return Val; }
1334
1335     /// \brief Remove the built instruction.
1336     void undo() override {
1337       DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
1338       if (Instruction *IVal = dyn_cast<Instruction>(Val))
1339         IVal->eraseFromParent();
1340     }
1341   };
1342
1343   /// \brief Mutate an instruction to another type.
1344   class TypeMutator : public TypePromotionAction {
1345     /// Record the original type.
1346     Type *OrigTy;
1347
1348   public:
1349     /// \brief Mutate the type of \p Inst into \p NewTy.
1350     TypeMutator(Instruction *Inst, Type *NewTy)
1351         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1352       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1353                    << "\n");
1354       Inst->mutateType(NewTy);
1355     }
1356
1357     /// \brief Mutate the instruction back to its original type.
1358     void undo() override {
1359       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1360                    << "\n");
1361       Inst->mutateType(OrigTy);
1362     }
1363   };
1364
1365   /// \brief Replace the uses of an instruction by another instruction.
1366   class UsesReplacer : public TypePromotionAction {
1367     /// Helper structure to keep track of the replaced uses.
1368     struct InstructionAndIdx {
1369       /// The instruction using the instruction.
1370       Instruction *Inst;
1371       /// The index where this instruction is used for Inst.
1372       unsigned Idx;
1373       InstructionAndIdx(Instruction *Inst, unsigned Idx)
1374           : Inst(Inst), Idx(Idx) {}
1375     };
1376
1377     /// Keep track of the original uses (pair Instruction, Index).
1378     SmallVector<InstructionAndIdx, 4> OriginalUses;
1379     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1380
1381   public:
1382     /// \brief Replace all the use of \p Inst by \p New.
1383     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1384       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1385                    << "\n");
1386       // Record the original uses.
1387       for (Use &U : Inst->uses()) {
1388         Instruction *UserI = cast<Instruction>(U.getUser());
1389         OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
1390       }
1391       // Now, we can replace the uses.
1392       Inst->replaceAllUsesWith(New);
1393     }
1394
1395     /// \brief Reassign the original uses of Inst to Inst.
1396     void undo() override {
1397       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1398       for (use_iterator UseIt = OriginalUses.begin(),
1399                         EndIt = OriginalUses.end();
1400            UseIt != EndIt; ++UseIt) {
1401         UseIt->Inst->setOperand(UseIt->Idx, Inst);
1402       }
1403     }
1404   };
1405
1406   /// \brief Remove an instruction from the IR.
1407   class InstructionRemover : public TypePromotionAction {
1408     /// Original position of the instruction.
1409     InsertionHandler Inserter;
1410     /// Helper structure to hide all the link to the instruction. In other
1411     /// words, this helps to do as if the instruction was removed.
1412     OperandsHider Hider;
1413     /// Keep track of the uses replaced, if any.
1414     UsesReplacer *Replacer;
1415
1416   public:
1417     /// \brief Remove all reference of \p Inst and optinally replace all its
1418     /// uses with New.
1419     /// \pre If !Inst->use_empty(), then New != nullptr
1420     InstructionRemover(Instruction *Inst, Value *New = nullptr)
1421         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1422           Replacer(nullptr) {
1423       if (New)
1424         Replacer = new UsesReplacer(Inst, New);
1425       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1426       Inst->removeFromParent();
1427     }
1428
1429     ~InstructionRemover() { delete Replacer; }
1430
1431     /// \brief Really remove the instruction.
1432     void commit() override { delete Inst; }
1433
1434     /// \brief Resurrect the instruction and reassign it to the proper uses if
1435     /// new value was provided when build this action.
1436     void undo() override {
1437       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1438       Inserter.insert(Inst);
1439       if (Replacer)
1440         Replacer->undo();
1441       Hider.undo();
1442     }
1443   };
1444
1445 public:
1446   /// Restoration point.
1447   /// The restoration point is a pointer to an action instead of an iterator
1448   /// because the iterator may be invalidated but not the pointer.
1449   typedef const TypePromotionAction *ConstRestorationPt;
1450   /// Advocate every changes made in that transaction.
1451   void commit();
1452   /// Undo all the changes made after the given point.
1453   void rollback(ConstRestorationPt Point);
1454   /// Get the current restoration point.
1455   ConstRestorationPt getRestorationPoint() const;
1456
1457   /// \name API for IR modification with state keeping to support rollback.
1458   /// @{
1459   /// Same as Instruction::setOperand.
1460   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1461   /// Same as Instruction::eraseFromParent.
1462   void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
1463   /// Same as Value::replaceAllUsesWith.
1464   void replaceAllUsesWith(Instruction *Inst, Value *New);
1465   /// Same as Value::mutateType.
1466   void mutateType(Instruction *Inst, Type *NewTy);
1467   /// Same as IRBuilder::createTrunc.
1468   Value *createTrunc(Instruction *Opnd, Type *Ty);
1469   /// Same as IRBuilder::createSExt.
1470   Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1471   /// Same as IRBuilder::createZExt.
1472   Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
1473   /// Same as Instruction::moveBefore.
1474   void moveBefore(Instruction *Inst, Instruction *Before);
1475   /// @}
1476
1477 private:
1478   /// The ordered list of actions made so far.
1479   SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
1480   typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
1481 };
1482
1483 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1484                                           Value *NewVal) {
1485   Actions.push_back(
1486       make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
1487 }
1488
1489 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1490                                                 Value *NewVal) {
1491   Actions.push_back(
1492       make_unique<TypePromotionTransaction::InstructionRemover>(Inst, NewVal));
1493 }
1494
1495 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1496                                                   Value *New) {
1497   Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
1498 }
1499
1500 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1501   Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
1502 }
1503
1504 Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1505                                              Type *Ty) {
1506   std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
1507   Value *Val = Ptr->getBuiltValue();
1508   Actions.push_back(std::move(Ptr));
1509   return Val;
1510 }
1511
1512 Value *TypePromotionTransaction::createSExt(Instruction *Inst,
1513                                             Value *Opnd, Type *Ty) {
1514   std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
1515   Value *Val = Ptr->getBuiltValue();
1516   Actions.push_back(std::move(Ptr));
1517   return Val;
1518 }
1519
1520 Value *TypePromotionTransaction::createZExt(Instruction *Inst,
1521                                             Value *Opnd, Type *Ty) {
1522   std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
1523   Value *Val = Ptr->getBuiltValue();
1524   Actions.push_back(std::move(Ptr));
1525   return Val;
1526 }
1527
1528 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1529                                           Instruction *Before) {
1530   Actions.push_back(
1531       make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
1532 }
1533
1534 TypePromotionTransaction::ConstRestorationPt
1535 TypePromotionTransaction::getRestorationPoint() const {
1536   return !Actions.empty() ? Actions.back().get() : nullptr;
1537 }
1538
1539 void TypePromotionTransaction::commit() {
1540   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1541        ++It)
1542     (*It)->commit();
1543   Actions.clear();
1544 }
1545
1546 void TypePromotionTransaction::rollback(
1547     TypePromotionTransaction::ConstRestorationPt Point) {
1548   while (!Actions.empty() && Point != Actions.back().get()) {
1549     std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
1550     Curr->undo();
1551   }
1552 }
1553
1554 /// \brief A helper class for matching addressing modes.
1555 ///
1556 /// This encapsulates the logic for matching the target-legal addressing modes.
1557 class AddressingModeMatcher {
1558   SmallVectorImpl<Instruction*> &AddrModeInsts;
1559   const TargetLowering &TLI;
1560
1561   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1562   /// the memory instruction that we're computing this address for.
1563   Type *AccessTy;
1564   Instruction *MemoryInst;
1565
1566   /// AddrMode - This is the addressing mode that we're building up.  This is
1567   /// part of the return value of this addressing mode matching stuff.
1568   ExtAddrMode &AddrMode;
1569
1570   /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1571   const SetOfInstrs &InsertedTruncs;
1572   /// A map from the instructions to their type before promotion.
1573   InstrToOrigTy &PromotedInsts;
1574   /// The ongoing transaction where every action should be registered.
1575   TypePromotionTransaction &TPT;
1576
1577   /// IgnoreProfitability - This is set to true when we should not do
1578   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
1579   /// always returns true.
1580   bool IgnoreProfitability;
1581
1582   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1583                         const TargetLowering &T, Type *AT,
1584                         Instruction *MI, ExtAddrMode &AM,
1585                         const SetOfInstrs &InsertedTruncs,
1586                         InstrToOrigTy &PromotedInsts,
1587                         TypePromotionTransaction &TPT)
1588       : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1589         InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1590     IgnoreProfitability = false;
1591   }
1592 public:
1593
1594   /// Match - Find the maximal addressing mode that a load/store of V can fold,
1595   /// give an access type of AccessTy.  This returns a list of involved
1596   /// instructions in AddrModeInsts.
1597   /// \p InsertedTruncs The truncate instruction inserted by other
1598   /// CodeGenPrepare
1599   /// optimizations.
1600   /// \p PromotedInsts maps the instructions to their type before promotion.
1601   /// \p The ongoing transaction where every action should be registered.
1602   static ExtAddrMode Match(Value *V, Type *AccessTy,
1603                            Instruction *MemoryInst,
1604                            SmallVectorImpl<Instruction*> &AddrModeInsts,
1605                            const TargetLowering &TLI,
1606                            const SetOfInstrs &InsertedTruncs,
1607                            InstrToOrigTy &PromotedInsts,
1608                            TypePromotionTransaction &TPT) {
1609     ExtAddrMode Result;
1610
1611     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1612                                          MemoryInst, Result, InsertedTruncs,
1613                                          PromotedInsts, TPT).MatchAddr(V, 0);
1614     (void)Success; assert(Success && "Couldn't select *anything*?");
1615     return Result;
1616   }
1617 private:
1618   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1619   bool MatchAddr(Value *V, unsigned Depth);
1620   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1621                           bool *MovedAway = nullptr);
1622   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1623                                             ExtAddrMode &AMBefore,
1624                                             ExtAddrMode &AMAfter);
1625   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1626   bool IsPromotionProfitable(unsigned MatchedSize, unsigned SizeWithPromotion,
1627                              Value *PromotedOperand) const;
1628 };
1629
1630 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1631 /// Return true and update AddrMode if this addr mode is legal for the target,
1632 /// false if not.
1633 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1634                                              unsigned Depth) {
1635   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1636   // mode.  Just process that directly.
1637   if (Scale == 1)
1638     return MatchAddr(ScaleReg, Depth);
1639
1640   // If the scale is 0, it takes nothing to add this.
1641   if (Scale == 0)
1642     return true;
1643
1644   // If we already have a scale of this value, we can add to it, otherwise, we
1645   // need an available scale field.
1646   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1647     return false;
1648
1649   ExtAddrMode TestAddrMode = AddrMode;
1650
1651   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
1652   // [A+B + A*7] -> [B+A*8].
1653   TestAddrMode.Scale += Scale;
1654   TestAddrMode.ScaledReg = ScaleReg;
1655
1656   // If the new address isn't legal, bail out.
1657   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1658     return false;
1659
1660   // It was legal, so commit it.
1661   AddrMode = TestAddrMode;
1662
1663   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
1664   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
1665   // X*Scale + C*Scale to addr mode.
1666   ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
1667   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
1668       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1669     TestAddrMode.ScaledReg = AddLHS;
1670     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1671
1672     // If this addressing mode is legal, commit it and remember that we folded
1673     // this instruction.
1674     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1675       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1676       AddrMode = TestAddrMode;
1677       return true;
1678     }
1679   }
1680
1681   // Otherwise, not (x+c)*scale, just return what we have.
1682   return true;
1683 }
1684
1685 /// MightBeFoldableInst - This is a little filter, which returns true if an
1686 /// addressing computation involving I might be folded into a load/store
1687 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
1688 /// the set of instructions that MatchOperationAddr can.
1689 static bool MightBeFoldableInst(Instruction *I) {
1690   switch (I->getOpcode()) {
1691   case Instruction::BitCast:
1692   case Instruction::AddrSpaceCast:
1693     // Don't touch identity bitcasts.
1694     if (I->getType() == I->getOperand(0)->getType())
1695       return false;
1696     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1697   case Instruction::PtrToInt:
1698     // PtrToInt is always a noop, as we know that the int type is pointer sized.
1699     return true;
1700   case Instruction::IntToPtr:
1701     // We know the input is intptr_t, so this is foldable.
1702     return true;
1703   case Instruction::Add:
1704     return true;
1705   case Instruction::Mul:
1706   case Instruction::Shl:
1707     // Can only handle X*C and X << C.
1708     return isa<ConstantInt>(I->getOperand(1));
1709   case Instruction::GetElementPtr:
1710     return true;
1711   default:
1712     return false;
1713   }
1714 }
1715
1716 /// \brief Hepler class to perform type promotion.
1717 class TypePromotionHelper {
1718   /// \brief Utility function to check whether or not a sign extension of
1719   /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1720   /// using the operands of \p Inst or promoting \p Inst.
1721   /// In other words, check if:
1722   /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1723   /// #1 Promotion applies:
1724   /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1725   /// #2 Operand reuses:
1726   /// sext opnd1 to ConsideredSExtType.
1727   /// \p PromotedInsts maps the instructions to their type before promotion.
1728   static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1729                             const InstrToOrigTy &PromotedInsts);
1730
1731   /// \brief Utility function to determine if \p OpIdx should be promoted when
1732   /// promoting \p Inst.
1733   static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1734     if (isa<SelectInst>(Inst) && OpIdx == 0)
1735       return false;
1736     return true;
1737   }
1738
1739   /// \brief Utility function to promote the operand of \p SExt when this
1740   /// operand is a promotable trunc or sext or zext.
1741   /// \p PromotedInsts maps the instructions to their type before promotion.
1742   /// \p CreatedInsts[out] contains how many non-free instructions have been
1743   /// created to promote the operand of SExt.
1744   /// Should never be called directly.
1745   /// \return The promoted value which is used instead of SExt.
1746   static Value *promoteOperandForTruncAndAnyExt(Instruction *SExt,
1747                                                 TypePromotionTransaction &TPT,
1748                                                 InstrToOrigTy &PromotedInsts,
1749                                                 unsigned &CreatedInsts);
1750
1751   /// \brief Utility function to promote the operand of \p SExt when this
1752   /// operand is promotable and is not a supported trunc or sext.
1753   /// \p PromotedInsts maps the instructions to their type before promotion.
1754   /// \p CreatedInsts[out] contains how many non-free instructions have been
1755   /// created to promote the operand of SExt.
1756   /// Should never be called directly.
1757   /// \return The promoted value which is used instead of SExt.
1758   static Value *promoteOperandForOther(Instruction *SExt,
1759                                        TypePromotionTransaction &TPT,
1760                                        InstrToOrigTy &PromotedInsts,
1761                                        unsigned &CreatedInsts);
1762
1763 public:
1764   /// Type for the utility function that promotes the operand of SExt.
1765   typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1766                            InstrToOrigTy &PromotedInsts,
1767                            unsigned &CreatedInsts);
1768   /// \brief Given a sign extend instruction \p SExt, return the approriate
1769   /// action to promote the operand of \p SExt instead of using SExt.
1770   /// \return NULL if no promotable action is possible with the current
1771   /// sign extension.
1772   /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1773   /// the others CodeGenPrepare optimizations. This information is important
1774   /// because we do not want to promote these instructions as CodeGenPrepare
1775   /// will reinsert them later. Thus creating an infinite loop: create/remove.
1776   /// \p PromotedInsts maps the instructions to their type before promotion.
1777   static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1778                           const TargetLowering &TLI,
1779                           const InstrToOrigTy &PromotedInsts);
1780 };
1781
1782 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1783                                         Type *ConsideredSExtType,
1784                                         const InstrToOrigTy &PromotedInsts) {
1785   // We can always get through sext or zext.
1786   if (isa<SExtInst>(Inst) || isa<ZExtInst>(Inst))
1787     return true;
1788
1789   // We can get through binary operator, if it is legal. In other words, the
1790   // binary operator must have a nuw or nsw flag.
1791   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1792   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1793       (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1794     return true;
1795
1796   // Check if we can do the following simplification.
1797   // sext(trunc(sext)) --> sext
1798   if (!isa<TruncInst>(Inst))
1799     return false;
1800
1801   Value *OpndVal = Inst->getOperand(0);
1802   // Check if we can use this operand in the sext.
1803   // If the type is larger than the result type of the sign extension,
1804   // we cannot.
1805   if (OpndVal->getType()->getIntegerBitWidth() >
1806       ConsideredSExtType->getIntegerBitWidth())
1807     return false;
1808
1809   // If the operand of the truncate is not an instruction, we will not have
1810   // any information on the dropped bits.
1811   // (Actually we could for constant but it is not worth the extra logic).
1812   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1813   if (!Opnd)
1814     return false;
1815
1816   // Check if the source of the type is narrow enough.
1817   // I.e., check that trunc just drops sign extended bits.
1818   // #1 get the type of the operand.
1819   const Type *OpndType;
1820   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1821   if (It != PromotedInsts.end())
1822     OpndType = It->second;
1823   else if (isa<SExtInst>(Opnd))
1824     OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1825   else
1826     return false;
1827
1828   // #2 check that the truncate just drop sign extended bits.
1829   if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1830     return true;
1831
1832   return false;
1833 }
1834
1835 TypePromotionHelper::Action TypePromotionHelper::getAction(
1836     Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1837     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1838   Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1839   Type *SExtTy = SExt->getType();
1840   // If the operand of the sign extension is not an instruction, we cannot
1841   // get through.
1842   // If it, check we can get through.
1843   if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1844     return nullptr;
1845
1846   // Do not promote if the operand has been added by codegenprepare.
1847   // Otherwise, it means we are undoing an optimization that is likely to be
1848   // redone, thus causing potential infinite loop.
1849   if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1850     return nullptr;
1851
1852   // SExt or Trunc instructions.
1853   // Return the related handler.
1854   if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd) ||
1855       isa<ZExtInst>(SExtOpnd))
1856     return promoteOperandForTruncAndAnyExt;
1857
1858   // Regular instruction.
1859   // Abort early if we will have to insert non-free instructions.
1860   if (!SExtOpnd->hasOneUse() &&
1861       !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1862     return nullptr;
1863   return promoteOperandForOther;
1864 }
1865
1866 Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
1867     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1868     InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1869   // By construction, the operand of SExt is an instruction. Otherwise we cannot
1870   // get through it and this method should not be called.
1871   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1872   Value *ExtVal = SExt;
1873   if (isa<ZExtInst>(SExtOpnd)) {
1874     // Replace sext(zext(opnd))
1875     // => zext(opnd).
1876     Value *ZExt =
1877         TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
1878     TPT.replaceAllUsesWith(SExt, ZExt);
1879     TPT.eraseInstruction(SExt);
1880     ExtVal = ZExt;
1881   } else {
1882     // Replace sext(trunc(opnd)) or sext(sext(opnd))
1883     // => sext(opnd).
1884     TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1885   }
1886   CreatedInsts = 0;
1887
1888   // Remove dead code.
1889   if (SExtOpnd->use_empty())
1890     TPT.eraseInstruction(SExtOpnd);
1891
1892   // Check if the extension is still needed.
1893   Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
1894   if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType())
1895     return ExtVal;
1896
1897   // At this point we have: ext ty opnd to ty.
1898   // Reassign the uses of ExtInst to the opnd and remove ExtInst.
1899   Value *NextVal = ExtInst->getOperand(0);
1900   TPT.eraseInstruction(ExtInst, NextVal);
1901   return NextVal;
1902 }
1903
1904 Value *
1905 TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1906                                             TypePromotionTransaction &TPT,
1907                                             InstrToOrigTy &PromotedInsts,
1908                                             unsigned &CreatedInsts) {
1909   // By construction, the operand of SExt is an instruction. Otherwise we cannot
1910   // get through it and this method should not be called.
1911   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1912   CreatedInsts = 0;
1913   if (!SExtOpnd->hasOneUse()) {
1914     // SExtOpnd will be promoted.
1915     // All its uses, but SExt, will need to use a truncated value of the
1916     // promoted version.
1917     // Create the truncate now.
1918     Value *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1919     if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
1920       ITrunc->removeFromParent();
1921       // Insert it just after the definition.
1922       ITrunc->insertAfter(SExtOpnd);
1923     }
1924
1925     TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1926     // Restore the operand of SExt (which has been replace by the previous call
1927     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1928     TPT.setOperand(SExt, 0, SExtOpnd);
1929   }
1930
1931   // Get through the Instruction:
1932   // 1. Update its type.
1933   // 2. Replace the uses of SExt by Inst.
1934   // 3. Sign extend each operand that needs to be sign extended.
1935
1936   // Remember the original type of the instruction before promotion.
1937   // This is useful to know that the high bits are sign extended bits.
1938   PromotedInsts.insert(
1939       std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1940   // Step #1.
1941   TPT.mutateType(SExtOpnd, SExt->getType());
1942   // Step #2.
1943   TPT.replaceAllUsesWith(SExt, SExtOpnd);
1944   // Step #3.
1945   Instruction *SExtForOpnd = SExt;
1946
1947   DEBUG(dbgs() << "Propagate SExt to operands\n");
1948   for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1949        ++OpIdx) {
1950     DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1951     if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1952         !shouldSExtOperand(SExtOpnd, OpIdx)) {
1953       DEBUG(dbgs() << "No need to propagate\n");
1954       continue;
1955     }
1956     // Check if we can statically sign extend the operand.
1957     Value *Opnd = SExtOpnd->getOperand(OpIdx);
1958     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1959       DEBUG(dbgs() << "Statically sign extend\n");
1960       TPT.setOperand(
1961           SExtOpnd, OpIdx,
1962           ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1963       continue;
1964     }
1965     // UndefValue are typed, so we have to statically sign extend them.
1966     if (isa<UndefValue>(Opnd)) {
1967       DEBUG(dbgs() << "Statically sign extend\n");
1968       TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1969       continue;
1970     }
1971
1972     // Otherwise we have to explicity sign extend the operand.
1973     // Check if SExt was reused to sign extend an operand.
1974     if (!SExtForOpnd) {
1975       // If yes, create a new one.
1976       DEBUG(dbgs() << "More operands to sext\n");
1977       SExtForOpnd =
1978         cast<Instruction>(TPT.createSExt(SExt, Opnd, SExt->getType()));
1979       ++CreatedInsts;
1980     }
1981
1982     TPT.setOperand(SExtForOpnd, 0, Opnd);
1983
1984     // Move the sign extension before the insertion point.
1985     TPT.moveBefore(SExtForOpnd, SExtOpnd);
1986     TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1987     // If more sext are required, new instructions will have to be created.
1988     SExtForOpnd = nullptr;
1989   }
1990   if (SExtForOpnd == SExt) {
1991     DEBUG(dbgs() << "Sign extension is useless now\n");
1992     TPT.eraseInstruction(SExt);
1993   }
1994   return SExtOpnd;
1995 }
1996
1997 /// IsPromotionProfitable - Check whether or not promoting an instruction
1998 /// to a wider type was profitable.
1999 /// \p MatchedSize gives the number of instructions that have been matched
2000 /// in the addressing mode after the promotion was applied.
2001 /// \p SizeWithPromotion gives the number of created instructions for
2002 /// the promotion plus the number of instructions that have been
2003 /// matched in the addressing mode before the promotion.
2004 /// \p PromotedOperand is the value that has been promoted.
2005 /// \return True if the promotion is profitable, false otherwise.
2006 bool
2007 AddressingModeMatcher::IsPromotionProfitable(unsigned MatchedSize,
2008                                              unsigned SizeWithPromotion,
2009                                              Value *PromotedOperand) const {
2010   // We folded less instructions than what we created to promote the operand.
2011   // This is not profitable.
2012   if (MatchedSize < SizeWithPromotion)
2013     return false;
2014   if (MatchedSize > SizeWithPromotion)
2015     return true;
2016   // The promotion is neutral but it may help folding the sign extension in
2017   // loads for instance.
2018   // Check that we did not create an illegal instruction.
2019   Instruction *PromotedInst = dyn_cast<Instruction>(PromotedOperand);
2020   if (!PromotedInst)
2021     return false;
2022   int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
2023   // If the ISDOpcode is undefined, it was undefined before the promotion.
2024   if (!ISDOpcode)
2025     return true;
2026   // Otherwise, check if the promoted instruction is legal or not.
2027   return TLI.isOperationLegalOrCustom(ISDOpcode,
2028                                       EVT::getEVT(PromotedInst->getType()));
2029 }
2030
2031 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
2032 /// fold the operation into the addressing mode.  If so, update the addressing
2033 /// mode and return true, otherwise return false without modifying AddrMode.
2034 /// If \p MovedAway is not NULL, it contains the information of whether or
2035 /// not AddrInst has to be folded into the addressing mode on success.
2036 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
2037 /// because it has been moved away.
2038 /// Thus AddrInst must not be added in the matched instructions.
2039 /// This state can happen when AddrInst is a sext, since it may be moved away.
2040 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
2041 /// not be referenced anymore.
2042 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
2043                                                unsigned Depth,
2044                                                bool *MovedAway) {
2045   // Avoid exponential behavior on extremely deep expression trees.
2046   if (Depth >= 5) return false;
2047
2048   // By default, all matched instructions stay in place.
2049   if (MovedAway)
2050     *MovedAway = false;
2051
2052   switch (Opcode) {
2053   case Instruction::PtrToInt:
2054     // PtrToInt is always a noop, as we know that the int type is pointer sized.
2055     return MatchAddr(AddrInst->getOperand(0), Depth);
2056   case Instruction::IntToPtr:
2057     // This inttoptr is a no-op if the integer type is pointer sized.
2058     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
2059         TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
2060       return MatchAddr(AddrInst->getOperand(0), Depth);
2061     return false;
2062   case Instruction::BitCast:
2063   case Instruction::AddrSpaceCast:
2064     // BitCast is always a noop, and we can handle it as long as it is
2065     // int->int or pointer->pointer (we don't want int<->fp or something).
2066     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
2067          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
2068         // Don't touch identity bitcasts.  These were probably put here by LSR,
2069         // and we don't want to mess around with them.  Assume it knows what it
2070         // is doing.
2071         AddrInst->getOperand(0)->getType() != AddrInst->getType())
2072       return MatchAddr(AddrInst->getOperand(0), Depth);
2073     return false;
2074   case Instruction::Add: {
2075     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
2076     ExtAddrMode BackupAddrMode = AddrMode;
2077     unsigned OldSize = AddrModeInsts.size();
2078     // Start a transaction at this point.
2079     // The LHS may match but not the RHS.
2080     // Therefore, we need a higher level restoration point to undo partially
2081     // matched operation.
2082     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2083         TPT.getRestorationPoint();
2084
2085     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
2086         MatchAddr(AddrInst->getOperand(0), Depth+1))
2087       return true;
2088
2089     // Restore the old addr mode info.
2090     AddrMode = BackupAddrMode;
2091     AddrModeInsts.resize(OldSize);
2092     TPT.rollback(LastKnownGood);
2093
2094     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
2095     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
2096         MatchAddr(AddrInst->getOperand(1), Depth+1))
2097       return true;
2098
2099     // Otherwise we definitely can't merge the ADD in.
2100     AddrMode = BackupAddrMode;
2101     AddrModeInsts.resize(OldSize);
2102     TPT.rollback(LastKnownGood);
2103     break;
2104   }
2105   //case Instruction::Or:
2106   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
2107   //break;
2108   case Instruction::Mul:
2109   case Instruction::Shl: {
2110     // Can only handle X*C and X << C.
2111     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
2112     if (!RHS)
2113       return false;
2114     int64_t Scale = RHS->getSExtValue();
2115     if (Opcode == Instruction::Shl)
2116       Scale = 1LL << Scale;
2117
2118     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
2119   }
2120   case Instruction::GetElementPtr: {
2121     // Scan the GEP.  We check it if it contains constant offsets and at most
2122     // one variable offset.
2123     int VariableOperand = -1;
2124     unsigned VariableScale = 0;
2125
2126     int64_t ConstantOffset = 0;
2127     const DataLayout *TD = TLI.getDataLayout();
2128     gep_type_iterator GTI = gep_type_begin(AddrInst);
2129     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
2130       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
2131         const StructLayout *SL = TD->getStructLayout(STy);
2132         unsigned Idx =
2133           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
2134         ConstantOffset += SL->getElementOffset(Idx);
2135       } else {
2136         uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
2137         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
2138           ConstantOffset += CI->getSExtValue()*TypeSize;
2139         } else if (TypeSize) {  // Scales of zero don't do anything.
2140           // We only allow one variable index at the moment.
2141           if (VariableOperand != -1)
2142             return false;
2143
2144           // Remember the variable index.
2145           VariableOperand = i;
2146           VariableScale = TypeSize;
2147         }
2148       }
2149     }
2150
2151     // A common case is for the GEP to only do a constant offset.  In this case,
2152     // just add it to the disp field and check validity.
2153     if (VariableOperand == -1) {
2154       AddrMode.BaseOffs += ConstantOffset;
2155       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
2156         // Check to see if we can fold the base pointer in too.
2157         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
2158           return true;
2159       }
2160       AddrMode.BaseOffs -= ConstantOffset;
2161       return false;
2162     }
2163
2164     // Save the valid addressing mode in case we can't match.
2165     ExtAddrMode BackupAddrMode = AddrMode;
2166     unsigned OldSize = AddrModeInsts.size();
2167
2168     // See if the scale and offset amount is valid for this target.
2169     AddrMode.BaseOffs += ConstantOffset;
2170
2171     // Match the base operand of the GEP.
2172     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
2173       // If it couldn't be matched, just stuff the value in a register.
2174       if (AddrMode.HasBaseReg) {
2175         AddrMode = BackupAddrMode;
2176         AddrModeInsts.resize(OldSize);
2177         return false;
2178       }
2179       AddrMode.HasBaseReg = true;
2180       AddrMode.BaseReg = AddrInst->getOperand(0);
2181     }
2182
2183     // Match the remaining variable portion of the GEP.
2184     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
2185                           Depth)) {
2186       // If it couldn't be matched, try stuffing the base into a register
2187       // instead of matching it, and retrying the match of the scale.
2188       AddrMode = BackupAddrMode;
2189       AddrModeInsts.resize(OldSize);
2190       if (AddrMode.HasBaseReg)
2191         return false;
2192       AddrMode.HasBaseReg = true;
2193       AddrMode.BaseReg = AddrInst->getOperand(0);
2194       AddrMode.BaseOffs += ConstantOffset;
2195       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
2196                             VariableScale, Depth)) {
2197         // If even that didn't work, bail.
2198         AddrMode = BackupAddrMode;
2199         AddrModeInsts.resize(OldSize);
2200         return false;
2201       }
2202     }
2203
2204     return true;
2205   }
2206   case Instruction::SExt: {
2207     Instruction *SExt = dyn_cast<Instruction>(AddrInst);
2208     if (!SExt)
2209       return false;
2210
2211     // Try to move this sext out of the way of the addressing mode.
2212     // Ask for a method for doing so.
2213     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
2214         SExt, InsertedTruncs, TLI, PromotedInsts);
2215     if (!TPH)
2216       return false;
2217
2218     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2219         TPT.getRestorationPoint();
2220     unsigned CreatedInsts = 0;
2221     Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
2222     // SExt has been moved away.
2223     // Thus either it will be rematched later in the recursive calls or it is
2224     // gone. Anyway, we must not fold it into the addressing mode at this point.
2225     // E.g.,
2226     // op = add opnd, 1
2227     // idx = sext op
2228     // addr = gep base, idx
2229     // is now:
2230     // promotedOpnd = sext opnd           <- no match here
2231     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
2232     // addr = gep base, op                <- match
2233     if (MovedAway)
2234       *MovedAway = true;
2235
2236     assert(PromotedOperand &&
2237            "TypePromotionHelper should have filtered out those cases");
2238
2239     ExtAddrMode BackupAddrMode = AddrMode;
2240     unsigned OldSize = AddrModeInsts.size();
2241
2242     if (!MatchAddr(PromotedOperand, Depth) ||
2243         !IsPromotionProfitable(AddrModeInsts.size(), OldSize + CreatedInsts,
2244                                PromotedOperand)) {
2245       AddrMode = BackupAddrMode;
2246       AddrModeInsts.resize(OldSize);
2247       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
2248       TPT.rollback(LastKnownGood);
2249       return false;
2250     }
2251     return true;
2252   }
2253   }
2254   return false;
2255 }
2256
2257 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
2258 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
2259 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
2260 /// or intptr_t for the target.
2261 ///
2262 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
2263   // Start a transaction at this point that we will rollback if the matching
2264   // fails.
2265   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2266       TPT.getRestorationPoint();
2267   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
2268     // Fold in immediates if legal for the target.
2269     AddrMode.BaseOffs += CI->getSExtValue();
2270     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2271       return true;
2272     AddrMode.BaseOffs -= CI->getSExtValue();
2273   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
2274     // If this is a global variable, try to fold it into the addressing mode.
2275     if (!AddrMode.BaseGV) {
2276       AddrMode.BaseGV = GV;
2277       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2278         return true;
2279       AddrMode.BaseGV = nullptr;
2280     }
2281   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
2282     ExtAddrMode BackupAddrMode = AddrMode;
2283     unsigned OldSize = AddrModeInsts.size();
2284
2285     // Check to see if it is possible to fold this operation.
2286     bool MovedAway = false;
2287     if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
2288       // This instruction may have been move away. If so, there is nothing
2289       // to check here.
2290       if (MovedAway)
2291         return true;
2292       // Okay, it's possible to fold this.  Check to see if it is actually
2293       // *profitable* to do so.  We use a simple cost model to avoid increasing
2294       // register pressure too much.
2295       if (I->hasOneUse() ||
2296           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
2297         AddrModeInsts.push_back(I);
2298         return true;
2299       }
2300
2301       // It isn't profitable to do this, roll back.
2302       //cerr << "NOT FOLDING: " << *I;
2303       AddrMode = BackupAddrMode;
2304       AddrModeInsts.resize(OldSize);
2305       TPT.rollback(LastKnownGood);
2306     }
2307   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2308     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2309       return true;
2310     TPT.rollback(LastKnownGood);
2311   } else if (isa<ConstantPointerNull>(Addr)) {
2312     // Null pointer gets folded without affecting the addressing mode.
2313     return true;
2314   }
2315
2316   // Worse case, the target should support [reg] addressing modes. :)
2317   if (!AddrMode.HasBaseReg) {
2318     AddrMode.HasBaseReg = true;
2319     AddrMode.BaseReg = Addr;
2320     // Still check for legality in case the target supports [imm] but not [i+r].
2321     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2322       return true;
2323     AddrMode.HasBaseReg = false;
2324     AddrMode.BaseReg = nullptr;
2325   }
2326
2327   // If the base register is already taken, see if we can do [r+r].
2328   if (AddrMode.Scale == 0) {
2329     AddrMode.Scale = 1;
2330     AddrMode.ScaledReg = Addr;
2331     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2332       return true;
2333     AddrMode.Scale = 0;
2334     AddrMode.ScaledReg = nullptr;
2335   }
2336   // Couldn't match.
2337   TPT.rollback(LastKnownGood);
2338   return false;
2339 }
2340
2341 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2342 /// inline asm call are due to memory operands.  If so, return true, otherwise
2343 /// return false.
2344 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2345                                     const TargetLowering &TLI) {
2346   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2347   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2348     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2349
2350     // Compute the constraint code and ConstraintType to use.
2351     TLI.ComputeConstraintToUse(OpInfo, SDValue());
2352
2353     // If this asm operand is our Value*, and if it isn't an indirect memory
2354     // operand, we can't fold it!
2355     if (OpInfo.CallOperandVal == OpVal &&
2356         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2357          !OpInfo.isIndirect))
2358       return false;
2359   }
2360
2361   return true;
2362 }
2363
2364 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2365 /// memory use.  If we find an obviously non-foldable instruction, return true.
2366 /// Add the ultimately found memory instructions to MemoryUses.
2367 static bool FindAllMemoryUses(Instruction *I,
2368                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2369                               SmallPtrSetImpl<Instruction*> &ConsideredInsts,
2370                               const TargetLowering &TLI) {
2371   // If we already considered this instruction, we're done.
2372   if (!ConsideredInsts.insert(I))
2373     return false;
2374
2375   // If this is an obviously unfoldable instruction, bail out.
2376   if (!MightBeFoldableInst(I))
2377     return true;
2378
2379   // Loop over all the uses, recursively processing them.
2380   for (Use &U : I->uses()) {
2381     Instruction *UserI = cast<Instruction>(U.getUser());
2382
2383     if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
2384       MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
2385       continue;
2386     }
2387
2388     if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
2389       unsigned opNo = U.getOperandNo();
2390       if (opNo == 0) return true; // Storing addr, not into addr.
2391       MemoryUses.push_back(std::make_pair(SI, opNo));
2392       continue;
2393     }
2394
2395     if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
2396       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2397       if (!IA) return true;
2398
2399       // If this is a memory operand, we're cool, otherwise bail out.
2400       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2401         return true;
2402       continue;
2403     }
2404
2405     if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI))
2406       return true;
2407   }
2408
2409   return false;
2410 }
2411
2412 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2413 /// the use site that we're folding it into.  If so, there is no cost to
2414 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
2415 /// that we know are live at the instruction already.
2416 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2417                                                    Value *KnownLive2) {
2418   // If Val is either of the known-live values, we know it is live!
2419   if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
2420     return true;
2421
2422   // All values other than instructions and arguments (e.g. constants) are live.
2423   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2424
2425   // If Val is a constant sized alloca in the entry block, it is live, this is
2426   // true because it is just a reference to the stack/frame pointer, which is
2427   // live for the whole function.
2428   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2429     if (AI->isStaticAlloca())
2430       return true;
2431
2432   // Check to see if this value is already used in the memory instruction's
2433   // block.  If so, it's already live into the block at the very least, so we
2434   // can reasonably fold it.
2435   return Val->isUsedInBasicBlock(MemoryInst->getParent());
2436 }
2437
2438 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2439 /// mode of the machine to fold the specified instruction into a load or store
2440 /// that ultimately uses it.  However, the specified instruction has multiple
2441 /// uses.  Given this, it may actually increase register pressure to fold it
2442 /// into the load.  For example, consider this code:
2443 ///
2444 ///     X = ...
2445 ///     Y = X+1
2446 ///     use(Y)   -> nonload/store
2447 ///     Z = Y+1
2448 ///     load Z
2449 ///
2450 /// In this case, Y has multiple uses, and can be folded into the load of Z
2451 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
2452 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
2453 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
2454 /// number of computations either.
2455 ///
2456 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
2457 /// X was live across 'load Z' for other reasons, we actually *would* want to
2458 /// fold the addressing mode in the Z case.  This would make Y die earlier.
2459 bool AddressingModeMatcher::
2460 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2461                                      ExtAddrMode &AMAfter) {
2462   if (IgnoreProfitability) return true;
2463
2464   // AMBefore is the addressing mode before this instruction was folded into it,
2465   // and AMAfter is the addressing mode after the instruction was folded.  Get
2466   // the set of registers referenced by AMAfter and subtract out those
2467   // referenced by AMBefore: this is the set of values which folding in this
2468   // address extends the lifetime of.
2469   //
2470   // Note that there are only two potential values being referenced here,
2471   // BaseReg and ScaleReg (global addresses are always available, as are any
2472   // folded immediates).
2473   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2474
2475   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2476   // lifetime wasn't extended by adding this instruction.
2477   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2478     BaseReg = nullptr;
2479   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2480     ScaledReg = nullptr;
2481
2482   // If folding this instruction (and it's subexprs) didn't extend any live
2483   // ranges, we're ok with it.
2484   if (!BaseReg && !ScaledReg)
2485     return true;
2486
2487   // If all uses of this instruction are ultimately load/store/inlineasm's,
2488   // check to see if their addressing modes will include this instruction.  If
2489   // so, we can fold it into all uses, so it doesn't matter if it has multiple
2490   // uses.
2491   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2492   SmallPtrSet<Instruction*, 16> ConsideredInsts;
2493   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2494     return false;  // Has a non-memory, non-foldable use!
2495
2496   // Now that we know that all uses of this instruction are part of a chain of
2497   // computation involving only operations that could theoretically be folded
2498   // into a memory use, loop over each of these uses and see if they could
2499   // *actually* fold the instruction.
2500   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2501   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2502     Instruction *User = MemoryUses[i].first;
2503     unsigned OpNo = MemoryUses[i].second;
2504
2505     // Get the access type of this use.  If the use isn't a pointer, we don't
2506     // know what it accesses.
2507     Value *Address = User->getOperand(OpNo);
2508     if (!Address->getType()->isPointerTy())
2509       return false;
2510     Type *AddressAccessTy = Address->getType()->getPointerElementType();
2511
2512     // Do a match against the root of this address, ignoring profitability. This
2513     // will tell us if the addressing mode for the memory operation will
2514     // *actually* cover the shared instruction.
2515     ExtAddrMode Result;
2516     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2517         TPT.getRestorationPoint();
2518     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2519                                   MemoryInst, Result, InsertedTruncs,
2520                                   PromotedInsts, TPT);
2521     Matcher.IgnoreProfitability = true;
2522     bool Success = Matcher.MatchAddr(Address, 0);
2523     (void)Success; assert(Success && "Couldn't select *anything*?");
2524
2525     // The match was to check the profitability, the changes made are not
2526     // part of the original matcher. Therefore, they should be dropped
2527     // otherwise the original matcher will not present the right state.
2528     TPT.rollback(LastKnownGood);
2529
2530     // If the match didn't cover I, then it won't be shared by it.
2531     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2532                   I) == MatchedAddrModeInsts.end())
2533       return false;
2534
2535     MatchedAddrModeInsts.clear();
2536   }
2537
2538   return true;
2539 }
2540
2541 } // end anonymous namespace
2542
2543 /// IsNonLocalValue - Return true if the specified values are defined in a
2544 /// different basic block than BB.
2545 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2546   if (Instruction *I = dyn_cast<Instruction>(V))
2547     return I->getParent() != BB;
2548   return false;
2549 }
2550
2551 /// OptimizeMemoryInst - Load and Store Instructions often have
2552 /// addressing modes that can do significant amounts of computation.  As such,
2553 /// instruction selection will try to get the load or store to do as much
2554 /// computation as possible for the program.  The problem is that isel can only
2555 /// see within a single block.  As such, we sink as much legal addressing mode
2556 /// stuff into the block as possible.
2557 ///
2558 /// This method is used to optimize both load/store and inline asms with memory
2559 /// operands.
2560 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2561                                         Type *AccessTy) {
2562   Value *Repl = Addr;
2563
2564   // Try to collapse single-value PHI nodes.  This is necessary to undo
2565   // unprofitable PRE transformations.
2566   SmallVector<Value*, 8> worklist;
2567   SmallPtrSet<Value*, 16> Visited;
2568   worklist.push_back(Addr);
2569
2570   // Use a worklist to iteratively look through PHI nodes, and ensure that
2571   // the addressing mode obtained from the non-PHI roots of the graph
2572   // are equivalent.
2573   Value *Consensus = nullptr;
2574   unsigned NumUsesConsensus = 0;
2575   bool IsNumUsesConsensusValid = false;
2576   SmallVector<Instruction*, 16> AddrModeInsts;
2577   ExtAddrMode AddrMode;
2578   TypePromotionTransaction TPT;
2579   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2580       TPT.getRestorationPoint();
2581   while (!worklist.empty()) {
2582     Value *V = worklist.back();
2583     worklist.pop_back();
2584
2585     // Break use-def graph loops.
2586     if (!Visited.insert(V)) {
2587       Consensus = nullptr;
2588       break;
2589     }
2590
2591     // For a PHI node, push all of its incoming values.
2592     if (PHINode *P = dyn_cast<PHINode>(V)) {
2593       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2594         worklist.push_back(P->getIncomingValue(i));
2595       continue;
2596     }
2597
2598     // For non-PHIs, determine the addressing mode being computed.
2599     SmallVector<Instruction*, 16> NewAddrModeInsts;
2600     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2601         V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2602         PromotedInsts, TPT);
2603
2604     // This check is broken into two cases with very similar code to avoid using
2605     // getNumUses() as much as possible. Some values have a lot of uses, so
2606     // calling getNumUses() unconditionally caused a significant compile-time
2607     // regression.
2608     if (!Consensus) {
2609       Consensus = V;
2610       AddrMode = NewAddrMode;
2611       AddrModeInsts = NewAddrModeInsts;
2612       continue;
2613     } else if (NewAddrMode == AddrMode) {
2614       if (!IsNumUsesConsensusValid) {
2615         NumUsesConsensus = Consensus->getNumUses();
2616         IsNumUsesConsensusValid = true;
2617       }
2618
2619       // Ensure that the obtained addressing mode is equivalent to that obtained
2620       // for all other roots of the PHI traversal.  Also, when choosing one
2621       // such root as representative, select the one with the most uses in order
2622       // to keep the cost modeling heuristics in AddressingModeMatcher
2623       // applicable.
2624       unsigned NumUses = V->getNumUses();
2625       if (NumUses > NumUsesConsensus) {
2626         Consensus = V;
2627         NumUsesConsensus = NumUses;
2628         AddrModeInsts = NewAddrModeInsts;
2629       }
2630       continue;
2631     }
2632
2633     Consensus = nullptr;
2634     break;
2635   }
2636
2637   // If the addressing mode couldn't be determined, or if multiple different
2638   // ones were determined, bail out now.
2639   if (!Consensus) {
2640     TPT.rollback(LastKnownGood);
2641     return false;
2642   }
2643   TPT.commit();
2644
2645   // Check to see if any of the instructions supersumed by this addr mode are
2646   // non-local to I's BB.
2647   bool AnyNonLocal = false;
2648   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2649     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2650       AnyNonLocal = true;
2651       break;
2652     }
2653   }
2654
2655   // If all the instructions matched are already in this BB, don't do anything.
2656   if (!AnyNonLocal) {
2657     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
2658     return false;
2659   }
2660
2661   // Insert this computation right after this user.  Since our caller is
2662   // scanning from the top of the BB to the bottom, reuse of the expr are
2663   // guaranteed to happen later.
2664   IRBuilder<> Builder(MemoryInst);
2665
2666   // Now that we determined the addressing expression we want to use and know
2667   // that we have to sink it into this block.  Check to see if we have already
2668   // done this for some other load/store instr in this block.  If so, reuse the
2669   // computation.
2670   Value *&SunkAddr = SunkAddrs[Addr];
2671   if (SunkAddr) {
2672     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2673                  << *MemoryInst << "\n");
2674     if (SunkAddr->getType() != Addr->getType())
2675       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2676   } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
2677                TM && TM->getSubtarget<TargetSubtargetInfo>().useAA())) {
2678     // By default, we use the GEP-based method when AA is used later. This
2679     // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
2680     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2681                  << *MemoryInst << "\n");
2682     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2683     Value *ResultPtr = nullptr, *ResultIndex = nullptr;
2684
2685     // First, find the pointer.
2686     if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
2687       ResultPtr = AddrMode.BaseReg;
2688       AddrMode.BaseReg = nullptr;
2689     }
2690
2691     if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
2692       // We can't add more than one pointer together, nor can we scale a
2693       // pointer (both of which seem meaningless).
2694       if (ResultPtr || AddrMode.Scale != 1)
2695         return false;
2696
2697       ResultPtr = AddrMode.ScaledReg;
2698       AddrMode.Scale = 0;
2699     }
2700
2701     if (AddrMode.BaseGV) {
2702       if (ResultPtr)
2703         return false;
2704
2705       ResultPtr = AddrMode.BaseGV;
2706     }
2707
2708     // If the real base value actually came from an inttoptr, then the matcher
2709     // will look through it and provide only the integer value. In that case,
2710     // use it here.
2711     if (!ResultPtr && AddrMode.BaseReg) {
2712       ResultPtr =
2713         Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
2714       AddrMode.BaseReg = nullptr;
2715     } else if (!ResultPtr && AddrMode.Scale == 1) {
2716       ResultPtr =
2717         Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
2718       AddrMode.Scale = 0;
2719     }
2720
2721     if (!ResultPtr &&
2722         !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
2723       SunkAddr = Constant::getNullValue(Addr->getType());
2724     } else if (!ResultPtr) {
2725       return false;
2726     } else {
2727       Type *I8PtrTy =
2728         Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
2729
2730       // Start with the base register. Do this first so that subsequent address
2731       // matching finds it last, which will prevent it from trying to match it
2732       // as the scaled value in case it happens to be a mul. That would be
2733       // problematic if we've sunk a different mul for the scale, because then
2734       // we'd end up sinking both muls.
2735       if (AddrMode.BaseReg) {
2736         Value *V = AddrMode.BaseReg;
2737         if (V->getType() != IntPtrTy)
2738           V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2739
2740         ResultIndex = V;
2741       }
2742
2743       // Add the scale value.
2744       if (AddrMode.Scale) {
2745         Value *V = AddrMode.ScaledReg;
2746         if (V->getType() == IntPtrTy) {
2747           // done.
2748         } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2749                    cast<IntegerType>(V->getType())->getBitWidth()) {
2750           V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2751         } else {
2752           // It is only safe to sign extend the BaseReg if we know that the math
2753           // required to create it did not overflow before we extend it. Since
2754           // the original IR value was tossed in favor of a constant back when
2755           // the AddrMode was created we need to bail out gracefully if widths
2756           // do not match instead of extending it.
2757           Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
2758           if (I && (ResultIndex != AddrMode.BaseReg))
2759             I->eraseFromParent();
2760           return false;
2761         }
2762
2763         if (AddrMode.Scale != 1)
2764           V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2765                                 "sunkaddr");
2766         if (ResultIndex)
2767           ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
2768         else
2769           ResultIndex = V;
2770       }
2771
2772       // Add in the Base Offset if present.
2773       if (AddrMode.BaseOffs) {
2774         Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2775         if (ResultIndex) {
2776           // We need to add this separately from the scale above to help with
2777           // SDAG consecutive load/store merging.
2778           if (ResultPtr->getType() != I8PtrTy)
2779             ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2780           ResultPtr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2781         }
2782
2783         ResultIndex = V;
2784       }
2785
2786       if (!ResultIndex) {
2787         SunkAddr = ResultPtr;
2788       } else {
2789         if (ResultPtr->getType() != I8PtrTy)
2790           ResultPtr = Builder.CreateBitCast(ResultPtr, I8PtrTy);
2791         SunkAddr = Builder.CreateGEP(ResultPtr, ResultIndex, "sunkaddr");
2792       }
2793
2794       if (SunkAddr->getType() != Addr->getType())
2795         SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2796     }
2797   } else {
2798     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2799                  << *MemoryInst << "\n");
2800     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2801     Value *Result = nullptr;
2802
2803     // Start with the base register. Do this first so that subsequent address
2804     // matching finds it last, which will prevent it from trying to match it
2805     // as the scaled value in case it happens to be a mul. That would be
2806     // problematic if we've sunk a different mul for the scale, because then
2807     // we'd end up sinking both muls.
2808     if (AddrMode.BaseReg) {
2809       Value *V = AddrMode.BaseReg;
2810       if (V->getType()->isPointerTy())
2811         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2812       if (V->getType() != IntPtrTy)
2813         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2814       Result = V;
2815     }
2816
2817     // Add the scale value.
2818     if (AddrMode.Scale) {
2819       Value *V = AddrMode.ScaledReg;
2820       if (V->getType() == IntPtrTy) {
2821         // done.
2822       } else if (V->getType()->isPointerTy()) {
2823         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2824       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2825                  cast<IntegerType>(V->getType())->getBitWidth()) {
2826         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2827       } else {
2828         // It is only safe to sign extend the BaseReg if we know that the math
2829         // required to create it did not overflow before we extend it. Since
2830         // the original IR value was tossed in favor of a constant back when
2831         // the AddrMode was created we need to bail out gracefully if widths
2832         // do not match instead of extending it.
2833         Instruction *I = dyn_cast_or_null<Instruction>(Result);
2834         if (I && (Result != AddrMode.BaseReg))
2835           I->eraseFromParent();
2836         return false;
2837       }
2838       if (AddrMode.Scale != 1)
2839         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2840                               "sunkaddr");
2841       if (Result)
2842         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2843       else
2844         Result = V;
2845     }
2846
2847     // Add in the BaseGV if present.
2848     if (AddrMode.BaseGV) {
2849       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
2850       if (Result)
2851         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2852       else
2853         Result = V;
2854     }
2855
2856     // Add in the Base Offset if present.
2857     if (AddrMode.BaseOffs) {
2858       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2859       if (Result)
2860         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2861       else
2862         Result = V;
2863     }
2864
2865     if (!Result)
2866       SunkAddr = Constant::getNullValue(Addr->getType());
2867     else
2868       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
2869   }
2870
2871   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
2872
2873   // If we have no uses, recursively delete the value and all dead instructions
2874   // using it.
2875   if (Repl->use_empty()) {
2876     // This can cause recursive deletion, which can invalidate our iterator.
2877     // Use a WeakVH to hold onto it in case this happens.
2878     WeakVH IterHandle(CurInstIterator);
2879     BasicBlock *BB = CurInstIterator->getParent();
2880
2881     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
2882
2883     if (IterHandle != CurInstIterator) {
2884       // If the iterator instruction was recursively deleted, start over at the
2885       // start of the block.
2886       CurInstIterator = BB->begin();
2887       SunkAddrs.clear();
2888     }
2889   }
2890   ++NumMemoryInsts;
2891   return true;
2892 }
2893
2894 /// OptimizeInlineAsmInst - If there are any memory operands, use
2895 /// OptimizeMemoryInst to sink their address computing into the block when
2896 /// possible / profitable.
2897 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
2898   bool MadeChange = false;
2899
2900   TargetLowering::AsmOperandInfoVector
2901     TargetConstraints = TLI->ParseConstraints(CS);
2902   unsigned ArgNo = 0;
2903   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2904     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2905
2906     // Compute the constraint code and ConstraintType to use.
2907     TLI->ComputeConstraintToUse(OpInfo, SDValue());
2908
2909     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2910         OpInfo.isIndirect) {
2911       Value *OpVal = CS->getArgOperand(ArgNo++);
2912       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
2913     } else if (OpInfo.Type == InlineAsm::isInput)
2914       ArgNo++;
2915   }
2916
2917   return MadeChange;
2918 }
2919
2920 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2921 /// basic block as the load, unless conditions are unfavorable. This allows
2922 /// SelectionDAG to fold the extend into the load.
2923 ///
2924 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2925   // Look for a load being extended.
2926   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2927   if (!LI) return false;
2928
2929   // If they're already in the same block, there's nothing to do.
2930   if (LI->getParent() == I->getParent())
2931     return false;
2932
2933   // If the load has other users and the truncate is not free, this probably
2934   // isn't worthwhile.
2935   if (!LI->hasOneUse() &&
2936       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2937               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
2938       !TLI->isTruncateFree(I->getType(), LI->getType()))
2939     return false;
2940
2941   // Check whether the target supports casts folded into loads.
2942   unsigned LType;
2943   if (isa<ZExtInst>(I))
2944     LType = ISD::ZEXTLOAD;
2945   else {
2946     assert(isa<SExtInst>(I) && "Unexpected ext type!");
2947     LType = ISD::SEXTLOAD;
2948   }
2949   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
2950     return false;
2951
2952   // Move the extend into the same block as the load, so that SelectionDAG
2953   // can fold it.
2954   I->removeFromParent();
2955   I->insertAfter(LI);
2956   ++NumExtsMoved;
2957   return true;
2958 }
2959
2960 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2961   BasicBlock *DefBB = I->getParent();
2962
2963   // If the result of a {s|z}ext and its source are both live out, rewrite all
2964   // other uses of the source with result of extension.
2965   Value *Src = I->getOperand(0);
2966   if (Src->hasOneUse())
2967     return false;
2968
2969   // Only do this xform if truncating is free.
2970   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
2971     return false;
2972
2973   // Only safe to perform the optimization if the source is also defined in
2974   // this block.
2975   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
2976     return false;
2977
2978   bool DefIsLiveOut = false;
2979   for (User *U : I->users()) {
2980     Instruction *UI = cast<Instruction>(U);
2981
2982     // Figure out which BB this ext is used in.
2983     BasicBlock *UserBB = UI->getParent();
2984     if (UserBB == DefBB) continue;
2985     DefIsLiveOut = true;
2986     break;
2987   }
2988   if (!DefIsLiveOut)
2989     return false;
2990
2991   // Make sure none of the uses are PHI nodes.
2992   for (User *U : Src->users()) {
2993     Instruction *UI = cast<Instruction>(U);
2994     BasicBlock *UserBB = UI->getParent();
2995     if (UserBB == DefBB) continue;
2996     // Be conservative. We don't want this xform to end up introducing
2997     // reloads just before load / store instructions.
2998     if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
2999       return false;
3000   }
3001
3002   // InsertedTruncs - Only insert one trunc in each block once.
3003   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
3004
3005   bool MadeChange = false;
3006   for (Use &U : Src->uses()) {
3007     Instruction *User = cast<Instruction>(U.getUser());
3008
3009     // Figure out which BB this ext is used in.
3010     BasicBlock *UserBB = User->getParent();
3011     if (UserBB == DefBB) continue;
3012
3013     // Both src and def are live in this block. Rewrite the use.
3014     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
3015
3016     if (!InsertedTrunc) {
3017       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3018       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
3019       InsertedTruncsSet.insert(InsertedTrunc);
3020     }
3021
3022     // Replace a use of the {s|z}ext source with a use of the result.
3023     U = InsertedTrunc;
3024     ++NumExtUses;
3025     MadeChange = true;
3026   }
3027
3028   return MadeChange;
3029 }
3030
3031 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
3032 /// turned into an explicit branch.
3033 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
3034   // FIXME: This should use the same heuristics as IfConversion to determine
3035   // whether a select is better represented as a branch.  This requires that
3036   // branch probability metadata is preserved for the select, which is not the
3037   // case currently.
3038
3039   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
3040
3041   // If the branch is predicted right, an out of order CPU can avoid blocking on
3042   // the compare.  Emit cmovs on compares with a memory operand as branches to
3043   // avoid stalls on the load from memory.  If the compare has more than one use
3044   // there's probably another cmov or setcc around so it's not worth emitting a
3045   // branch.
3046   if (!Cmp)
3047     return false;
3048
3049   Value *CmpOp0 = Cmp->getOperand(0);
3050   Value *CmpOp1 = Cmp->getOperand(1);
3051
3052   // We check that the memory operand has one use to avoid uses of the loaded
3053   // value directly after the compare, making branches unprofitable.
3054   return Cmp->hasOneUse() &&
3055          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
3056           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
3057 }
3058
3059
3060 /// If we have a SelectInst that will likely profit from branch prediction,
3061 /// turn it into a branch.
3062 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
3063   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
3064
3065   // Can we convert the 'select' to CF ?
3066   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
3067     return false;
3068
3069   TargetLowering::SelectSupportKind SelectKind;
3070   if (VectorCond)
3071     SelectKind = TargetLowering::VectorMaskSelect;
3072   else if (SI->getType()->isVectorTy())
3073     SelectKind = TargetLowering::ScalarCondVectorVal;
3074   else
3075     SelectKind = TargetLowering::ScalarValSelect;
3076
3077   // Do we have efficient codegen support for this kind of 'selects' ?
3078   if (TLI->isSelectSupported(SelectKind)) {
3079     // We have efficient codegen support for the select instruction.
3080     // Check if it is profitable to keep this 'select'.
3081     if (!TLI->isPredictableSelectExpensive() ||
3082         !isFormingBranchFromSelectProfitable(SI))
3083       return false;
3084   }
3085
3086   ModifiedDT = true;
3087
3088   // First, we split the block containing the select into 2 blocks.
3089   BasicBlock *StartBlock = SI->getParent();
3090   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
3091   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
3092
3093   // Create a new block serving as the landing pad for the branch.
3094   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
3095                                              NextBlock->getParent(), NextBlock);
3096
3097   // Move the unconditional branch from the block with the select in it into our
3098   // landing pad block.
3099   StartBlock->getTerminator()->eraseFromParent();
3100   BranchInst::Create(NextBlock, SmallBlock);
3101
3102   // Insert the real conditional branch based on the original condition.
3103   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
3104
3105   // The select itself is replaced with a PHI Node.
3106   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
3107   PN->takeName(SI);
3108   PN->addIncoming(SI->getTrueValue(), StartBlock);
3109   PN->addIncoming(SI->getFalseValue(), SmallBlock);
3110   SI->replaceAllUsesWith(PN);
3111   SI->eraseFromParent();
3112
3113   // Instruct OptimizeBlock to skip to the next block.
3114   CurInstIterator = StartBlock->end();
3115   ++NumSelectsExpanded;
3116   return true;
3117 }
3118
3119 static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
3120   SmallVector<int, 16> Mask(SVI->getShuffleMask());
3121   int SplatElem = -1;
3122   for (unsigned i = 0; i < Mask.size(); ++i) {
3123     if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
3124       return false;
3125     SplatElem = Mask[i];
3126   }
3127
3128   return true;
3129 }
3130
3131 /// Some targets have expensive vector shifts if the lanes aren't all the same
3132 /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
3133 /// it's often worth sinking a shufflevector splat down to its use so that
3134 /// codegen can spot all lanes are identical.
3135 bool CodeGenPrepare::OptimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
3136   BasicBlock *DefBB = SVI->getParent();
3137
3138   // Only do this xform if variable vector shifts are particularly expensive.
3139   if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
3140     return false;
3141
3142   // We only expect better codegen by sinking a shuffle if we can recognise a
3143   // constant splat.
3144   if (!isBroadcastShuffle(SVI))
3145     return false;
3146
3147   // InsertedShuffles - Only insert a shuffle in each block once.
3148   DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
3149
3150   bool MadeChange = false;
3151   for (User *U : SVI->users()) {
3152     Instruction *UI = cast<Instruction>(U);
3153
3154     // Figure out which BB this ext is used in.
3155     BasicBlock *UserBB = UI->getParent();
3156     if (UserBB == DefBB) continue;
3157
3158     // For now only apply this when the splat is used by a shift instruction.
3159     if (!UI->isShift()) continue;
3160
3161     // Everything checks out, sink the shuffle if the user's block doesn't
3162     // already have a copy.
3163     Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
3164
3165     if (!InsertedShuffle) {
3166       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
3167       InsertedShuffle = new ShuffleVectorInst(SVI->getOperand(0),
3168                                               SVI->getOperand(1),
3169                                               SVI->getOperand(2), "", InsertPt);
3170     }
3171
3172     UI->replaceUsesOfWith(SVI, InsertedShuffle);
3173     MadeChange = true;
3174   }
3175
3176   // If we removed all uses, nuke the shuffle.
3177   if (SVI->use_empty()) {
3178     SVI->eraseFromParent();
3179     MadeChange = true;
3180   }
3181
3182   return MadeChange;
3183 }
3184
3185 namespace {
3186 /// \brief Helper class to promote a scalar operation to a vector one.
3187 /// This class is used to move downward extractelement transition.
3188 /// E.g.,
3189 /// a = vector_op <2 x i32>
3190 /// b = extractelement <2 x i32> a, i32 0
3191 /// c = scalar_op b
3192 /// store c
3193 ///
3194 /// =>
3195 /// a = vector_op <2 x i32>
3196 /// c = vector_op a (equivalent to scalar_op on the related lane)
3197 /// * d = extractelement <2 x i32> c, i32 0
3198 /// * store d
3199 /// Assuming both extractelement and store can be combine, we get rid of the
3200 /// transition.
3201 class VectorPromoteHelper {
3202   /// Used to perform some checks on the legality of vector operations.
3203   const TargetLowering &TLI;
3204
3205   /// Used to estimated the cost of the promoted chain.
3206   const TargetTransformInfo &TTI;
3207
3208   /// The transition being moved downwards.
3209   Instruction *Transition;
3210   /// The sequence of instructions to be promoted.
3211   SmallVector<Instruction *, 4> InstsToBePromoted;
3212   /// Cost of combining a store and an extract.
3213   unsigned StoreExtractCombineCost;
3214   /// Instruction that will be combined with the transition.
3215   Instruction *CombineInst;
3216
3217   /// \brief The instruction that represents the current end of the transition.
3218   /// Since we are faking the promotion until we reach the end of the chain
3219   /// of computation, we need a way to get the current end of the transition.
3220   Instruction *getEndOfTransition() const {
3221     if (InstsToBePromoted.empty())
3222       return Transition;
3223     return InstsToBePromoted.back();
3224   }
3225
3226   /// \brief Return the index of the original value in the transition.
3227   /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
3228   /// c, is at index 0.
3229   unsigned getTransitionOriginalValueIdx() const {
3230     assert(isa<ExtractElementInst>(Transition) &&
3231            "Other kind of transitions are not supported yet");
3232     return 0;
3233   }
3234
3235   /// \brief Return the index of the index in the transition.
3236   /// E.g., for "extractelement <2 x i32> c, i32 0" the index
3237   /// is at index 1.
3238   unsigned getTransitionIdx() const {
3239     assert(isa<ExtractElementInst>(Transition) &&
3240            "Other kind of transitions are not supported yet");
3241     return 1;
3242   }
3243
3244   /// \brief Get the type of the transition.
3245   /// This is the type of the original value.
3246   /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
3247   /// transition is <2 x i32>.
3248   Type *getTransitionType() const {
3249     return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
3250   }
3251
3252   /// \brief Promote \p ToBePromoted by moving \p Def downward through.
3253   /// I.e., we have the following sequence:
3254   /// Def = Transition <ty1> a to <ty2>
3255   /// b = ToBePromoted <ty2> Def, ...
3256   /// =>
3257   /// b = ToBePromoted <ty1> a, ...
3258   /// Def = Transition <ty1> ToBePromoted to <ty2>
3259   void promoteImpl(Instruction *ToBePromoted);
3260
3261   /// \brief Check whether or not it is profitable to promote all the
3262   /// instructions enqueued to be promoted.
3263   bool isProfitableToPromote() {
3264     Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
3265     unsigned Index = isa<ConstantInt>(ValIdx)
3266                          ? cast<ConstantInt>(ValIdx)->getZExtValue()
3267                          : -1;
3268     Type *PromotedType = getTransitionType();
3269
3270     StoreInst *ST = cast<StoreInst>(CombineInst);
3271     unsigned AS = ST->getPointerAddressSpace();
3272     unsigned Align = ST->getAlignment();
3273     // Check if this store is supported.
3274     if (!TLI.allowsMisalignedMemoryAccesses(
3275             EVT::getEVT(ST->getValueOperand()->getType()), AS, Align)) {
3276       // If this is not supported, there is no way we can combine
3277       // the extract with the store.
3278       return false;
3279     }
3280
3281     // The scalar chain of computation has to pay for the transition
3282     // scalar to vector.
3283     // The vector chain has to account for the combining cost.
3284     uint64_t ScalarCost =
3285         TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
3286     uint64_t VectorCost = StoreExtractCombineCost;
3287     for (const auto &Inst : InstsToBePromoted) {
3288       // Compute the cost.
3289       // By construction, all instructions being promoted are arithmetic ones.
3290       // Moreover, one argument is a constant that can be viewed as a splat
3291       // constant.
3292       Value *Arg0 = Inst->getOperand(0);
3293       bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
3294                             isa<ConstantFP>(Arg0);
3295       TargetTransformInfo::OperandValueKind Arg0OVK =
3296           IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3297                          : TargetTransformInfo::OK_AnyValue;
3298       TargetTransformInfo::OperandValueKind Arg1OVK =
3299           !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
3300                           : TargetTransformInfo::OK_AnyValue;
3301       ScalarCost += TTI.getArithmeticInstrCost(
3302           Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
3303       VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
3304                                                Arg0OVK, Arg1OVK);
3305     }
3306     DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
3307                  << ScalarCost << "\nVector: " << VectorCost << '\n');
3308     return ScalarCost > VectorCost;
3309   }
3310
3311   /// \brief Generate a constant vector with \p Val with the same
3312   /// number of elements as the transition.
3313   /// \p UseSplat defines whether or not \p Val should be replicated
3314   /// accross the whole vector.
3315   /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
3316   /// otherwise we generate a vector with as many undef as possible:
3317   /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
3318   /// used at the index of the extract.
3319   Value *getConstantVector(Constant *Val, bool UseSplat) const {
3320     unsigned ExtractIdx = UINT_MAX;
3321     if (!UseSplat) {
3322       // If we cannot determine where the constant must be, we have to
3323       // use a splat constant.
3324       Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
3325       if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
3326         ExtractIdx = CstVal->getSExtValue();
3327       else
3328         UseSplat = true;
3329     }
3330
3331     unsigned End = getTransitionType()->getVectorNumElements();
3332     if (UseSplat)
3333       return ConstantVector::getSplat(End, Val);
3334
3335     SmallVector<Constant *, 4> ConstVec;
3336     UndefValue *UndefVal = UndefValue::get(Val->getType());
3337     for (unsigned Idx = 0; Idx != End; ++Idx) {
3338       if (Idx == ExtractIdx)
3339         ConstVec.push_back(Val);
3340       else
3341         ConstVec.push_back(UndefVal);
3342     }
3343     return ConstantVector::get(ConstVec);
3344   }
3345
3346   /// \brief Check if promoting to a vector type an operand at \p OperandIdx
3347   /// in \p Use can trigger undefined behavior.
3348   static bool canCauseUndefinedBehavior(const Instruction *Use,
3349                                         unsigned OperandIdx) {
3350     // This is not safe to introduce undef when the operand is on
3351     // the right hand side of a division-like instruction.
3352     if (OperandIdx != 1)
3353       return false;
3354     switch (Use->getOpcode()) {
3355     default:
3356       return false;
3357     case Instruction::SDiv:
3358     case Instruction::UDiv:
3359     case Instruction::SRem:
3360     case Instruction::URem:
3361       return true;
3362     case Instruction::FDiv:
3363     case Instruction::FRem:
3364       return !Use->hasNoNaNs();
3365     }
3366     llvm_unreachable(nullptr);
3367   }
3368
3369 public:
3370   VectorPromoteHelper(const TargetLowering &TLI, const TargetTransformInfo &TTI,
3371                       Instruction *Transition, unsigned CombineCost)
3372       : TLI(TLI), TTI(TTI), Transition(Transition),
3373         StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
3374     assert(Transition && "Do not know how to promote null");
3375   }
3376
3377   /// \brief Check if we can promote \p ToBePromoted to \p Type.
3378   bool canPromote(const Instruction *ToBePromoted) const {
3379     // We could support CastInst too.
3380     return isa<BinaryOperator>(ToBePromoted);
3381   }
3382
3383   /// \brief Check if it is profitable to promote \p ToBePromoted
3384   /// by moving downward the transition through.
3385   bool shouldPromote(const Instruction *ToBePromoted) const {
3386     // Promote only if all the operands can be statically expanded.
3387     // Indeed, we do not want to introduce any new kind of transitions.
3388     for (const Use &U : ToBePromoted->operands()) {
3389       const Value *Val = U.get();
3390       if (Val == getEndOfTransition()) {
3391         // If the use is a division and the transition is on the rhs,
3392         // we cannot promote the operation, otherwise we may create a
3393         // division by zero.
3394         if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
3395           return false;
3396         continue;
3397       }
3398       if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
3399           !isa<ConstantFP>(Val))
3400         return false;
3401     }
3402     // Check that the resulting operation is legal.
3403     int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
3404     if (!ISDOpcode)
3405       return false;
3406     return StressStoreExtract ||
3407            TLI.isOperationLegalOrCustom(ISDOpcode,
3408                                         EVT::getEVT(getTransitionType(), true));
3409   }
3410
3411   /// \brief Check whether or not \p Use can be combined
3412   /// with the transition.
3413   /// I.e., is it possible to do Use(Transition) => AnotherUse?
3414   bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
3415
3416   /// \brief Record \p ToBePromoted as part of the chain to be promoted.
3417   void enqueueForPromotion(Instruction *ToBePromoted) {
3418     InstsToBePromoted.push_back(ToBePromoted);
3419   }
3420
3421   /// \brief Set the instruction that will be combined with the transition.
3422   void recordCombineInstruction(Instruction *ToBeCombined) {
3423     assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
3424     CombineInst = ToBeCombined;
3425   }
3426
3427   /// \brief Promote all the instructions enqueued for promotion if it is
3428   /// is profitable.
3429   /// \return True if the promotion happened, false otherwise.
3430   bool promote() {
3431     // Check if there is something to promote.
3432     // Right now, if we do not have anything to combine with,
3433     // we assume the promotion is not profitable.
3434     if (InstsToBePromoted.empty() || !CombineInst)
3435       return false;
3436
3437     // Check cost.
3438     if (!StressStoreExtract && !isProfitableToPromote())
3439       return false;
3440
3441     // Promote.
3442     for (auto &ToBePromoted : InstsToBePromoted)
3443       promoteImpl(ToBePromoted);
3444     InstsToBePromoted.clear();
3445     return true;
3446   }
3447 };
3448 } // End of anonymous namespace.
3449
3450 void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
3451   // At this point, we know that all the operands of ToBePromoted but Def
3452   // can be statically promoted.
3453   // For Def, we need to use its parameter in ToBePromoted:
3454   // b = ToBePromoted ty1 a
3455   // Def = Transition ty1 b to ty2
3456   // Move the transition down.
3457   // 1. Replace all uses of the promoted operation by the transition.
3458   // = ... b => = ... Def.
3459   assert(ToBePromoted->getType() == Transition->getType() &&
3460          "The type of the result of the transition does not match "
3461          "the final type");
3462   ToBePromoted->replaceAllUsesWith(Transition);
3463   // 2. Update the type of the uses.
3464   // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
3465   Type *TransitionTy = getTransitionType();
3466   ToBePromoted->mutateType(TransitionTy);
3467   // 3. Update all the operands of the promoted operation with promoted
3468   // operands.
3469   // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
3470   for (Use &U : ToBePromoted->operands()) {
3471     Value *Val = U.get();
3472     Value *NewVal = nullptr;
3473     if (Val == Transition)
3474       NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
3475     else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
3476              isa<ConstantFP>(Val)) {
3477       // Use a splat constant if it is not safe to use undef.
3478       NewVal = getConstantVector(
3479           cast<Constant>(Val),
3480           isa<UndefValue>(Val) ||
3481               canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
3482     } else
3483       assert(0 && "Did you modified shouldPromote and forgot to update this?");
3484     ToBePromoted->setOperand(U.getOperandNo(), NewVal);
3485   }
3486   Transition->removeFromParent();
3487   Transition->insertAfter(ToBePromoted);
3488   Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
3489 }
3490
3491 /// Some targets can do store(extractelement) with one instruction.
3492 /// Try to push the extractelement towards the stores when the target
3493 /// has this feature and this is profitable.
3494 bool CodeGenPrepare::OptimizeExtractElementInst(Instruction *Inst) {
3495   unsigned CombineCost = UINT_MAX;
3496   if (DisableStoreExtract || !TLI ||
3497       (!StressStoreExtract &&
3498        !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
3499                                        Inst->getOperand(1), CombineCost)))
3500     return false;
3501
3502   // At this point we know that Inst is a vector to scalar transition.
3503   // Try to move it down the def-use chain, until:
3504   // - We can combine the transition with its single use
3505   //   => we got rid of the transition.
3506   // - We escape the current basic block
3507   //   => we would need to check that we are moving it at a cheaper place and
3508   //      we do not do that for now.
3509   BasicBlock *Parent = Inst->getParent();
3510   DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
3511   VectorPromoteHelper VPH(*TLI, *TTI, Inst, CombineCost);
3512   // If the transition has more than one use, assume this is not going to be
3513   // beneficial.
3514   while (Inst->hasOneUse()) {
3515     Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
3516     DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
3517
3518     if (ToBePromoted->getParent() != Parent) {
3519       DEBUG(dbgs() << "Instruction to promote is in a different block ("
3520                    << ToBePromoted->getParent()->getName()
3521                    << ") than the transition (" << Parent->getName() << ").\n");
3522       return false;
3523     }
3524
3525     if (VPH.canCombine(ToBePromoted)) {
3526       DEBUG(dbgs() << "Assume " << *Inst << '\n'
3527                    << "will be combined with: " << *ToBePromoted << '\n');
3528       VPH.recordCombineInstruction(ToBePromoted);
3529       bool Changed = VPH.promote();
3530       NumStoreExtractExposed += Changed;
3531       return Changed;
3532     }
3533
3534     DEBUG(dbgs() << "Try promoting.\n");
3535     if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
3536       return false;
3537
3538     DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
3539
3540     VPH.enqueueForPromotion(ToBePromoted);
3541     Inst = ToBePromoted;
3542   }
3543   return false;
3544 }
3545
3546 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
3547   if (PHINode *P = dyn_cast<PHINode>(I)) {
3548     // It is possible for very late stage optimizations (such as SimplifyCFG)
3549     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
3550     // trivial PHI, go ahead and zap it here.
3551     if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : nullptr,
3552                                        TLInfo, DT)) {
3553       P->replaceAllUsesWith(V);
3554       P->eraseFromParent();
3555       ++NumPHIsElim;
3556       return true;
3557     }
3558     return false;
3559   }
3560
3561   if (CastInst *CI = dyn_cast<CastInst>(I)) {
3562     // If the source of the cast is a constant, then this should have
3563     // already been constant folded.  The only reason NOT to constant fold
3564     // it is if something (e.g. LSR) was careful to place the constant
3565     // evaluation in a block other than then one that uses it (e.g. to hoist
3566     // the address of globals out of a loop).  If this is the case, we don't
3567     // want to forward-subst the cast.
3568     if (isa<Constant>(CI->getOperand(0)))
3569       return false;
3570
3571     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
3572       return true;
3573
3574     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
3575       /// Sink a zext or sext into its user blocks if the target type doesn't
3576       /// fit in one register
3577       if (TLI && TLI->getTypeAction(CI->getContext(),
3578                                     TLI->getValueType(CI->getType())) ==
3579                      TargetLowering::TypeExpandInteger) {
3580         return SinkCast(CI);
3581       } else {
3582         bool MadeChange = MoveExtToFormExtLoad(I);
3583         return MadeChange | OptimizeExtUses(I);
3584       }
3585     }
3586     return false;
3587   }
3588
3589   if (CmpInst *CI = dyn_cast<CmpInst>(I))
3590     if (!TLI || !TLI->hasMultipleConditionRegisters())
3591       return OptimizeCmpExpression(CI);
3592
3593   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
3594     if (TLI)
3595       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
3596     return false;
3597   }
3598
3599   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
3600     if (TLI)
3601       return OptimizeMemoryInst(I, SI->getOperand(1),
3602                                 SI->getOperand(0)->getType());
3603     return false;
3604   }
3605
3606   BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
3607
3608   if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
3609                 BinOp->getOpcode() == Instruction::LShr)) {
3610     ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
3611     if (TLI && CI && TLI->hasExtractBitsInsn())
3612       return OptimizeExtractBits(BinOp, CI, *TLI);
3613
3614     return false;
3615   }
3616
3617   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3618     if (GEPI->hasAllZeroIndices()) {
3619       /// The GEP operand must be a pointer, so must its result -> BitCast
3620       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
3621                                         GEPI->getName(), GEPI);
3622       GEPI->replaceAllUsesWith(NC);
3623       GEPI->eraseFromParent();
3624       ++NumGEPsElim;
3625       OptimizeInst(NC);
3626       return true;
3627     }
3628     return false;
3629   }
3630
3631   if (CallInst *CI = dyn_cast<CallInst>(I))
3632     return OptimizeCallInst(CI);
3633
3634   if (SelectInst *SI = dyn_cast<SelectInst>(I))
3635     return OptimizeSelectInst(SI);
3636
3637   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
3638     return OptimizeShuffleVectorInst(SVI);
3639
3640   if (isa<ExtractElementInst>(I))
3641     return OptimizeExtractElementInst(I);
3642
3643   return false;
3644 }
3645
3646 // In this pass we look for GEP and cast instructions that are used
3647 // across basic blocks and rewrite them to improve basic-block-at-a-time
3648 // selection.
3649 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
3650   SunkAddrs.clear();
3651   bool MadeChange = false;
3652
3653   CurInstIterator = BB.begin();
3654   while (CurInstIterator != BB.end())
3655     MadeChange |= OptimizeInst(CurInstIterator++);
3656
3657   MadeChange |= DupRetToEnableTailCallOpts(&BB);
3658
3659   return MadeChange;
3660 }
3661
3662 // llvm.dbg.value is far away from the value then iSel may not be able
3663 // handle it properly. iSel will drop llvm.dbg.value if it can not
3664 // find a node corresponding to the value.
3665 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
3666   bool MadeChange = false;
3667   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
3668     Instruction *PrevNonDbgInst = nullptr;
3669     for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
3670       Instruction *Insn = BI; ++BI;
3671       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
3672       // Leave dbg.values that refer to an alloca alone. These
3673       // instrinsics describe the address of a variable (= the alloca)
3674       // being taken.  They should not be moved next to the alloca
3675       // (and to the beginning of the scope), but rather stay close to
3676       // where said address is used.
3677       if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
3678         PrevNonDbgInst = Insn;
3679         continue;
3680       }
3681
3682       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
3683       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
3684         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
3685         DVI->removeFromParent();
3686         if (isa<PHINode>(VI))
3687           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
3688         else
3689           DVI->insertAfter(VI);
3690         MadeChange = true;
3691         ++NumDbgValueMoved;
3692       }
3693     }
3694   }
3695   return MadeChange;
3696 }
3697
3698 // If there is a sequence that branches based on comparing a single bit
3699 // against zero that can be combined into a single instruction, and the
3700 // target supports folding these into a single instruction, sink the
3701 // mask and compare into the branch uses. Do this before OptimizeBlock ->
3702 // OptimizeInst -> OptimizeCmpExpression, which perturbs the pattern being
3703 // searched for.
3704 bool CodeGenPrepare::sinkAndCmp(Function &F) {
3705   if (!EnableAndCmpSinking)
3706     return false;
3707   if (!TLI || !TLI->isMaskAndBranchFoldingLegal())
3708     return false;
3709   bool MadeChange = false;
3710   for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
3711     BasicBlock *BB = I++;
3712
3713     // Does this BB end with the following?
3714     //   %andVal = and %val, #single-bit-set
3715     //   %icmpVal = icmp %andResult, 0
3716     //   br i1 %cmpVal label %dest1, label %dest2"
3717     BranchInst *Brcc = dyn_cast<BranchInst>(BB->getTerminator());
3718     if (!Brcc || !Brcc->isConditional())
3719       continue;
3720     ICmpInst *Cmp = dyn_cast<ICmpInst>(Brcc->getOperand(0));
3721     if (!Cmp || Cmp->getParent() != BB)
3722       continue;
3723     ConstantInt *Zero = dyn_cast<ConstantInt>(Cmp->getOperand(1));
3724     if (!Zero || !Zero->isZero())
3725       continue;
3726     Instruction *And = dyn_cast<Instruction>(Cmp->getOperand(0));
3727     if (!And || And->getOpcode() != Instruction::And || And->getParent() != BB)
3728       continue;
3729     ConstantInt* Mask = dyn_cast<ConstantInt>(And->getOperand(1));
3730     if (!Mask || !Mask->getUniqueInteger().isPowerOf2())
3731       continue;
3732     DEBUG(dbgs() << "found and; icmp ?,0; brcc\n"); DEBUG(BB->dump());
3733
3734     // Push the "and; icmp" for any users that are conditional branches.
3735     // Since there can only be one branch use per BB, we don't need to keep
3736     // track of which BBs we insert into.
3737     for (Value::use_iterator UI = Cmp->use_begin(), E = Cmp->use_end();
3738          UI != E; ) {
3739       Use &TheUse = *UI;
3740       // Find brcc use.
3741       BranchInst *BrccUser = dyn_cast<BranchInst>(*UI);
3742       ++UI;
3743       if (!BrccUser || !BrccUser->isConditional())
3744         continue;
3745       BasicBlock *UserBB = BrccUser->getParent();
3746       if (UserBB == BB) continue;
3747       DEBUG(dbgs() << "found Brcc use\n");
3748
3749       // Sink the "and; icmp" to use.
3750       MadeChange = true;
3751       BinaryOperator *NewAnd =
3752         BinaryOperator::CreateAnd(And->getOperand(0), And->getOperand(1), "",
3753                                   BrccUser);
3754       CmpInst *NewCmp =
3755         CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(), NewAnd, Zero,
3756                         "", BrccUser);
3757       TheUse = NewCmp;
3758       ++NumAndCmpsMoved;
3759       DEBUG(BrccUser->getParent()->dump());
3760     }
3761   }
3762   return MadeChange;
3763 }