cbc089ab788ea9ad72fdf857f49e9dd9ff515905
[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/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/IRBuilder.h"
22 #include "llvm/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/IntrinsicInst.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/DenseMap.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/InstructionSimplify.h"
31 #include "llvm/Analysis/ProfileInfo.h"
32 #include "llvm/Assembly/Writer.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/PatternMatch.h"
38 #include "llvm/Support/ValueHandle.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetData.h"
41 #include "llvm/Target/TargetLibraryInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/BuildLibCalls.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 // FIXME: Remove this abomination once all of the tests pass without it!
70 static cl::opt<bool> DisableDeleteDeadBlocks(
71   "disable-cgp-delete-dead-blocks", cl::Hidden, cl::init(false),
72   cl::desc("Disable deleting dead blocks in CodeGenPrepare"));
73
74 static cl::opt<bool> DisableSelectToBranch(
75   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
76   cl::desc("Disable select to branch conversion."));
77
78 namespace {
79   class CodeGenPrepare : public FunctionPass {
80     /// TLI - Keep a pointer of a TargetLowering to consult for determining
81     /// transformation profitability.
82     const TargetLowering *TLI;
83     const TargetLibraryInfo *TLInfo;
84     DominatorTree *DT;
85     ProfileInfo *PFI;
86     
87     /// CurInstIterator - As we scan instructions optimizing them, this is the
88     /// next instruction to optimize.  Xforms that can invalidate this should
89     /// update it.
90     BasicBlock::iterator CurInstIterator;
91
92     /// Keeps track of non-local addresses that have been sunk into a block.
93     /// This allows us to avoid inserting duplicate code for blocks with
94     /// multiple load/stores of the same address.
95     DenseMap<Value*, Value*> SunkAddrs;
96
97     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
98     /// be updated.
99     bool ModifiedDT;
100
101     /// OptSize - True if optimizing for size.
102     bool OptSize;
103
104   public:
105     static char ID; // Pass identification, replacement for typeid
106     explicit CodeGenPrepare(const TargetLowering *tli = 0)
107       : FunctionPass(ID), TLI(tli) {
108         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
109       }
110     bool runOnFunction(Function &F);
111
112     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
113       AU.addPreserved<DominatorTree>();
114       AU.addPreserved<ProfileInfo>();
115       AU.addRequired<TargetLibraryInfo>();
116     }
117
118   private:
119     bool EliminateMostlyEmptyBlocks(Function &F);
120     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
121     void EliminateMostlyEmptyBlock(BasicBlock *BB);
122     bool OptimizeBlock(BasicBlock &BB);
123     bool OptimizeInst(Instruction *I);
124     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
125     bool OptimizeInlineAsmInst(CallInst *CS);
126     bool OptimizeCallInst(CallInst *CI);
127     bool MoveExtToFormExtLoad(Instruction *I);
128     bool OptimizeExtUses(Instruction *I);
129     bool OptimizeSelectInst(SelectInst *SI);
130     bool DupRetToEnableTailCallOpts(ReturnInst *RI);
131     bool PlaceDbgValues(Function &F);
132   };
133 }
134
135 char CodeGenPrepare::ID = 0;
136 INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
137                 "Optimize for code generation", false, false)
138 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
139 INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
140                 "Optimize for code generation", false, false)
141
142 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
143   return new CodeGenPrepare(TLI);
144 }
145
146 bool CodeGenPrepare::runOnFunction(Function &F) {
147   bool EverMadeChange = false;
148
149   ModifiedDT = false;
150   TLInfo = &getAnalysis<TargetLibraryInfo>();
151   DT = getAnalysisIfAvailable<DominatorTree>();
152   PFI = getAnalysisIfAvailable<ProfileInfo>();
153   OptSize = F.hasFnAttr(Attribute::OptimizeForSize);
154
155   // First pass, eliminate blocks that contain only PHI nodes and an
156   // unconditional branch.
157   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
158
159   // llvm.dbg.value is far away from the value then iSel may not be able
160   // handle it properly. iSel will drop llvm.dbg.value if it can not 
161   // find a node corresponding to the value.
162   EverMadeChange |= PlaceDbgValues(F);
163
164   bool MadeChange = true;
165   while (MadeChange) {
166     MadeChange = false;
167     for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
168       BasicBlock *BB = I++;
169       MadeChange |= OptimizeBlock(*BB);
170     }
171     EverMadeChange |= MadeChange;
172   }
173
174   SunkAddrs.clear();
175
176   if (!DisableBranchOpts) {
177     MadeChange = false;
178     SmallPtrSet<BasicBlock*, 8> WorkList;
179     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
180       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
181       MadeChange |= ConstantFoldTerminator(BB, true);
182       if (!MadeChange) continue;
183
184       for (SmallVectorImpl<BasicBlock*>::iterator
185              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
186         if (pred_begin(*II) == pred_end(*II))
187           WorkList.insert(*II);
188     }
189
190     if (!DisableDeleteDeadBlocks)
191       for (SmallPtrSet<BasicBlock*, 8>::iterator
192              I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
193         DeleteDeadBlock(*I);
194
195     if (MadeChange)
196       ModifiedDT = true;
197     EverMadeChange |= MadeChange;
198   }
199
200   if (ModifiedDT && DT)
201     DT->DT->recalculate(F);
202
203   return EverMadeChange;
204 }
205
206 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
207 /// debug info directives, and an unconditional branch.  Passes before isel
208 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
209 /// isel.  Start by eliminating these blocks so we can split them the way we
210 /// want them.
211 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
212   bool MadeChange = false;
213   // Note that this intentionally skips the entry block.
214   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
215     BasicBlock *BB = I++;
216
217     // If this block doesn't end with an uncond branch, ignore it.
218     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
219     if (!BI || !BI->isUnconditional())
220       continue;
221
222     // If the instruction before the branch (skipping debug info) isn't a phi
223     // node, then other stuff is happening here.
224     BasicBlock::iterator BBI = BI;
225     if (BBI != BB->begin()) {
226       --BBI;
227       while (isa<DbgInfoIntrinsic>(BBI)) {
228         if (BBI == BB->begin())
229           break;
230         --BBI;
231       }
232       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
233         continue;
234     }
235
236     // Do not break infinite loops.
237     BasicBlock *DestBB = BI->getSuccessor(0);
238     if (DestBB == BB)
239       continue;
240
241     if (!CanMergeBlocks(BB, DestBB))
242       continue;
243
244     EliminateMostlyEmptyBlock(BB);
245     MadeChange = true;
246   }
247   return MadeChange;
248 }
249
250 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
251 /// single uncond branch between them, and BB contains no other non-phi
252 /// instructions.
253 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
254                                     const BasicBlock *DestBB) const {
255   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
256   // the successor.  If there are more complex condition (e.g. preheaders),
257   // don't mess around with them.
258   BasicBlock::const_iterator BBI = BB->begin();
259   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
260     for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
261          UI != E; ++UI) {
262       const Instruction *User = cast<Instruction>(*UI);
263       if (User->getParent() != DestBB || !isa<PHINode>(User))
264         return false;
265       // If User is inside DestBB block and it is a PHINode then check
266       // incoming value. If incoming value is not from BB then this is
267       // a complex condition (e.g. preheaders) we want to avoid here.
268       if (User->getParent() == DestBB) {
269         if (const PHINode *UPN = dyn_cast<PHINode>(User))
270           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
271             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
272             if (Insn && Insn->getParent() == BB &&
273                 Insn->getParent() != UPN->getIncomingBlock(I))
274               return false;
275           }
276       }
277     }
278   }
279
280   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
281   // and DestBB may have conflicting incoming values for the block.  If so, we
282   // can't merge the block.
283   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
284   if (!DestBBPN) return true;  // no conflict.
285
286   // Collect the preds of BB.
287   SmallPtrSet<const BasicBlock*, 16> BBPreds;
288   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
289     // It is faster to get preds from a PHI than with pred_iterator.
290     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
291       BBPreds.insert(BBPN->getIncomingBlock(i));
292   } else {
293     BBPreds.insert(pred_begin(BB), pred_end(BB));
294   }
295
296   // Walk the preds of DestBB.
297   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
298     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
299     if (BBPreds.count(Pred)) {   // Common predecessor?
300       BBI = DestBB->begin();
301       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
302         const Value *V1 = PN->getIncomingValueForBlock(Pred);
303         const Value *V2 = PN->getIncomingValueForBlock(BB);
304
305         // If V2 is a phi node in BB, look up what the mapped value will be.
306         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
307           if (V2PN->getParent() == BB)
308             V2 = V2PN->getIncomingValueForBlock(Pred);
309
310         // If there is a conflict, bail out.
311         if (V1 != V2) return false;
312       }
313     }
314   }
315
316   return true;
317 }
318
319
320 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
321 /// an unconditional branch in it.
322 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
323   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
324   BasicBlock *DestBB = BI->getSuccessor(0);
325
326   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
327
328   // If the destination block has a single pred, then this is a trivial edge,
329   // just collapse it.
330   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
331     if (SinglePred != DestBB) {
332       // Remember if SinglePred was the entry block of the function.  If so, we
333       // will need to move BB back to the entry position.
334       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
335       MergeBasicBlockIntoOnlyPred(DestBB, this);
336
337       if (isEntry && BB != &BB->getParent()->getEntryBlock())
338         BB->moveBefore(&BB->getParent()->getEntryBlock());
339       
340       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
341       return;
342     }
343   }
344
345   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
346   // to handle the new incoming edges it is about to have.
347   PHINode *PN;
348   for (BasicBlock::iterator BBI = DestBB->begin();
349        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
350     // Remove the incoming value for BB, and remember it.
351     Value *InVal = PN->removeIncomingValue(BB, false);
352
353     // Two options: either the InVal is a phi node defined in BB or it is some
354     // value that dominates BB.
355     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
356     if (InValPhi && InValPhi->getParent() == BB) {
357       // Add all of the input values of the input PHI as inputs of this phi.
358       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
359         PN->addIncoming(InValPhi->getIncomingValue(i),
360                         InValPhi->getIncomingBlock(i));
361     } else {
362       // Otherwise, add one instance of the dominating value for each edge that
363       // we will be adding.
364       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
365         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
366           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
367       } else {
368         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
369           PN->addIncoming(InVal, *PI);
370       }
371     }
372   }
373
374   // The PHIs are now updated, change everything that refers to BB to use
375   // DestBB and remove BB.
376   BB->replaceAllUsesWith(DestBB);
377   if (DT && !ModifiedDT) {
378     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
379     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
380     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
381     DT->changeImmediateDominator(DestBB, NewIDom);
382     DT->eraseNode(BB);
383   }
384   if (PFI) {
385     PFI->replaceAllUses(BB, DestBB);
386     PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
387   }
388   BB->eraseFromParent();
389   ++NumBlocksElim;
390
391   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
392 }
393
394 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
395 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
396 /// sink it into user blocks to reduce the number of virtual
397 /// registers that must be created and coalesced.
398 ///
399 /// Return true if any changes are made.
400 ///
401 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
402   // If this is a noop copy,
403   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
404   EVT DstVT = TLI.getValueType(CI->getType());
405
406   // This is an fp<->int conversion?
407   if (SrcVT.isInteger() != DstVT.isInteger())
408     return false;
409
410   // If this is an extension, it will be a zero or sign extension, which
411   // isn't a noop.
412   if (SrcVT.bitsLT(DstVT)) return false;
413
414   // If these values will be promoted, find out what they will be promoted
415   // to.  This helps us consider truncates on PPC as noop copies when they
416   // are.
417   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
418       TargetLowering::TypePromoteInteger)
419     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
420   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
421       TargetLowering::TypePromoteInteger)
422     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
423
424   // If, after promotion, these are the same types, this is a noop copy.
425   if (SrcVT != DstVT)
426     return false;
427
428   BasicBlock *DefBB = CI->getParent();
429
430   /// InsertedCasts - Only insert a cast in each block once.
431   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
432
433   bool MadeChange = false;
434   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
435        UI != E; ) {
436     Use &TheUse = UI.getUse();
437     Instruction *User = cast<Instruction>(*UI);
438
439     // Figure out which BB this cast is used in.  For PHI's this is the
440     // appropriate predecessor block.
441     BasicBlock *UserBB = User->getParent();
442     if (PHINode *PN = dyn_cast<PHINode>(User)) {
443       UserBB = PN->getIncomingBlock(UI);
444     }
445
446     // Preincrement use iterator so we don't invalidate it.
447     ++UI;
448
449     // If this user is in the same block as the cast, don't change the cast.
450     if (UserBB == DefBB) continue;
451
452     // If we have already inserted a cast into this block, use it.
453     CastInst *&InsertedCast = InsertedCasts[UserBB];
454
455     if (!InsertedCast) {
456       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
457       InsertedCast =
458         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
459                          InsertPt);
460       MadeChange = true;
461     }
462
463     // Replace a use of the cast with a use of the new cast.
464     TheUse = InsertedCast;
465     ++NumCastUses;
466   }
467
468   // If we removed all uses, nuke the cast.
469   if (CI->use_empty()) {
470     CI->eraseFromParent();
471     MadeChange = true;
472   }
473
474   return MadeChange;
475 }
476
477 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
478 /// the number of virtual registers that must be created and coalesced.  This is
479 /// a clear win except on targets with multiple condition code registers
480 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
481 ///
482 /// Return true if any changes are made.
483 static bool OptimizeCmpExpression(CmpInst *CI) {
484   BasicBlock *DefBB = CI->getParent();
485
486   /// InsertedCmp - Only insert a cmp in each block once.
487   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
488
489   bool MadeChange = false;
490   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
491        UI != E; ) {
492     Use &TheUse = UI.getUse();
493     Instruction *User = cast<Instruction>(*UI);
494
495     // Preincrement use iterator so we don't invalidate it.
496     ++UI;
497
498     // Don't bother for PHI nodes.
499     if (isa<PHINode>(User))
500       continue;
501
502     // Figure out which BB this cmp is used in.
503     BasicBlock *UserBB = User->getParent();
504
505     // If this user is in the same block as the cmp, don't change the cmp.
506     if (UserBB == DefBB) continue;
507
508     // If we have already inserted a cmp into this block, use it.
509     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
510
511     if (!InsertedCmp) {
512       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
513       InsertedCmp =
514         CmpInst::Create(CI->getOpcode(),
515                         CI->getPredicate(),  CI->getOperand(0),
516                         CI->getOperand(1), "", InsertPt);
517       MadeChange = true;
518     }
519
520     // Replace a use of the cmp with a use of the new cmp.
521     TheUse = InsertedCmp;
522     ++NumCmpUses;
523   }
524
525   // If we removed all uses, nuke the cmp.
526   if (CI->use_empty())
527     CI->eraseFromParent();
528
529   return MadeChange;
530 }
531
532 namespace {
533 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
534 protected:
535   void replaceCall(Value *With) {
536     CI->replaceAllUsesWith(With);
537     CI->eraseFromParent();
538   }
539   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
540       if (ConstantInt *SizeCI =
541                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
542         return SizeCI->isAllOnesValue();
543     return false;
544   }
545 };
546 } // end anonymous namespace
547
548 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
549   BasicBlock *BB = CI->getParent();
550   
551   // Lower inline assembly if we can.
552   // If we found an inline asm expession, and if the target knows how to
553   // lower it to normal LLVM code, do so now.
554   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
555     if (TLI->ExpandInlineAsm(CI)) {
556       // Avoid invalidating the iterator.
557       CurInstIterator = BB->begin();
558       // Avoid processing instructions out of order, which could cause
559       // reuse before a value is defined.
560       SunkAddrs.clear();
561       return true;
562     }
563     // Sink address computing for memory operands into the block.
564     if (OptimizeInlineAsmInst(CI))
565       return true;
566   }
567   
568   // Lower all uses of llvm.objectsize.*
569   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
570   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
571     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
572     Type *ReturnTy = CI->getType();
573     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);    
574     
575     // Substituting this can cause recursive simplifications, which can
576     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
577     // happens.
578     WeakVH IterHandle(CurInstIterator);
579     
580     replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getTargetData() : 0,
581                                   TLInfo, ModifiedDT ? 0 : DT);
582
583     // If the iterator instruction was recursively deleted, start over at the
584     // start of the block.
585     if (IterHandle != CurInstIterator) {
586       CurInstIterator = BB->begin();
587       SunkAddrs.clear();
588     }
589     return true;
590   }
591
592   if (II && TLI) {
593     SmallVector<Value*, 2> PtrOps;
594     Type *AccessTy;
595     if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
596       while (!PtrOps.empty())
597         if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
598           return true;
599   }
600
601   // From here on out we're working with named functions.
602   if (CI->getCalledFunction() == 0) return false;
603
604   // We'll need TargetData from here on out.
605   const TargetData *TD = TLI ? TLI->getTargetData() : 0;
606   if (!TD) return false;
607   
608   // Lower all default uses of _chk calls.  This is very similar
609   // to what InstCombineCalls does, but here we are only lowering calls
610   // that have the default "don't know" as the objectsize.  Anything else
611   // should be left alone.
612   CodeGenPrepareFortifiedLibCalls Simplifier;
613   return Simplifier.fold(CI, TD);
614 }
615
616 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
617 /// instructions to the predecessor to enable tail call optimizations. The
618 /// case it is currently looking for is:
619 /// bb0:
620 ///   %tmp0 = tail call i32 @f0()
621 ///   br label %return
622 /// bb1:
623 ///   %tmp1 = tail call i32 @f1()
624 ///   br label %return
625 /// bb2:
626 ///   %tmp2 = tail call i32 @f2()
627 ///   br label %return
628 /// return:
629 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
630 ///   ret i32 %retval
631 ///
632 /// =>
633 ///
634 /// bb0:
635 ///   %tmp0 = tail call i32 @f0()
636 ///   ret i32 %tmp0
637 /// bb1:
638 ///   %tmp1 = tail call i32 @f1()
639 ///   ret i32 %tmp1
640 /// bb2:
641 ///   %tmp2 = tail call i32 @f2()
642 ///   ret i32 %tmp2
643 ///
644 bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
645   if (!TLI)
646     return false;
647
648   Value *V = RI->getReturnValue();
649   PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
650   if (V && !PN)
651     return false;
652
653   BasicBlock *BB = RI->getParent();
654   if (PN && PN->getParent() != BB)
655     return false;
656
657   // It's not safe to eliminate the sign / zero extension of the return value.
658   // See llvm::isInTailCallPosition().
659   const Function *F = BB->getParent();
660   Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
661   if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
662     return false;
663
664   // Make sure there are no instructions between the PHI and return, or that the
665   // return is the first instruction in the block.
666   if (PN) {
667     BasicBlock::iterator BI = BB->begin();
668     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
669     if (&*BI != RI)
670       return false;
671   } else {
672     BasicBlock::iterator BI = BB->begin();
673     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
674     if (&*BI != RI)
675       return false;
676   }
677
678   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
679   /// call.
680   SmallVector<CallInst*, 4> TailCalls;
681   if (PN) {
682     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
683       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
684       // Make sure the phi value is indeed produced by the tail call.
685       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
686           TLI->mayBeEmittedAsTailCall(CI))
687         TailCalls.push_back(CI);
688     }
689   } else {
690     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
691     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
692       if (!VisitedBBs.insert(*PI))
693         continue;
694
695       BasicBlock::InstListType &InstList = (*PI)->getInstList();
696       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
697       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
698       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
699       if (RI == RE)
700         continue;
701
702       CallInst *CI = dyn_cast<CallInst>(&*RI);
703       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
704         TailCalls.push_back(CI);
705     }
706   }
707
708   bool Changed = false;
709   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
710     CallInst *CI = TailCalls[i];
711     CallSite CS(CI);
712
713     // Conservatively require the attributes of the call to match those of the
714     // return. Ignore noalias because it doesn't affect the call sequence.
715     Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
716     if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
717       continue;
718
719     // Make sure the call instruction is followed by an unconditional branch to
720     // the return block.
721     BasicBlock *CallBB = CI->getParent();
722     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
723     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
724       continue;
725
726     // Duplicate the return into CallBB.
727     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
728     ModifiedDT = Changed = true;
729     ++NumRetsDup;
730   }
731
732   // If we eliminated all predecessors of the block, delete the block now.
733   if (Changed && pred_begin(BB) == pred_end(BB))
734     BB->eraseFromParent();
735
736   return Changed;
737 }
738
739 //===----------------------------------------------------------------------===//
740 // Memory Optimization
741 //===----------------------------------------------------------------------===//
742
743 /// IsNonLocalValue - Return true if the specified values are defined in a
744 /// different basic block than BB.
745 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
746   if (Instruction *I = dyn_cast<Instruction>(V))
747     return I->getParent() != BB;
748   return false;
749 }
750
751 /// OptimizeMemoryInst - Load and Store Instructions often have
752 /// addressing modes that can do significant amounts of computation.  As such,
753 /// instruction selection will try to get the load or store to do as much
754 /// computation as possible for the program.  The problem is that isel can only
755 /// see within a single block.  As such, we sink as much legal addressing mode
756 /// stuff into the block as possible.
757 ///
758 /// This method is used to optimize both load/store and inline asms with memory
759 /// operands.
760 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
761                                         Type *AccessTy) {
762   Value *Repl = Addr;
763   
764   // Try to collapse single-value PHI nodes.  This is necessary to undo 
765   // unprofitable PRE transformations.
766   SmallVector<Value*, 8> worklist;
767   SmallPtrSet<Value*, 16> Visited;
768   worklist.push_back(Addr);
769   
770   // Use a worklist to iteratively look through PHI nodes, and ensure that
771   // the addressing mode obtained from the non-PHI roots of the graph
772   // are equivalent.
773   Value *Consensus = 0;
774   unsigned NumUsesConsensus = 0;
775   bool IsNumUsesConsensusValid = false;
776   SmallVector<Instruction*, 16> AddrModeInsts;
777   ExtAddrMode AddrMode;
778   while (!worklist.empty()) {
779     Value *V = worklist.back();
780     worklist.pop_back();
781     
782     // Break use-def graph loops.
783     if (!Visited.insert(V)) {
784       Consensus = 0;
785       break;
786     }
787     
788     // For a PHI node, push all of its incoming values.
789     if (PHINode *P = dyn_cast<PHINode>(V)) {
790       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
791         worklist.push_back(P->getIncomingValue(i));
792       continue;
793     }
794     
795     // For non-PHIs, determine the addressing mode being computed.
796     SmallVector<Instruction*, 16> NewAddrModeInsts;
797     ExtAddrMode NewAddrMode =
798       AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
799                                    NewAddrModeInsts, *TLI);
800
801     // This check is broken into two cases with very similar code to avoid using
802     // getNumUses() as much as possible. Some values have a lot of uses, so
803     // calling getNumUses() unconditionally caused a significant compile-time
804     // regression.
805     if (!Consensus) {
806       Consensus = V;
807       AddrMode = NewAddrMode;
808       AddrModeInsts = NewAddrModeInsts;
809       continue;
810     } else if (NewAddrMode == AddrMode) {
811       if (!IsNumUsesConsensusValid) {
812         NumUsesConsensus = Consensus->getNumUses();
813         IsNumUsesConsensusValid = true;
814       }
815
816       // Ensure that the obtained addressing mode is equivalent to that obtained
817       // for all other roots of the PHI traversal.  Also, when choosing one
818       // such root as representative, select the one with the most uses in order
819       // to keep the cost modeling heuristics in AddressingModeMatcher
820       // applicable.
821       unsigned NumUses = V->getNumUses();
822       if (NumUses > NumUsesConsensus) {
823         Consensus = V;
824         NumUsesConsensus = NumUses;
825         AddrModeInsts = NewAddrModeInsts;
826       }
827       continue;
828     }
829     
830     Consensus = 0;
831     break;
832   }
833   
834   // If the addressing mode couldn't be determined, or if multiple different
835   // ones were determined, bail out now.
836   if (!Consensus) return false;
837   
838   // Check to see if any of the instructions supersumed by this addr mode are
839   // non-local to I's BB.
840   bool AnyNonLocal = false;
841   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
842     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
843       AnyNonLocal = true;
844       break;
845     }
846   }
847
848   // If all the instructions matched are already in this BB, don't do anything.
849   if (!AnyNonLocal) {
850     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
851     return false;
852   }
853
854   // Insert this computation right after this user.  Since our caller is
855   // scanning from the top of the BB to the bottom, reuse of the expr are
856   // guaranteed to happen later.
857   IRBuilder<> Builder(MemoryInst);
858
859   // Now that we determined the addressing expression we want to use and know
860   // that we have to sink it into this block.  Check to see if we have already
861   // done this for some other load/store instr in this block.  If so, reuse the
862   // computation.
863   Value *&SunkAddr = SunkAddrs[Addr];
864   if (SunkAddr) {
865     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
866                  << *MemoryInst);
867     if (SunkAddr->getType() != Addr->getType())
868       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
869   } else {
870     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
871                  << *MemoryInst);
872     Type *IntPtrTy =
873           TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
874
875     Value *Result = 0;
876
877     // Start with the base register. Do this first so that subsequent address
878     // matching finds it last, which will prevent it from trying to match it
879     // as the scaled value in case it happens to be a mul. That would be
880     // problematic if we've sunk a different mul for the scale, because then
881     // we'd end up sinking both muls.
882     if (AddrMode.BaseReg) {
883       Value *V = AddrMode.BaseReg;
884       if (V->getType()->isPointerTy())
885         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
886       if (V->getType() != IntPtrTy)
887         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
888       Result = V;
889     }
890
891     // Add the scale value.
892     if (AddrMode.Scale) {
893       Value *V = AddrMode.ScaledReg;
894       if (V->getType() == IntPtrTy) {
895         // done.
896       } else if (V->getType()->isPointerTy()) {
897         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
898       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
899                  cast<IntegerType>(V->getType())->getBitWidth()) {
900         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
901       } else {
902         V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
903       }
904       if (AddrMode.Scale != 1)
905         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
906                               "sunkaddr");
907       if (Result)
908         Result = Builder.CreateAdd(Result, V, "sunkaddr");
909       else
910         Result = V;
911     }
912
913     // Add in the BaseGV if present.
914     if (AddrMode.BaseGV) {
915       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
916       if (Result)
917         Result = Builder.CreateAdd(Result, V, "sunkaddr");
918       else
919         Result = V;
920     }
921
922     // Add in the Base Offset if present.
923     if (AddrMode.BaseOffs) {
924       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
925       if (Result)
926         Result = Builder.CreateAdd(Result, V, "sunkaddr");
927       else
928         Result = V;
929     }
930
931     if (Result == 0)
932       SunkAddr = Constant::getNullValue(Addr->getType());
933     else
934       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
935   }
936
937   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
938
939   // If we have no uses, recursively delete the value and all dead instructions
940   // using it.
941   if (Repl->use_empty()) {
942     // This can cause recursive deletion, which can invalidate our iterator.
943     // Use a WeakVH to hold onto it in case this happens.
944     WeakVH IterHandle(CurInstIterator);
945     BasicBlock *BB = CurInstIterator->getParent();
946     
947     RecursivelyDeleteTriviallyDeadInstructions(Repl);
948
949     if (IterHandle != CurInstIterator) {
950       // If the iterator instruction was recursively deleted, start over at the
951       // start of the block.
952       CurInstIterator = BB->begin();
953       SunkAddrs.clear();
954     } else {
955       // This address is now available for reassignment, so erase the table
956       // entry; we don't want to match some completely different instruction.
957       SunkAddrs[Addr] = 0;
958     }    
959   }
960   ++NumMemoryInsts;
961   return true;
962 }
963
964 /// OptimizeInlineAsmInst - If there are any memory operands, use
965 /// OptimizeMemoryInst to sink their address computing into the block when
966 /// possible / profitable.
967 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
968   bool MadeChange = false;
969
970   TargetLowering::AsmOperandInfoVector 
971     TargetConstraints = TLI->ParseConstraints(CS);
972   unsigned ArgNo = 0;
973   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
974     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
975     
976     // Compute the constraint code and ConstraintType to use.
977     TLI->ComputeConstraintToUse(OpInfo, SDValue());
978
979     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
980         OpInfo.isIndirect) {
981       Value *OpVal = CS->getArgOperand(ArgNo++);
982       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
983     } else if (OpInfo.Type == InlineAsm::isInput)
984       ArgNo++;
985   }
986
987   return MadeChange;
988 }
989
990 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
991 /// basic block as the load, unless conditions are unfavorable. This allows
992 /// SelectionDAG to fold the extend into the load.
993 ///
994 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
995   // Look for a load being extended.
996   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
997   if (!LI) return false;
998
999   // If they're already in the same block, there's nothing to do.
1000   if (LI->getParent() == I->getParent())
1001     return false;
1002
1003   // If the load has other users and the truncate is not free, this probably
1004   // isn't worthwhile.
1005   if (!LI->hasOneUse() &&
1006       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
1007               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
1008       !TLI->isTruncateFree(I->getType(), LI->getType()))
1009     return false;
1010
1011   // Check whether the target supports casts folded into loads.
1012   unsigned LType;
1013   if (isa<ZExtInst>(I))
1014     LType = ISD::ZEXTLOAD;
1015   else {
1016     assert(isa<SExtInst>(I) && "Unexpected ext type!");
1017     LType = ISD::SEXTLOAD;
1018   }
1019   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1020     return false;
1021
1022   // Move the extend into the same block as the load, so that SelectionDAG
1023   // can fold it.
1024   I->removeFromParent();
1025   I->insertAfter(LI);
1026   ++NumExtsMoved;
1027   return true;
1028 }
1029
1030 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1031   BasicBlock *DefBB = I->getParent();
1032
1033   // If the result of a {s|z}ext and its source are both live out, rewrite all
1034   // other uses of the source with result of extension.
1035   Value *Src = I->getOperand(0);
1036   if (Src->hasOneUse())
1037     return false;
1038
1039   // Only do this xform if truncating is free.
1040   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1041     return false;
1042
1043   // Only safe to perform the optimization if the source is also defined in
1044   // this block.
1045   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1046     return false;
1047
1048   bool DefIsLiveOut = false;
1049   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1050        UI != E; ++UI) {
1051     Instruction *User = cast<Instruction>(*UI);
1052
1053     // Figure out which BB this ext is used in.
1054     BasicBlock *UserBB = User->getParent();
1055     if (UserBB == DefBB) continue;
1056     DefIsLiveOut = true;
1057     break;
1058   }
1059   if (!DefIsLiveOut)
1060     return false;
1061
1062   // Make sure non of the uses are PHI nodes.
1063   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1064        UI != E; ++UI) {
1065     Instruction *User = cast<Instruction>(*UI);
1066     BasicBlock *UserBB = User->getParent();
1067     if (UserBB == DefBB) continue;
1068     // Be conservative. We don't want this xform to end up introducing
1069     // reloads just before load / store instructions.
1070     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1071       return false;
1072   }
1073
1074   // InsertedTruncs - Only insert one trunc in each block once.
1075   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1076
1077   bool MadeChange = false;
1078   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1079        UI != E; ++UI) {
1080     Use &TheUse = UI.getUse();
1081     Instruction *User = cast<Instruction>(*UI);
1082
1083     // Figure out which BB this ext is used in.
1084     BasicBlock *UserBB = User->getParent();
1085     if (UserBB == DefBB) continue;
1086
1087     // Both src and def are live in this block. Rewrite the use.
1088     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1089
1090     if (!InsertedTrunc) {
1091       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1092       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1093     }
1094
1095     // Replace a use of the {s|z}ext source with a use of the result.
1096     TheUse = InsertedTrunc;
1097     ++NumExtUses;
1098     MadeChange = true;
1099   }
1100
1101   return MadeChange;
1102 }
1103
1104 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
1105 /// turned into an explicit branch.
1106 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
1107   // FIXME: This should use the same heuristics as IfConversion to determine
1108   // whether a select is better represented as a branch.  This requires that
1109   // branch probability metadata is preserved for the select, which is not the
1110   // case currently.
1111
1112   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1113
1114   // If the branch is predicted right, an out of order CPU can avoid blocking on
1115   // the compare.  Emit cmovs on compares with a memory operand as branches to
1116   // avoid stalls on the load from memory.  If the compare has more than one use
1117   // there's probably another cmov or setcc around so it's not worth emitting a
1118   // branch.
1119   if (!Cmp)
1120     return false;
1121
1122   Value *CmpOp0 = Cmp->getOperand(0);
1123   Value *CmpOp1 = Cmp->getOperand(1);
1124
1125   // We check that the memory operand has one use to avoid uses of the loaded
1126   // value directly after the compare, making branches unprofitable.
1127   return Cmp->hasOneUse() &&
1128          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
1129           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
1130 }
1131
1132
1133 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
1134   // If we have a SelectInst that will likely profit from branch prediction,
1135   // turn it into a branch.
1136   if (DisableSelectToBranch || OptSize || !TLI ||
1137       !TLI->isPredictableSelectExpensive())
1138     return false;
1139
1140   if (!SI->getCondition()->getType()->isIntegerTy(1) ||
1141       !isFormingBranchFromSelectProfitable(SI))
1142     return false;
1143
1144   ModifiedDT = true;
1145
1146   // First, we split the block containing the select into 2 blocks.
1147   BasicBlock *StartBlock = SI->getParent();
1148   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
1149   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
1150
1151   // Create a new block serving as the landing pad for the branch.
1152   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
1153                                              NextBlock->getParent(), NextBlock);
1154
1155   // Move the unconditional branch from the block with the select in it into our
1156   // landing pad block.
1157   StartBlock->getTerminator()->eraseFromParent();
1158   BranchInst::Create(NextBlock, SmallBlock);
1159
1160   // Insert the real conditional branch based on the original condition.
1161   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
1162
1163   // The select itself is replaced with a PHI Node.
1164   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
1165   PN->takeName(SI);
1166   PN->addIncoming(SI->getTrueValue(), StartBlock);
1167   PN->addIncoming(SI->getFalseValue(), SmallBlock);
1168   SI->replaceAllUsesWith(PN);
1169   SI->eraseFromParent();
1170
1171   // Instruct OptimizeBlock to skip to the next block.
1172   CurInstIterator = StartBlock->end();
1173   ++NumSelectsExpanded;
1174   return true;
1175 }
1176
1177 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1178   if (PHINode *P = dyn_cast<PHINode>(I)) {
1179     // It is possible for very late stage optimizations (such as SimplifyCFG)
1180     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
1181     // trivial PHI, go ahead and zap it here.
1182     if (Value *V = SimplifyInstruction(P)) {
1183       P->replaceAllUsesWith(V);
1184       P->eraseFromParent();
1185       ++NumPHIsElim;
1186       return true;
1187     }
1188     return false;
1189   }
1190   
1191   if (CastInst *CI = dyn_cast<CastInst>(I)) {
1192     // If the source of the cast is a constant, then this should have
1193     // already been constant folded.  The only reason NOT to constant fold
1194     // it is if something (e.g. LSR) was careful to place the constant
1195     // evaluation in a block other than then one that uses it (e.g. to hoist
1196     // the address of globals out of a loop).  If this is the case, we don't
1197     // want to forward-subst the cast.
1198     if (isa<Constant>(CI->getOperand(0)))
1199       return false;
1200
1201     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1202       return true;
1203
1204     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1205       bool MadeChange = MoveExtToFormExtLoad(I);
1206       return MadeChange | OptimizeExtUses(I);
1207     }
1208     return false;
1209   }
1210   
1211   if (CmpInst *CI = dyn_cast<CmpInst>(I))
1212     return OptimizeCmpExpression(CI);
1213   
1214   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1215     if (TLI)
1216       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1217     return false;
1218   }
1219   
1220   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1221     if (TLI)
1222       return OptimizeMemoryInst(I, SI->getOperand(1),
1223                                 SI->getOperand(0)->getType());
1224     return false;
1225   }
1226   
1227   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1228     if (GEPI->hasAllZeroIndices()) {
1229       /// The GEP operand must be a pointer, so must its result -> BitCast
1230       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1231                                         GEPI->getName(), GEPI);
1232       GEPI->replaceAllUsesWith(NC);
1233       GEPI->eraseFromParent();
1234       ++NumGEPsElim;
1235       OptimizeInst(NC);
1236       return true;
1237     }
1238     return false;
1239   }
1240   
1241   if (CallInst *CI = dyn_cast<CallInst>(I))
1242     return OptimizeCallInst(CI);
1243
1244   if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1245     return DupRetToEnableTailCallOpts(RI);
1246
1247   if (SelectInst *SI = dyn_cast<SelectInst>(I))
1248     return OptimizeSelectInst(SI);
1249
1250   return false;
1251 }
1252
1253 // In this pass we look for GEP and cast instructions that are used
1254 // across basic blocks and rewrite them to improve basic-block-at-a-time
1255 // selection.
1256 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1257   SunkAddrs.clear();
1258   bool MadeChange = false;
1259
1260   CurInstIterator = BB.begin();
1261   for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1262     MadeChange |= OptimizeInst(CurInstIterator++);
1263
1264   return MadeChange;
1265 }
1266
1267 // llvm.dbg.value is far away from the value then iSel may not be able
1268 // handle it properly. iSel will drop llvm.dbg.value if it can not 
1269 // find a node corresponding to the value.
1270 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1271   bool MadeChange = false;
1272   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1273     Instruction *PrevNonDbgInst = NULL;
1274     for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1275       Instruction *Insn = BI; ++BI;
1276       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1277       if (!DVI) {
1278         PrevNonDbgInst = Insn;
1279         continue;
1280       }
1281
1282       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1283       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1284         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1285         DVI->removeFromParent();
1286         if (isa<PHINode>(VI))
1287           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1288         else
1289           DVI->insertAfter(VI);
1290         MadeChange = true;
1291         ++NumDbgValueMoved;
1292       }
1293     }
1294   }
1295   return MadeChange;
1296 }