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