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