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