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