ed12b2e7537efb7a094ea2a75d34557a0994119b
[oota-llvm.git] / lib / Transforms / Scalar / 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/Transforms/Scalar.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/ValueMap.h"
22 #include "llvm/Analysis/DominatorInternals.h"
23 #include "llvm/Analysis/Dominators.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.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/Pass.h"
34 #include "llvm/Support/CallSite.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/GetElementPtrTypeIterator.h"
38 #include "llvm/Support/PatternMatch.h"
39 #include "llvm/Support/ValueHandle.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/BuildLibCalls.h"
45 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 using namespace llvm;
48 using namespace llvm::PatternMatch;
49
50 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
51 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
52 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
53 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54                       "sunken Cmps");
55 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56                        "of sunken Casts");
57 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58                           "computations were sunk");
59 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
60 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
61 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
62 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
63 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
64
65 static cl::opt<bool> DisableBranchOpts(
66   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
67   cl::desc("Disable branch optimizations in CodeGenPrepare"));
68
69 static cl::opt<bool> DisableSelectToBranch(
70   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
71   cl::desc("Disable select to branch conversion."));
72
73 namespace {
74   class CodeGenPrepare : public FunctionPass {
75     /// TLI - Keep a pointer of a TargetLowering to consult for determining
76     /// transformation profitability.
77     const TargetMachine *TM;
78     const TargetLowering *TLI;
79     const TargetLibraryInfo *TLInfo;
80     DominatorTree *DT;
81
82     /// CurInstIterator - As we scan instructions optimizing them, this is the
83     /// next instruction to optimize.  Xforms that can invalidate this should
84     /// update it.
85     BasicBlock::iterator CurInstIterator;
86
87     /// Keeps track of non-local addresses that have been sunk into a block.
88     /// This allows us to avoid inserting duplicate code for blocks with
89     /// multiple load/stores of the same address.
90     ValueMap<Value*, Value*> SunkAddrs;
91
92     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
93     /// be updated.
94     bool ModifiedDT;
95
96     /// OptSize - True if optimizing for size.
97     bool OptSize;
98
99   public:
100     static char ID; // Pass identification, replacement for typeid
101     explicit CodeGenPrepare(const TargetMachine *TM = 0)
102       : FunctionPass(ID), TM(TM), TLI(0) {
103         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
104       }
105     bool runOnFunction(Function &F);
106
107     const char *getPassName() const { return "CodeGen Prepare"; }
108
109     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
110       AU.addPreserved<DominatorTree>();
111       AU.addRequired<TargetLibraryInfo>();
112     }
113
114   private:
115     bool EliminateFallThrough(Function &F);
116     bool EliminateMostlyEmptyBlocks(Function &F);
117     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
118     void EliminateMostlyEmptyBlock(BasicBlock *BB);
119     bool OptimizeBlock(BasicBlock &BB);
120     bool OptimizeInst(Instruction *I);
121     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
122     bool OptimizeInlineAsmInst(CallInst *CS);
123     bool OptimizeCallInst(CallInst *CI);
124     bool MoveExtToFormExtLoad(Instruction *I);
125     bool OptimizeExtUses(Instruction *I);
126     bool OptimizeSelectInst(SelectInst *SI);
127     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
128     bool PlaceDbgValues(Function &F);
129   };
130 }
131
132 char CodeGenPrepare::ID = 0;
133 INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
134                 "Optimize for code generation", false, false)
135 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
136 INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
137                 "Optimize for code generation", false, false)
138
139 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
140   return new CodeGenPrepare(TM);
141 }
142
143 bool CodeGenPrepare::runOnFunction(Function &F) {
144   bool EverMadeChange = false;
145
146   ModifiedDT = false;
147   if (TM) TLI = TM->getTargetLowering();
148   TLInfo = &getAnalysis<TargetLibraryInfo>();
149   DT = getAnalysisIfAvailable<DominatorTree>();
150   OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
151                                            Attribute::OptimizeForSize);
152
153   /// This optimization identifies DIV instructions that can be
154   /// profitably bypassed and carried out with a shorter, faster divide.
155   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
156     const DenseMap<unsigned int, unsigned int> &BypassWidths =
157        TLI->getBypassSlowDivWidths();
158     for (Function::iterator I = F.begin(); I != F.end(); I++)
159       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
160   }
161
162   // Eliminate blocks that contain only PHI nodes and an
163   // unconditional branch.
164   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
165
166   // llvm.dbg.value is far away from the value then iSel may not be able
167   // handle it properly. iSel will drop llvm.dbg.value if it can not
168   // find a node corresponding to the value.
169   EverMadeChange |= PlaceDbgValues(F);
170
171   bool MadeChange = true;
172   while (MadeChange) {
173     MadeChange = false;
174     for (Function::iterator I = F.begin(); I != F.end(); ) {
175       BasicBlock *BB = I++;
176       MadeChange |= OptimizeBlock(*BB);
177     }
178     EverMadeChange |= MadeChange;
179   }
180
181   SunkAddrs.clear();
182
183   if (!DisableBranchOpts) {
184     MadeChange = false;
185     SmallPtrSet<BasicBlock*, 8> WorkList;
186     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
187       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
188       MadeChange |= ConstantFoldTerminator(BB, true);
189       if (!MadeChange) continue;
190
191       for (SmallVectorImpl<BasicBlock*>::iterator
192              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
193         if (pred_begin(*II) == pred_end(*II))
194           WorkList.insert(*II);
195     }
196
197     // Delete the dead blocks and any of their dead successors.
198     MadeChange |= !WorkList.empty();
199     while (!WorkList.empty()) {
200       BasicBlock *BB = *WorkList.begin();
201       WorkList.erase(BB);
202       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
203
204       DeleteDeadBlock(BB);
205
206       for (SmallVectorImpl<BasicBlock*>::iterator
207              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
208         if (pred_begin(*II) == pred_end(*II))
209           WorkList.insert(*II);
210     }
211
212     // Merge pairs of basic blocks with unconditional branches, connected by
213     // a single edge.
214     if (EverMadeChange || MadeChange)
215       MadeChange |= EliminateFallThrough(F);
216
217     if (MadeChange)
218       ModifiedDT = true;
219     EverMadeChange |= MadeChange;
220   }
221
222   if (ModifiedDT && DT)
223     DT->DT->recalculate(F);
224
225   return EverMadeChange;
226 }
227
228 /// EliminateFallThrough - Merge basic blocks which are connected
229 /// by a single edge, where one of the basic blocks has a single successor
230 /// pointing to the other basic block, which has a single predecessor.
231 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
232   bool Changed = false;
233   // Scan all of the blocks in the function, except for the entry block.
234   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
235     BasicBlock *BB = I++;
236     // If the destination block has a single pred, then this is a trivial
237     // edge, just collapse it.
238     BasicBlock *SinglePred = BB->getSinglePredecessor();
239
240     // Don't merge if BB's address is taken.
241     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
242
243     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
244     if (Term && !Term->isConditional()) {
245       Changed = true;
246       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
247       // Remember if SinglePred was the entry block of the function.
248       // If so, we will need to move BB back to the entry position.
249       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
250       MergeBasicBlockIntoOnlyPred(BB, this);
251
252       if (isEntry && BB != &BB->getParent()->getEntryBlock())
253         BB->moveBefore(&BB->getParent()->getEntryBlock());
254
255       // We have erased a block. Update the iterator.
256       I = BB;
257     }
258   }
259   return Changed;
260 }
261
262 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
263 /// debug info directives, and an unconditional branch.  Passes before isel
264 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
265 /// isel.  Start by eliminating these blocks so we can split them the way we
266 /// want them.
267 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
268   bool MadeChange = false;
269   // Note that this intentionally skips the entry block.
270   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
271     BasicBlock *BB = I++;
272
273     // If this block doesn't end with an uncond branch, ignore it.
274     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
275     if (!BI || !BI->isUnconditional())
276       continue;
277
278     // If the instruction before the branch (skipping debug info) isn't a phi
279     // node, then other stuff is happening here.
280     BasicBlock::iterator BBI = BI;
281     if (BBI != BB->begin()) {
282       --BBI;
283       while (isa<DbgInfoIntrinsic>(BBI)) {
284         if (BBI == BB->begin())
285           break;
286         --BBI;
287       }
288       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
289         continue;
290     }
291
292     // Do not break infinite loops.
293     BasicBlock *DestBB = BI->getSuccessor(0);
294     if (DestBB == BB)
295       continue;
296
297     if (!CanMergeBlocks(BB, DestBB))
298       continue;
299
300     EliminateMostlyEmptyBlock(BB);
301     MadeChange = true;
302   }
303   return MadeChange;
304 }
305
306 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
307 /// single uncond branch between them, and BB contains no other non-phi
308 /// instructions.
309 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
310                                     const BasicBlock *DestBB) const {
311   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
312   // the successor.  If there are more complex condition (e.g. preheaders),
313   // don't mess around with them.
314   BasicBlock::const_iterator BBI = BB->begin();
315   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
316     for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
317          UI != E; ++UI) {
318       const Instruction *User = cast<Instruction>(*UI);
319       if (User->getParent() != DestBB || !isa<PHINode>(User))
320         return false;
321       // If User is inside DestBB block and it is a PHINode then check
322       // incoming value. If incoming value is not from BB then this is
323       // a complex condition (e.g. preheaders) we want to avoid here.
324       if (User->getParent() == DestBB) {
325         if (const PHINode *UPN = dyn_cast<PHINode>(User))
326           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
327             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
328             if (Insn && Insn->getParent() == BB &&
329                 Insn->getParent() != UPN->getIncomingBlock(I))
330               return false;
331           }
332       }
333     }
334   }
335
336   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
337   // and DestBB may have conflicting incoming values for the block.  If so, we
338   // can't merge the block.
339   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
340   if (!DestBBPN) return true;  // no conflict.
341
342   // Collect the preds of BB.
343   SmallPtrSet<const BasicBlock*, 16> BBPreds;
344   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
345     // It is faster to get preds from a PHI than with pred_iterator.
346     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
347       BBPreds.insert(BBPN->getIncomingBlock(i));
348   } else {
349     BBPreds.insert(pred_begin(BB), pred_end(BB));
350   }
351
352   // Walk the preds of DestBB.
353   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
354     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
355     if (BBPreds.count(Pred)) {   // Common predecessor?
356       BBI = DestBB->begin();
357       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
358         const Value *V1 = PN->getIncomingValueForBlock(Pred);
359         const Value *V2 = PN->getIncomingValueForBlock(BB);
360
361         // If V2 is a phi node in BB, look up what the mapped value will be.
362         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
363           if (V2PN->getParent() == BB)
364             V2 = V2PN->getIncomingValueForBlock(Pred);
365
366         // If there is a conflict, bail out.
367         if (V1 != V2) return false;
368       }
369     }
370   }
371
372   return true;
373 }
374
375
376 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
377 /// an unconditional branch in it.
378 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
379   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
380   BasicBlock *DestBB = BI->getSuccessor(0);
381
382   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
383
384   // If the destination block has a single pred, then this is a trivial edge,
385   // just collapse it.
386   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
387     if (SinglePred != DestBB) {
388       // Remember if SinglePred was the entry block of the function.  If so, we
389       // will need to move BB back to the entry position.
390       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
391       MergeBasicBlockIntoOnlyPred(DestBB, this);
392
393       if (isEntry && BB != &BB->getParent()->getEntryBlock())
394         BB->moveBefore(&BB->getParent()->getEntryBlock());
395
396       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
397       return;
398     }
399   }
400
401   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
402   // to handle the new incoming edges it is about to have.
403   PHINode *PN;
404   for (BasicBlock::iterator BBI = DestBB->begin();
405        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
406     // Remove the incoming value for BB, and remember it.
407     Value *InVal = PN->removeIncomingValue(BB, false);
408
409     // Two options: either the InVal is a phi node defined in BB or it is some
410     // value that dominates BB.
411     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
412     if (InValPhi && InValPhi->getParent() == BB) {
413       // Add all of the input values of the input PHI as inputs of this phi.
414       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
415         PN->addIncoming(InValPhi->getIncomingValue(i),
416                         InValPhi->getIncomingBlock(i));
417     } else {
418       // Otherwise, add one instance of the dominating value for each edge that
419       // we will be adding.
420       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
421         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
422           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
423       } else {
424         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
425           PN->addIncoming(InVal, *PI);
426       }
427     }
428   }
429
430   // The PHIs are now updated, change everything that refers to BB to use
431   // DestBB and remove BB.
432   BB->replaceAllUsesWith(DestBB);
433   if (DT && !ModifiedDT) {
434     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
435     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
436     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
437     DT->changeImmediateDominator(DestBB, NewIDom);
438     DT->eraseNode(BB);
439   }
440   BB->eraseFromParent();
441   ++NumBlocksElim;
442
443   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
444 }
445
446 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
447 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
448 /// sink it into user blocks to reduce the number of virtual
449 /// registers that must be created and coalesced.
450 ///
451 /// Return true if any changes are made.
452 ///
453 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
454   // If this is a noop copy,
455   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
456   EVT DstVT = TLI.getValueType(CI->getType());
457
458   // This is an fp<->int conversion?
459   if (SrcVT.isInteger() != DstVT.isInteger())
460     return false;
461
462   // If this is an extension, it will be a zero or sign extension, which
463   // isn't a noop.
464   if (SrcVT.bitsLT(DstVT)) return false;
465
466   // If these values will be promoted, find out what they will be promoted
467   // to.  This helps us consider truncates on PPC as noop copies when they
468   // are.
469   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
470       TargetLowering::TypePromoteInteger)
471     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
472   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
473       TargetLowering::TypePromoteInteger)
474     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
475
476   // If, after promotion, these are the same types, this is a noop copy.
477   if (SrcVT != DstVT)
478     return false;
479
480   BasicBlock *DefBB = CI->getParent();
481
482   /// InsertedCasts - Only insert a cast in each block once.
483   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
484
485   bool MadeChange = false;
486   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
487        UI != E; ) {
488     Use &TheUse = UI.getUse();
489     Instruction *User = cast<Instruction>(*UI);
490
491     // Figure out which BB this cast is used in.  For PHI's this is the
492     // appropriate predecessor block.
493     BasicBlock *UserBB = User->getParent();
494     if (PHINode *PN = dyn_cast<PHINode>(User)) {
495       UserBB = PN->getIncomingBlock(UI);
496     }
497
498     // Preincrement use iterator so we don't invalidate it.
499     ++UI;
500
501     // If this user is in the same block as the cast, don't change the cast.
502     if (UserBB == DefBB) continue;
503
504     // If we have already inserted a cast into this block, use it.
505     CastInst *&InsertedCast = InsertedCasts[UserBB];
506
507     if (!InsertedCast) {
508       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
509       InsertedCast =
510         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
511                          InsertPt);
512       MadeChange = true;
513     }
514
515     // Replace a use of the cast with a use of the new cast.
516     TheUse = InsertedCast;
517     ++NumCastUses;
518   }
519
520   // If we removed all uses, nuke the cast.
521   if (CI->use_empty()) {
522     CI->eraseFromParent();
523     MadeChange = true;
524   }
525
526   return MadeChange;
527 }
528
529 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
530 /// the number of virtual registers that must be created and coalesced.  This is
531 /// a clear win except on targets with multiple condition code registers
532 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
533 ///
534 /// Return true if any changes are made.
535 static bool OptimizeCmpExpression(CmpInst *CI) {
536   BasicBlock *DefBB = CI->getParent();
537
538   /// InsertedCmp - Only insert a cmp in each block once.
539   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
540
541   bool MadeChange = false;
542   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
543        UI != E; ) {
544     Use &TheUse = UI.getUse();
545     Instruction *User = cast<Instruction>(*UI);
546
547     // Preincrement use iterator so we don't invalidate it.
548     ++UI;
549
550     // Don't bother for PHI nodes.
551     if (isa<PHINode>(User))
552       continue;
553
554     // Figure out which BB this cmp is used in.
555     BasicBlock *UserBB = User->getParent();
556
557     // If this user is in the same block as the cmp, don't change the cmp.
558     if (UserBB == DefBB) continue;
559
560     // If we have already inserted a cmp into this block, use it.
561     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
562
563     if (!InsertedCmp) {
564       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
565       InsertedCmp =
566         CmpInst::Create(CI->getOpcode(),
567                         CI->getPredicate(),  CI->getOperand(0),
568                         CI->getOperand(1), "", InsertPt);
569       MadeChange = true;
570     }
571
572     // Replace a use of the cmp with a use of the new cmp.
573     TheUse = InsertedCmp;
574     ++NumCmpUses;
575   }
576
577   // If we removed all uses, nuke the cmp.
578   if (CI->use_empty())
579     CI->eraseFromParent();
580
581   return MadeChange;
582 }
583
584 namespace {
585 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
586 protected:
587   void replaceCall(Value *With) {
588     CI->replaceAllUsesWith(With);
589     CI->eraseFromParent();
590   }
591   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
592       if (ConstantInt *SizeCI =
593                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
594         return SizeCI->isAllOnesValue();
595     return false;
596   }
597 };
598 } // end anonymous namespace
599
600 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
601   BasicBlock *BB = CI->getParent();
602
603   // Lower inline assembly if we can.
604   // If we found an inline asm expession, and if the target knows how to
605   // lower it to normal LLVM code, do so now.
606   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
607     if (TLI->ExpandInlineAsm(CI)) {
608       // Avoid invalidating the iterator.
609       CurInstIterator = BB->begin();
610       // Avoid processing instructions out of order, which could cause
611       // reuse before a value is defined.
612       SunkAddrs.clear();
613       return true;
614     }
615     // Sink address computing for memory operands into the block.
616     if (OptimizeInlineAsmInst(CI))
617       return true;
618   }
619
620   // Lower all uses of llvm.objectsize.*
621   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
622   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
623     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
624     Type *ReturnTy = CI->getType();
625     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
626
627     // Substituting this can cause recursive simplifications, which can
628     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
629     // happens.
630     WeakVH IterHandle(CurInstIterator);
631
632     replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
633                                   TLInfo, ModifiedDT ? 0 : DT);
634
635     // If the iterator instruction was recursively deleted, start over at the
636     // start of the block.
637     if (IterHandle != CurInstIterator) {
638       CurInstIterator = BB->begin();
639       SunkAddrs.clear();
640     }
641     return true;
642   }
643
644   if (II && TLI) {
645     SmallVector<Value*, 2> PtrOps;
646     Type *AccessTy;
647     if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
648       while (!PtrOps.empty())
649         if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
650           return true;
651   }
652
653   // From here on out we're working with named functions.
654   if (CI->getCalledFunction() == 0) return false;
655
656   // We'll need DataLayout from here on out.
657   const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
658   if (!TD) return false;
659
660   // Lower all default uses of _chk calls.  This is very similar
661   // to what InstCombineCalls does, but here we are only lowering calls
662   // that have the default "don't know" as the objectsize.  Anything else
663   // should be left alone.
664   CodeGenPrepareFortifiedLibCalls Simplifier;
665   return Simplifier.fold(CI, TD, TLInfo);
666 }
667
668 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
669 /// instructions to the predecessor to enable tail call optimizations. The
670 /// case it is currently looking for is:
671 /// @code
672 /// bb0:
673 ///   %tmp0 = tail call i32 @f0()
674 ///   br label %return
675 /// bb1:
676 ///   %tmp1 = tail call i32 @f1()
677 ///   br label %return
678 /// bb2:
679 ///   %tmp2 = tail call i32 @f2()
680 ///   br label %return
681 /// return:
682 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
683 ///   ret i32 %retval
684 /// @endcode
685 ///
686 /// =>
687 ///
688 /// @code
689 /// bb0:
690 ///   %tmp0 = tail call i32 @f0()
691 ///   ret i32 %tmp0
692 /// bb1:
693 ///   %tmp1 = tail call i32 @f1()
694 ///   ret i32 %tmp1
695 /// bb2:
696 ///   %tmp2 = tail call i32 @f2()
697 ///   ret i32 %tmp2
698 /// @endcode
699 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
700   if (!TLI)
701     return false;
702
703   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
704   if (!RI)
705     return false;
706
707   PHINode *PN = 0;
708   BitCastInst *BCI = 0;
709   Value *V = RI->getReturnValue();
710   if (V) {
711     BCI = dyn_cast<BitCastInst>(V);
712     if (BCI)
713       V = BCI->getOperand(0);
714
715     PN = dyn_cast<PHINode>(V);
716     if (!PN)
717       return false;
718   }
719
720   if (PN && PN->getParent() != BB)
721     return false;
722
723   // It's not safe to eliminate the sign / zero extension of the return value.
724   // See llvm::isInTailCallPosition().
725   const Function *F = BB->getParent();
726   AttributeSet CallerAttrs = F->getAttributes();
727   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
728       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
729     return false;
730
731   // Make sure there are no instructions between the PHI and return, or that the
732   // return is the first instruction in the block.
733   if (PN) {
734     BasicBlock::iterator BI = BB->begin();
735     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
736     if (&*BI == BCI)
737       // Also skip over the bitcast.
738       ++BI;
739     if (&*BI != RI)
740       return false;
741   } else {
742     BasicBlock::iterator BI = BB->begin();
743     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
744     if (&*BI != RI)
745       return false;
746   }
747
748   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
749   /// call.
750   SmallVector<CallInst*, 4> TailCalls;
751   if (PN) {
752     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
753       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
754       // Make sure the phi value is indeed produced by the tail call.
755       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
756           TLI->mayBeEmittedAsTailCall(CI))
757         TailCalls.push_back(CI);
758     }
759   } else {
760     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
761     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
762       if (!VisitedBBs.insert(*PI))
763         continue;
764
765       BasicBlock::InstListType &InstList = (*PI)->getInstList();
766       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
767       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
768       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
769       if (RI == RE)
770         continue;
771
772       CallInst *CI = dyn_cast<CallInst>(&*RI);
773       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
774         TailCalls.push_back(CI);
775     }
776   }
777
778   bool Changed = false;
779   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
780     CallInst *CI = TailCalls[i];
781     CallSite CS(CI);
782
783     // Conservatively require the attributes of the call to match those of the
784     // return. Ignore noalias because it doesn't affect the call sequence.
785     AttributeSet CalleeAttrs = CS.getAttributes();
786     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
787           removeAttribute(Attribute::NoAlias) !=
788         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
789           removeAttribute(Attribute::NoAlias))
790       continue;
791
792     // Make sure the call instruction is followed by an unconditional branch to
793     // the return block.
794     BasicBlock *CallBB = CI->getParent();
795     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
796     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
797       continue;
798
799     // Duplicate the return into CallBB.
800     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
801     ModifiedDT = Changed = true;
802     ++NumRetsDup;
803   }
804
805   // If we eliminated all predecessors of the block, delete the block now.
806   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
807     BB->eraseFromParent();
808
809   return Changed;
810 }
811
812 //===----------------------------------------------------------------------===//
813 // Memory Optimization
814 //===----------------------------------------------------------------------===//
815
816 namespace {
817
818 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
819 /// which holds actual Value*'s for register values.
820 struct ExtAddrMode : public TargetLowering::AddrMode {
821   Value *BaseReg;
822   Value *ScaledReg;
823   ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
824   void print(raw_ostream &OS) const;
825   void dump() const;
826
827   bool operator==(const ExtAddrMode& O) const {
828     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
829            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
830            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
831   }
832 };
833
834 #ifndef NDEBUG
835 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
836   AM.print(OS);
837   return OS;
838 }
839 #endif
840
841 void ExtAddrMode::print(raw_ostream &OS) const {
842   bool NeedPlus = false;
843   OS << "[";
844   if (BaseGV) {
845     OS << (NeedPlus ? " + " : "")
846        << "GV:";
847     BaseGV->printAsOperand(OS, /*PrintType=*/false);
848     NeedPlus = true;
849   }
850
851   if (BaseOffs)
852     OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
853
854   if (BaseReg) {
855     OS << (NeedPlus ? " + " : "")
856        << "Base:";
857     BaseReg->printAsOperand(OS, /*PrintType=*/false);
858     NeedPlus = true;
859   }
860   if (Scale) {
861     OS << (NeedPlus ? " + " : "")
862        << Scale << "*";
863     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
864   }
865
866   OS << ']';
867 }
868
869 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
870 void ExtAddrMode::dump() const {
871   print(dbgs());
872   dbgs() << '\n';
873 }
874 #endif
875
876
877 /// \brief A helper class for matching addressing modes.
878 ///
879 /// This encapsulates the logic for matching the target-legal addressing modes.
880 class AddressingModeMatcher {
881   SmallVectorImpl<Instruction*> &AddrModeInsts;
882   const TargetLowering &TLI;
883
884   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
885   /// the memory instruction that we're computing this address for.
886   Type *AccessTy;
887   Instruction *MemoryInst;
888
889   /// AddrMode - This is the addressing mode that we're building up.  This is
890   /// part of the return value of this addressing mode matching stuff.
891   ExtAddrMode &AddrMode;
892
893   /// IgnoreProfitability - This is set to true when we should not do
894   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
895   /// always returns true.
896   bool IgnoreProfitability;
897
898   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
899                         const TargetLowering &T, Type *AT,
900                         Instruction *MI, ExtAddrMode &AM)
901     : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
902     IgnoreProfitability = false;
903   }
904 public:
905
906   /// Match - Find the maximal addressing mode that a load/store of V can fold,
907   /// give an access type of AccessTy.  This returns a list of involved
908   /// instructions in AddrModeInsts.
909   static ExtAddrMode Match(Value *V, Type *AccessTy,
910                            Instruction *MemoryInst,
911                            SmallVectorImpl<Instruction*> &AddrModeInsts,
912                            const TargetLowering &TLI) {
913     ExtAddrMode Result;
914
915     bool Success =
916       AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
917                             MemoryInst, Result).MatchAddr(V, 0);
918     (void)Success; assert(Success && "Couldn't select *anything*?");
919     return Result;
920   }
921 private:
922   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
923   bool MatchAddr(Value *V, unsigned Depth);
924   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
925   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
926                                             ExtAddrMode &AMBefore,
927                                             ExtAddrMode &AMAfter);
928   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
929 };
930
931 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
932 /// Return true and update AddrMode if this addr mode is legal for the target,
933 /// false if not.
934 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
935                                              unsigned Depth) {
936   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
937   // mode.  Just process that directly.
938   if (Scale == 1)
939     return MatchAddr(ScaleReg, Depth);
940
941   // If the scale is 0, it takes nothing to add this.
942   if (Scale == 0)
943     return true;
944
945   // If we already have a scale of this value, we can add to it, otherwise, we
946   // need an available scale field.
947   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
948     return false;
949
950   ExtAddrMode TestAddrMode = AddrMode;
951
952   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
953   // [A+B + A*7] -> [B+A*8].
954   TestAddrMode.Scale += Scale;
955   TestAddrMode.ScaledReg = ScaleReg;
956
957   // If the new address isn't legal, bail out.
958   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
959     return false;
960
961   // It was legal, so commit it.
962   AddrMode = TestAddrMode;
963
964   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
965   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
966   // X*Scale + C*Scale to addr mode.
967   ConstantInt *CI = 0; Value *AddLHS = 0;
968   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
969       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
970     TestAddrMode.ScaledReg = AddLHS;
971     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
972
973     // If this addressing mode is legal, commit it and remember that we folded
974     // this instruction.
975     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
976       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
977       AddrMode = TestAddrMode;
978       return true;
979     }
980   }
981
982   // Otherwise, not (x+c)*scale, just return what we have.
983   return true;
984 }
985
986 /// MightBeFoldableInst - This is a little filter, which returns true if an
987 /// addressing computation involving I might be folded into a load/store
988 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
989 /// the set of instructions that MatchOperationAddr can.
990 static bool MightBeFoldableInst(Instruction *I) {
991   switch (I->getOpcode()) {
992   case Instruction::BitCast:
993     // Don't touch identity bitcasts.
994     if (I->getType() == I->getOperand(0)->getType())
995       return false;
996     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
997   case Instruction::PtrToInt:
998     // PtrToInt is always a noop, as we know that the int type is pointer sized.
999     return true;
1000   case Instruction::IntToPtr:
1001     // We know the input is intptr_t, so this is foldable.
1002     return true;
1003   case Instruction::Add:
1004     return true;
1005   case Instruction::Mul:
1006   case Instruction::Shl:
1007     // Can only handle X*C and X << C.
1008     return isa<ConstantInt>(I->getOperand(1));
1009   case Instruction::GetElementPtr:
1010     return true;
1011   default:
1012     return false;
1013   }
1014 }
1015
1016 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
1017 /// fold the operation into the addressing mode.  If so, update the addressing
1018 /// mode and return true, otherwise return false without modifying AddrMode.
1019 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
1020                                                unsigned Depth) {
1021   // Avoid exponential behavior on extremely deep expression trees.
1022   if (Depth >= 5) return false;
1023
1024   switch (Opcode) {
1025   case Instruction::PtrToInt:
1026     // PtrToInt is always a noop, as we know that the int type is pointer sized.
1027     return MatchAddr(AddrInst->getOperand(0), Depth);
1028   case Instruction::IntToPtr:
1029     // This inttoptr is a no-op if the integer type is pointer sized.
1030     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
1031         TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
1032       return MatchAddr(AddrInst->getOperand(0), Depth);
1033     return false;
1034   case Instruction::BitCast:
1035     // BitCast is always a noop, and we can handle it as long as it is
1036     // int->int or pointer->pointer (we don't want int<->fp or something).
1037     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1038          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1039         // Don't touch identity bitcasts.  These were probably put here by LSR,
1040         // and we don't want to mess around with them.  Assume it knows what it
1041         // is doing.
1042         AddrInst->getOperand(0)->getType() != AddrInst->getType())
1043       return MatchAddr(AddrInst->getOperand(0), Depth);
1044     return false;
1045   case Instruction::Add: {
1046     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
1047     ExtAddrMode BackupAddrMode = AddrMode;
1048     unsigned OldSize = AddrModeInsts.size();
1049     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1050         MatchAddr(AddrInst->getOperand(0), Depth+1))
1051       return true;
1052
1053     // Restore the old addr mode info.
1054     AddrMode = BackupAddrMode;
1055     AddrModeInsts.resize(OldSize);
1056
1057     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
1058     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1059         MatchAddr(AddrInst->getOperand(1), Depth+1))
1060       return true;
1061
1062     // Otherwise we definitely can't merge the ADD in.
1063     AddrMode = BackupAddrMode;
1064     AddrModeInsts.resize(OldSize);
1065     break;
1066   }
1067   //case Instruction::Or:
1068   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1069   //break;
1070   case Instruction::Mul:
1071   case Instruction::Shl: {
1072     // Can only handle X*C and X << C.
1073     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1074     if (!RHS) return false;
1075     int64_t Scale = RHS->getSExtValue();
1076     if (Opcode == Instruction::Shl)
1077       Scale = 1LL << Scale;
1078
1079     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1080   }
1081   case Instruction::GetElementPtr: {
1082     // Scan the GEP.  We check it if it contains constant offsets and at most
1083     // one variable offset.
1084     int VariableOperand = -1;
1085     unsigned VariableScale = 0;
1086
1087     int64_t ConstantOffset = 0;
1088     const DataLayout *TD = TLI.getDataLayout();
1089     gep_type_iterator GTI = gep_type_begin(AddrInst);
1090     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1091       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1092         const StructLayout *SL = TD->getStructLayout(STy);
1093         unsigned Idx =
1094           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1095         ConstantOffset += SL->getElementOffset(Idx);
1096       } else {
1097         uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1098         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1099           ConstantOffset += CI->getSExtValue()*TypeSize;
1100         } else if (TypeSize) {  // Scales of zero don't do anything.
1101           // We only allow one variable index at the moment.
1102           if (VariableOperand != -1)
1103             return false;
1104
1105           // Remember the variable index.
1106           VariableOperand = i;
1107           VariableScale = TypeSize;
1108         }
1109       }
1110     }
1111
1112     // A common case is for the GEP to only do a constant offset.  In this case,
1113     // just add it to the disp field and check validity.
1114     if (VariableOperand == -1) {
1115       AddrMode.BaseOffs += ConstantOffset;
1116       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1117         // Check to see if we can fold the base pointer in too.
1118         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1119           return true;
1120       }
1121       AddrMode.BaseOffs -= ConstantOffset;
1122       return false;
1123     }
1124
1125     // Save the valid addressing mode in case we can't match.
1126     ExtAddrMode BackupAddrMode = AddrMode;
1127     unsigned OldSize = AddrModeInsts.size();
1128
1129     // See if the scale and offset amount is valid for this target.
1130     AddrMode.BaseOffs += ConstantOffset;
1131
1132     // Match the base operand of the GEP.
1133     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1134       // If it couldn't be matched, just stuff the value in a register.
1135       if (AddrMode.HasBaseReg) {
1136         AddrMode = BackupAddrMode;
1137         AddrModeInsts.resize(OldSize);
1138         return false;
1139       }
1140       AddrMode.HasBaseReg = true;
1141       AddrMode.BaseReg = AddrInst->getOperand(0);
1142     }
1143
1144     // Match the remaining variable portion of the GEP.
1145     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1146                           Depth)) {
1147       // If it couldn't be matched, try stuffing the base into a register
1148       // instead of matching it, and retrying the match of the scale.
1149       AddrMode = BackupAddrMode;
1150       AddrModeInsts.resize(OldSize);
1151       if (AddrMode.HasBaseReg)
1152         return false;
1153       AddrMode.HasBaseReg = true;
1154       AddrMode.BaseReg = AddrInst->getOperand(0);
1155       AddrMode.BaseOffs += ConstantOffset;
1156       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1157                             VariableScale, Depth)) {
1158         // If even that didn't work, bail.
1159         AddrMode = BackupAddrMode;
1160         AddrModeInsts.resize(OldSize);
1161         return false;
1162       }
1163     }
1164
1165     return true;
1166   }
1167   }
1168   return false;
1169 }
1170
1171 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
1172 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
1173 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
1174 /// or intptr_t for the target.
1175 ///
1176 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
1177   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
1178     // Fold in immediates if legal for the target.
1179     AddrMode.BaseOffs += CI->getSExtValue();
1180     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1181       return true;
1182     AddrMode.BaseOffs -= CI->getSExtValue();
1183   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
1184     // If this is a global variable, try to fold it into the addressing mode.
1185     if (AddrMode.BaseGV == 0) {
1186       AddrMode.BaseGV = GV;
1187       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1188         return true;
1189       AddrMode.BaseGV = 0;
1190     }
1191   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
1192     ExtAddrMode BackupAddrMode = AddrMode;
1193     unsigned OldSize = AddrModeInsts.size();
1194
1195     // Check to see if it is possible to fold this operation.
1196     if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
1197       // Okay, it's possible to fold this.  Check to see if it is actually
1198       // *profitable* to do so.  We use a simple cost model to avoid increasing
1199       // register pressure too much.
1200       if (I->hasOneUse() ||
1201           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
1202         AddrModeInsts.push_back(I);
1203         return true;
1204       }
1205
1206       // It isn't profitable to do this, roll back.
1207       //cerr << "NOT FOLDING: " << *I;
1208       AddrMode = BackupAddrMode;
1209       AddrModeInsts.resize(OldSize);
1210     }
1211   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
1212     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
1213       return true;
1214   } else if (isa<ConstantPointerNull>(Addr)) {
1215     // Null pointer gets folded without affecting the addressing mode.
1216     return true;
1217   }
1218
1219   // Worse case, the target should support [reg] addressing modes. :)
1220   if (!AddrMode.HasBaseReg) {
1221     AddrMode.HasBaseReg = true;
1222     AddrMode.BaseReg = Addr;
1223     // Still check for legality in case the target supports [imm] but not [i+r].
1224     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1225       return true;
1226     AddrMode.HasBaseReg = false;
1227     AddrMode.BaseReg = 0;
1228   }
1229
1230   // If the base register is already taken, see if we can do [r+r].
1231   if (AddrMode.Scale == 0) {
1232     AddrMode.Scale = 1;
1233     AddrMode.ScaledReg = Addr;
1234     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1235       return true;
1236     AddrMode.Scale = 0;
1237     AddrMode.ScaledReg = 0;
1238   }
1239   // Couldn't match.
1240   return false;
1241 }
1242
1243 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
1244 /// inline asm call are due to memory operands.  If so, return true, otherwise
1245 /// return false.
1246 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
1247                                     const TargetLowering &TLI) {
1248   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
1249   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1250     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1251
1252     // Compute the constraint code and ConstraintType to use.
1253     TLI.ComputeConstraintToUse(OpInfo, SDValue());
1254
1255     // If this asm operand is our Value*, and if it isn't an indirect memory
1256     // operand, we can't fold it!
1257     if (OpInfo.CallOperandVal == OpVal &&
1258         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
1259          !OpInfo.isIndirect))
1260       return false;
1261   }
1262
1263   return true;
1264 }
1265
1266 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
1267 /// memory use.  If we find an obviously non-foldable instruction, return true.
1268 /// Add the ultimately found memory instructions to MemoryUses.
1269 static bool FindAllMemoryUses(Instruction *I,
1270                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
1271                               SmallPtrSet<Instruction*, 16> &ConsideredInsts,
1272                               const TargetLowering &TLI) {
1273   // If we already considered this instruction, we're done.
1274   if (!ConsideredInsts.insert(I))
1275     return false;
1276
1277   // If this is an obviously unfoldable instruction, bail out.
1278   if (!MightBeFoldableInst(I))
1279     return true;
1280
1281   // Loop over all the uses, recursively processing them.
1282   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1283        UI != E; ++UI) {
1284     User *U = *UI;
1285
1286     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
1287       MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
1288       continue;
1289     }
1290
1291     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1292       unsigned opNo = UI.getOperandNo();
1293       if (opNo == 0) return true; // Storing addr, not into addr.
1294       MemoryUses.push_back(std::make_pair(SI, opNo));
1295       continue;
1296     }
1297
1298     if (CallInst *CI = dyn_cast<CallInst>(U)) {
1299       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
1300       if (!IA) return true;
1301
1302       // If this is a memory operand, we're cool, otherwise bail out.
1303       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
1304         return true;
1305       continue;
1306     }
1307
1308     if (FindAllMemoryUses(cast<Instruction>(U), MemoryUses, ConsideredInsts,
1309                           TLI))
1310       return true;
1311   }
1312
1313   return false;
1314 }
1315
1316 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
1317 /// the use site that we're folding it into.  If so, there is no cost to
1318 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
1319 /// that we know are live at the instruction already.
1320 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
1321                                                    Value *KnownLive2) {
1322   // If Val is either of the known-live values, we know it is live!
1323   if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
1324     return true;
1325
1326   // All values other than instructions and arguments (e.g. constants) are live.
1327   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
1328
1329   // If Val is a constant sized alloca in the entry block, it is live, this is
1330   // true because it is just a reference to the stack/frame pointer, which is
1331   // live for the whole function.
1332   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
1333     if (AI->isStaticAlloca())
1334       return true;
1335
1336   // Check to see if this value is already used in the memory instruction's
1337   // block.  If so, it's already live into the block at the very least, so we
1338   // can reasonably fold it.
1339   return Val->isUsedInBasicBlock(MemoryInst->getParent());
1340 }
1341
1342 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
1343 /// mode of the machine to fold the specified instruction into a load or store
1344 /// that ultimately uses it.  However, the specified instruction has multiple
1345 /// uses.  Given this, it may actually increase register pressure to fold it
1346 /// into the load.  For example, consider this code:
1347 ///
1348 ///     X = ...
1349 ///     Y = X+1
1350 ///     use(Y)   -> nonload/store
1351 ///     Z = Y+1
1352 ///     load Z
1353 ///
1354 /// In this case, Y has multiple uses, and can be folded into the load of Z
1355 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
1356 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
1357 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
1358 /// number of computations either.
1359 ///
1360 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
1361 /// X was live across 'load Z' for other reasons, we actually *would* want to
1362 /// fold the addressing mode in the Z case.  This would make Y die earlier.
1363 bool AddressingModeMatcher::
1364 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1365                                      ExtAddrMode &AMAfter) {
1366   if (IgnoreProfitability) return true;
1367
1368   // AMBefore is the addressing mode before this instruction was folded into it,
1369   // and AMAfter is the addressing mode after the instruction was folded.  Get
1370   // the set of registers referenced by AMAfter and subtract out those
1371   // referenced by AMBefore: this is the set of values which folding in this
1372   // address extends the lifetime of.
1373   //
1374   // Note that there are only two potential values being referenced here,
1375   // BaseReg and ScaleReg (global addresses are always available, as are any
1376   // folded immediates).
1377   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
1378
1379   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1380   // lifetime wasn't extended by adding this instruction.
1381   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1382     BaseReg = 0;
1383   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1384     ScaledReg = 0;
1385
1386   // If folding this instruction (and it's subexprs) didn't extend any live
1387   // ranges, we're ok with it.
1388   if (BaseReg == 0 && ScaledReg == 0)
1389     return true;
1390
1391   // If all uses of this instruction are ultimately load/store/inlineasm's,
1392   // check to see if their addressing modes will include this instruction.  If
1393   // so, we can fold it into all uses, so it doesn't matter if it has multiple
1394   // uses.
1395   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1396   SmallPtrSet<Instruction*, 16> ConsideredInsts;
1397   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
1398     return false;  // Has a non-memory, non-foldable use!
1399
1400   // Now that we know that all uses of this instruction are part of a chain of
1401   // computation involving only operations that could theoretically be folded
1402   // into a memory use, loop over each of these uses and see if they could
1403   // *actually* fold the instruction.
1404   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1405   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1406     Instruction *User = MemoryUses[i].first;
1407     unsigned OpNo = MemoryUses[i].second;
1408
1409     // Get the access type of this use.  If the use isn't a pointer, we don't
1410     // know what it accesses.
1411     Value *Address = User->getOperand(OpNo);
1412     if (!Address->getType()->isPointerTy())
1413       return false;
1414     Type *AddressAccessTy = Address->getType()->getPointerElementType();
1415
1416     // Do a match against the root of this address, ignoring profitability. This
1417     // will tell us if the addressing mode for the memory operation will
1418     // *actually* cover the shared instruction.
1419     ExtAddrMode Result;
1420     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
1421                                   MemoryInst, Result);
1422     Matcher.IgnoreProfitability = true;
1423     bool Success = Matcher.MatchAddr(Address, 0);
1424     (void)Success; assert(Success && "Couldn't select *anything*?");
1425
1426     // If the match didn't cover I, then it won't be shared by it.
1427     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1428                   I) == MatchedAddrModeInsts.end())
1429       return false;
1430
1431     MatchedAddrModeInsts.clear();
1432   }
1433
1434   return true;
1435 }
1436
1437 } // end anonymous namespace
1438
1439 /// IsNonLocalValue - Return true if the specified values are defined in a
1440 /// different basic block than BB.
1441 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1442   if (Instruction *I = dyn_cast<Instruction>(V))
1443     return I->getParent() != BB;
1444   return false;
1445 }
1446
1447 /// OptimizeMemoryInst - Load and Store Instructions often have
1448 /// addressing modes that can do significant amounts of computation.  As such,
1449 /// instruction selection will try to get the load or store to do as much
1450 /// computation as possible for the program.  The problem is that isel can only
1451 /// see within a single block.  As such, we sink as much legal addressing mode
1452 /// stuff into the block as possible.
1453 ///
1454 /// This method is used to optimize both load/store and inline asms with memory
1455 /// operands.
1456 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
1457                                         Type *AccessTy) {
1458   Value *Repl = Addr;
1459
1460   // Try to collapse single-value PHI nodes.  This is necessary to undo
1461   // unprofitable PRE transformations.
1462   SmallVector<Value*, 8> worklist;
1463   SmallPtrSet<Value*, 16> Visited;
1464   worklist.push_back(Addr);
1465
1466   // Use a worklist to iteratively look through PHI nodes, and ensure that
1467   // the addressing mode obtained from the non-PHI roots of the graph
1468   // are equivalent.
1469   Value *Consensus = 0;
1470   unsigned NumUsesConsensus = 0;
1471   bool IsNumUsesConsensusValid = false;
1472   SmallVector<Instruction*, 16> AddrModeInsts;
1473   ExtAddrMode AddrMode;
1474   while (!worklist.empty()) {
1475     Value *V = worklist.back();
1476     worklist.pop_back();
1477
1478     // Break use-def graph loops.
1479     if (!Visited.insert(V)) {
1480       Consensus = 0;
1481       break;
1482     }
1483
1484     // For a PHI node, push all of its incoming values.
1485     if (PHINode *P = dyn_cast<PHINode>(V)) {
1486       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
1487         worklist.push_back(P->getIncomingValue(i));
1488       continue;
1489     }
1490
1491     // For non-PHIs, determine the addressing mode being computed.
1492     SmallVector<Instruction*, 16> NewAddrModeInsts;
1493     ExtAddrMode NewAddrMode =
1494       AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
1495                                    NewAddrModeInsts, *TLI);
1496
1497     // This check is broken into two cases with very similar code to avoid using
1498     // getNumUses() as much as possible. Some values have a lot of uses, so
1499     // calling getNumUses() unconditionally caused a significant compile-time
1500     // regression.
1501     if (!Consensus) {
1502       Consensus = V;
1503       AddrMode = NewAddrMode;
1504       AddrModeInsts = NewAddrModeInsts;
1505       continue;
1506     } else if (NewAddrMode == AddrMode) {
1507       if (!IsNumUsesConsensusValid) {
1508         NumUsesConsensus = Consensus->getNumUses();
1509         IsNumUsesConsensusValid = true;
1510       }
1511
1512       // Ensure that the obtained addressing mode is equivalent to that obtained
1513       // for all other roots of the PHI traversal.  Also, when choosing one
1514       // such root as representative, select the one with the most uses in order
1515       // to keep the cost modeling heuristics in AddressingModeMatcher
1516       // applicable.
1517       unsigned NumUses = V->getNumUses();
1518       if (NumUses > NumUsesConsensus) {
1519         Consensus = V;
1520         NumUsesConsensus = NumUses;
1521         AddrModeInsts = NewAddrModeInsts;
1522       }
1523       continue;
1524     }
1525
1526     Consensus = 0;
1527     break;
1528   }
1529
1530   // If the addressing mode couldn't be determined, or if multiple different
1531   // ones were determined, bail out now.
1532   if (!Consensus) return false;
1533
1534   // Check to see if any of the instructions supersumed by this addr mode are
1535   // non-local to I's BB.
1536   bool AnyNonLocal = false;
1537   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
1538     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
1539       AnyNonLocal = true;
1540       break;
1541     }
1542   }
1543
1544   // If all the instructions matched are already in this BB, don't do anything.
1545   if (!AnyNonLocal) {
1546     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
1547     return false;
1548   }
1549
1550   // Insert this computation right after this user.  Since our caller is
1551   // scanning from the top of the BB to the bottom, reuse of the expr are
1552   // guaranteed to happen later.
1553   IRBuilder<> Builder(MemoryInst);
1554
1555   // Now that we determined the addressing expression we want to use and know
1556   // that we have to sink it into this block.  Check to see if we have already
1557   // done this for some other load/store instr in this block.  If so, reuse the
1558   // computation.
1559   Value *&SunkAddr = SunkAddrs[Addr];
1560   if (SunkAddr) {
1561     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
1562                  << *MemoryInst);
1563     if (SunkAddr->getType() != Addr->getType())
1564       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
1565   } else {
1566     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
1567                  << *MemoryInst);
1568     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
1569     Value *Result = 0;
1570
1571     // Start with the base register. Do this first so that subsequent address
1572     // matching finds it last, which will prevent it from trying to match it
1573     // as the scaled value in case it happens to be a mul. That would be
1574     // problematic if we've sunk a different mul for the scale, because then
1575     // we'd end up sinking both muls.
1576     if (AddrMode.BaseReg) {
1577       Value *V = AddrMode.BaseReg;
1578       if (V->getType()->isPointerTy())
1579         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
1580       if (V->getType() != IntPtrTy)
1581         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
1582       Result = V;
1583     }
1584
1585     // Add the scale value.
1586     if (AddrMode.Scale) {
1587       Value *V = AddrMode.ScaledReg;
1588       if (V->getType() == IntPtrTy) {
1589         // done.
1590       } else if (V->getType()->isPointerTy()) {
1591         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
1592       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1593                  cast<IntegerType>(V->getType())->getBitWidth()) {
1594         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
1595       } else {
1596         V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
1597       }
1598       if (AddrMode.Scale != 1)
1599         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
1600                               "sunkaddr");
1601       if (Result)
1602         Result = Builder.CreateAdd(Result, V, "sunkaddr");
1603       else
1604         Result = V;
1605     }
1606
1607     // Add in the BaseGV if present.
1608     if (AddrMode.BaseGV) {
1609       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
1610       if (Result)
1611         Result = Builder.CreateAdd(Result, V, "sunkaddr");
1612       else
1613         Result = V;
1614     }
1615
1616     // Add in the Base Offset if present.
1617     if (AddrMode.BaseOffs) {
1618       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1619       if (Result)
1620         Result = Builder.CreateAdd(Result, V, "sunkaddr");
1621       else
1622         Result = V;
1623     }
1624
1625     if (Result == 0)
1626       SunkAddr = Constant::getNullValue(Addr->getType());
1627     else
1628       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
1629   }
1630
1631   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
1632
1633   // If we have no uses, recursively delete the value and all dead instructions
1634   // using it.
1635   if (Repl->use_empty()) {
1636     // This can cause recursive deletion, which can invalidate our iterator.
1637     // Use a WeakVH to hold onto it in case this happens.
1638     WeakVH IterHandle(CurInstIterator);
1639     BasicBlock *BB = CurInstIterator->getParent();
1640
1641     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
1642
1643     if (IterHandle != CurInstIterator) {
1644       // If the iterator instruction was recursively deleted, start over at the
1645       // start of the block.
1646       CurInstIterator = BB->begin();
1647       SunkAddrs.clear();
1648     }
1649   }
1650   ++NumMemoryInsts;
1651   return true;
1652 }
1653
1654 /// OptimizeInlineAsmInst - If there are any memory operands, use
1655 /// OptimizeMemoryInst to sink their address computing into the block when
1656 /// possible / profitable.
1657 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
1658   bool MadeChange = false;
1659
1660   TargetLowering::AsmOperandInfoVector
1661     TargetConstraints = TLI->ParseConstraints(CS);
1662   unsigned ArgNo = 0;
1663   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
1664     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
1665
1666     // Compute the constraint code and ConstraintType to use.
1667     TLI->ComputeConstraintToUse(OpInfo, SDValue());
1668
1669     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1670         OpInfo.isIndirect) {
1671       Value *OpVal = CS->getArgOperand(ArgNo++);
1672       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
1673     } else if (OpInfo.Type == InlineAsm::isInput)
1674       ArgNo++;
1675   }
1676
1677   return MadeChange;
1678 }
1679
1680 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
1681 /// basic block as the load, unless conditions are unfavorable. This allows
1682 /// SelectionDAG to fold the extend into the load.
1683 ///
1684 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
1685   // Look for a load being extended.
1686   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
1687   if (!LI) return false;
1688
1689   // If they're already in the same block, there's nothing to do.
1690   if (LI->getParent() == I->getParent())
1691     return false;
1692
1693   // If the load has other users and the truncate is not free, this probably
1694   // isn't worthwhile.
1695   if (!LI->hasOneUse() &&
1696       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1697               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1698       !TLI->isTruncateFree(I->getType(), LI->getType()))
1699     return false;
1700
1701   // Check whether the target supports casts folded into loads.
1702   unsigned LType;
1703   if (isa<ZExtInst>(I))
1704     LType = ISD::ZEXTLOAD;
1705   else {
1706     assert(isa<SExtInst>(I) && "Unexpected ext type!");
1707     LType = ISD::SEXTLOAD;
1708   }
1709   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1710     return false;
1711
1712   // Move the extend into the same block as the load, so that SelectionDAG
1713   // can fold it.
1714   I->removeFromParent();
1715   I->insertAfter(LI);
1716   ++NumExtsMoved;
1717   return true;
1718 }
1719
1720 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1721   BasicBlock *DefBB = I->getParent();
1722
1723   // If the result of a {s|z}ext and its source are both live out, rewrite all
1724   // other uses of the source with result of extension.
1725   Value *Src = I->getOperand(0);
1726   if (Src->hasOneUse())
1727     return false;
1728
1729   // Only do this xform if truncating is free.
1730   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1731     return false;
1732
1733   // Only safe to perform the optimization if the source is also defined in
1734   // this block.
1735   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1736     return false;
1737
1738   bool DefIsLiveOut = false;
1739   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1740        UI != E; ++UI) {
1741     Instruction *User = cast<Instruction>(*UI);
1742
1743     // Figure out which BB this ext is used in.
1744     BasicBlock *UserBB = User->getParent();
1745     if (UserBB == DefBB) continue;
1746     DefIsLiveOut = true;
1747     break;
1748   }
1749   if (!DefIsLiveOut)
1750     return false;
1751
1752   // Make sure none of the uses are PHI nodes.
1753   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1754        UI != E; ++UI) {
1755     Instruction *User = cast<Instruction>(*UI);
1756     BasicBlock *UserBB = User->getParent();
1757     if (UserBB == DefBB) continue;
1758     // Be conservative. We don't want this xform to end up introducing
1759     // reloads just before load / store instructions.
1760     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1761       return false;
1762   }
1763
1764   // InsertedTruncs - Only insert one trunc in each block once.
1765   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1766
1767   bool MadeChange = false;
1768   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1769        UI != E; ++UI) {
1770     Use &TheUse = UI.getUse();
1771     Instruction *User = cast<Instruction>(*UI);
1772
1773     // Figure out which BB this ext is used in.
1774     BasicBlock *UserBB = User->getParent();
1775     if (UserBB == DefBB) continue;
1776
1777     // Both src and def are live in this block. Rewrite the use.
1778     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1779
1780     if (!InsertedTrunc) {
1781       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1782       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1783     }
1784
1785     // Replace a use of the {s|z}ext source with a use of the result.
1786     TheUse = InsertedTrunc;
1787     ++NumExtUses;
1788     MadeChange = true;
1789   }
1790
1791   return MadeChange;
1792 }
1793
1794 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1795 /// turned into an explicit branch.
1796 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1797   // FIXME: This should use the same heuristics as IfConversion to determine
1798   // whether a select is better represented as a branch.  This requires that
1799   // branch probability metadata is preserved for the select, which is not the
1800   // case currently.
1801
1802   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1803
1804   // If the branch is predicted right, an out of order CPU can avoid blocking on
1805   // the compare.  Emit cmovs on compares with a memory operand as branches to
1806   // avoid stalls on the load from memory.  If the compare has more than one use
1807   // there's probably another cmov or setcc around so it's not worth emitting a
1808   // branch.
1809   if (!Cmp)
1810     return false;
1811
1812   Value *CmpOp0 = Cmp->getOperand(0);
1813   Value *CmpOp1 = Cmp->getOperand(1);
1814
1815   // We check that the memory operand has one use to avoid uses of the loaded
1816   // value directly after the compare, making branches unprofitable.
1817   return Cmp->hasOneUse() &&
1818          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1819           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1820 }
1821
1822
1823 /// If we have a SelectInst that will likely profit from branch prediction,
1824 /// turn it into a branch.
1825 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1826   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
1827
1828   // Can we convert the 'select' to CF ?
1829   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
1830     return false;
1831
1832   TargetLowering::SelectSupportKind SelectKind;
1833   if (VectorCond)
1834     SelectKind = TargetLowering::VectorMaskSelect;
1835   else if (SI->getType()->isVectorTy())
1836     SelectKind = TargetLowering::ScalarCondVectorVal;
1837   else
1838     SelectKind = TargetLowering::ScalarValSelect;
1839
1840   // Do we have efficient codegen support for this kind of 'selects' ?
1841   if (TLI->isSelectSupported(SelectKind)) {
1842     // We have efficient codegen support for the select instruction.
1843     // Check if it is profitable to keep this 'select'.
1844     if (!TLI->isPredictableSelectExpensive() ||
1845         !isFormingBranchFromSelectProfitable(SI))
1846       return false;
1847   }
1848
1849   ModifiedDT = true;
1850
1851   // First, we split the block containing the select into 2 blocks.
1852   BasicBlock *StartBlock = SI->getParent();
1853   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1854   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1855
1856   // Create a new block serving as the landing pad for the branch.
1857   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1858                                              NextBlock->getParent(), NextBlock);
1859
1860   // Move the unconditional branch from the block with the select in it into our
1861   // landing pad block.
1862   StartBlock->getTerminator()->eraseFromParent();
1863   BranchInst::Create(NextBlock, SmallBlock);
1864
1865   // Insert the real conditional branch based on the original condition.
1866   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1867
1868   // The select itself is replaced with a PHI Node.
1869   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1870   PN->takeName(SI);
1871   PN->addIncoming(SI->getTrueValue(), StartBlock);
1872   PN->addIncoming(SI->getFalseValue(), SmallBlock);
1873   SI->replaceAllUsesWith(PN);
1874   SI->eraseFromParent();
1875
1876   // Instruct OptimizeBlock to skip to the next block.
1877   CurInstIterator = StartBlock->end();
1878   ++NumSelectsExpanded;
1879   return true;
1880 }
1881
1882 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1883   if (PHINode *P = dyn_cast<PHINode>(I)) {
1884     // It is possible for very late stage optimizations (such as SimplifyCFG)
1885     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
1886     // trivial PHI, go ahead and zap it here.
1887     if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
1888                                        TLInfo, DT)) {
1889       P->replaceAllUsesWith(V);
1890       P->eraseFromParent();
1891       ++NumPHIsElim;
1892       return true;
1893     }
1894     return false;
1895   }
1896
1897   if (CastInst *CI = dyn_cast<CastInst>(I)) {
1898     // If the source of the cast is a constant, then this should have
1899     // already been constant folded.  The only reason NOT to constant fold
1900     // it is if something (e.g. LSR) was careful to place the constant
1901     // evaluation in a block other than then one that uses it (e.g. to hoist
1902     // the address of globals out of a loop).  If this is the case, we don't
1903     // want to forward-subst the cast.
1904     if (isa<Constant>(CI->getOperand(0)))
1905       return false;
1906
1907     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1908       return true;
1909
1910     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1911       bool MadeChange = MoveExtToFormExtLoad(I);
1912       return MadeChange | OptimizeExtUses(I);
1913     }
1914     return false;
1915   }
1916
1917   if (CmpInst *CI = dyn_cast<CmpInst>(I))
1918     if (!TLI || !TLI->hasMultipleConditionRegisters())
1919       return OptimizeCmpExpression(CI);
1920
1921   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1922     if (TLI)
1923       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1924     return false;
1925   }
1926
1927   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1928     if (TLI)
1929       return OptimizeMemoryInst(I, SI->getOperand(1),
1930                                 SI->getOperand(0)->getType());
1931     return false;
1932   }
1933
1934   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1935     if (GEPI->hasAllZeroIndices()) {
1936       /// The GEP operand must be a pointer, so must its result -> BitCast
1937       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1938                                         GEPI->getName(), GEPI);
1939       GEPI->replaceAllUsesWith(NC);
1940       GEPI->eraseFromParent();
1941       ++NumGEPsElim;
1942       OptimizeInst(NC);
1943       return true;
1944     }
1945     return false;
1946   }
1947
1948   if (CallInst *CI = dyn_cast<CallInst>(I))
1949     return OptimizeCallInst(CI);
1950
1951   if (SelectInst *SI = dyn_cast<SelectInst>(I))
1952     return OptimizeSelectInst(SI);
1953
1954   return false;
1955 }
1956
1957 // In this pass we look for GEP and cast instructions that are used
1958 // across basic blocks and rewrite them to improve basic-block-at-a-time
1959 // selection.
1960 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1961   SunkAddrs.clear();
1962   bool MadeChange = false;
1963
1964   CurInstIterator = BB.begin();
1965   while (CurInstIterator != BB.end())
1966     MadeChange |= OptimizeInst(CurInstIterator++);
1967
1968   MadeChange |= DupRetToEnableTailCallOpts(&BB);
1969
1970   return MadeChange;
1971 }
1972
1973 // llvm.dbg.value is far away from the value then iSel may not be able
1974 // handle it properly. iSel will drop llvm.dbg.value if it can not
1975 // find a node corresponding to the value.
1976 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1977   bool MadeChange = false;
1978   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1979     Instruction *PrevNonDbgInst = NULL;
1980     for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1981       Instruction *Insn = BI; ++BI;
1982       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1983       if (!DVI) {
1984         PrevNonDbgInst = Insn;
1985         continue;
1986       }
1987
1988       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1989       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1990         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1991         DVI->removeFromParent();
1992         if (isa<PHINode>(VI))
1993           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1994         else
1995           DVI->insertAfter(VI);
1996         MadeChange = true;
1997         ++NumDbgValueMoved;
1998       }
1999     }
2000   }
2001   return MadeChange;
2002 }