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