add a -backedge-hack llc-beta option to codegenprepare.
[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 was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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/Instructions.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Target/TargetAsmInfo.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Compiler.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/GetElementPtrTypeIterator.h"
35 using namespace llvm;
36
37 namespace {
38   cl::opt<bool> OptExtUses("optimize-ext-uses",
39                            cl::init(true), cl::Hidden);
40   // LLCBETA option.
41   cl::opt<bool> DontHackBackedge("backedge-hack", cl::Hidden);
42 }
43
44 namespace {  
45   class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
46     /// TLI - Keep a pointer of a TargetLowering to consult for determining
47     /// transformation profitability.
48     const TargetLowering *TLI;
49   public:
50     static char ID; // Pass identification, replacement for typeid
51     explicit CodeGenPrepare(const TargetLowering *tli = 0)
52       : FunctionPass((intptr_t)&ID), TLI(tli) {}
53     bool runOnFunction(Function &F);
54     
55   private:
56     bool EliminateMostlyEmptyBlocks(Function &F);
57     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
58     void EliminateMostlyEmptyBlock(BasicBlock *BB);
59     bool OptimizeBlock(BasicBlock &BB);
60     bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
61                                const Type *AccessTy,
62                                DenseMap<Value*,Value*> &SunkAddrs);
63     bool OptimizeExtUses(Instruction *I);
64   };
65 }
66
67 char CodeGenPrepare::ID = 0;
68 static RegisterPass<CodeGenPrepare> X("codegenprepare",
69                                       "Optimize for code generation");
70
71 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
72   return new CodeGenPrepare(TLI);
73 }
74
75
76 bool CodeGenPrepare::runOnFunction(Function &F) {
77   bool EverMadeChange = false;
78   
79   // First pass, eliminate blocks that contain only PHI nodes and an
80   // unconditional branch.
81   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
82   
83   bool MadeChange = true;
84   while (MadeChange) {
85     MadeChange = false;
86     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
87       MadeChange |= OptimizeBlock(*BB);
88     EverMadeChange |= MadeChange;
89   }
90   return EverMadeChange;
91 }
92
93 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
94 /// and an unconditional branch.  Passes before isel (e.g. LSR/loopsimplify) 
95 /// often split edges in ways that are non-optimal for isel.  Start by
96 /// eliminating these blocks so we can split them the way we want them.
97 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
98   bool MadeChange = false;
99   // Note that this intentionally skips the entry block.
100   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
101     BasicBlock *BB = I++;
102
103     // If this block doesn't end with an uncond branch, ignore it.
104     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
105     if (!BI || !BI->isUnconditional())
106       continue;
107     
108     // If the instruction before the branch isn't a phi node, then other stuff
109     // is happening here.
110     BasicBlock::iterator BBI = BI;
111     if (BBI != BB->begin()) {
112       --BBI;
113       if (!isa<PHINode>(BBI)) continue;
114     }
115     
116     // Do not break infinite loops.
117     BasicBlock *DestBB = BI->getSuccessor(0);
118     if (DestBB == BB)
119       continue;
120     
121     if (!CanMergeBlocks(BB, DestBB))
122       continue;
123     
124     EliminateMostlyEmptyBlock(BB);
125     MadeChange = true;
126   }
127   return MadeChange;
128 }
129
130 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
131 /// single uncond branch between them, and BB contains no other non-phi
132 /// instructions.
133 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
134                                     const BasicBlock *DestBB) const {
135   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
136   // the successor.  If there are more complex condition (e.g. preheaders),
137   // don't mess around with them.
138   BasicBlock::const_iterator BBI = BB->begin();
139   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
140     for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
141          UI != E; ++UI) {
142       const Instruction *User = cast<Instruction>(*UI);
143       if (User->getParent() != DestBB || !isa<PHINode>(User))
144         return false;
145       // If User is inside DestBB block and it is a PHINode then check 
146       // incoming value. If incoming value is not from BB then this is 
147       // a complex condition (e.g. preheaders) we want to avoid here.
148       if (User->getParent() == DestBB) {
149         if (const PHINode *UPN = dyn_cast<PHINode>(User))
150           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
151             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
152             if (Insn && Insn->getParent() == BB &&
153                 Insn->getParent() != UPN->getIncomingBlock(I))
154               return false;
155           }
156       }
157     }
158   }
159   
160   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
161   // and DestBB may have conflicting incoming values for the block.  If so, we
162   // can't merge the block.
163   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
164   if (!DestBBPN) return true;  // no conflict.
165   
166   // Collect the preds of BB.
167   SmallPtrSet<const BasicBlock*, 16> BBPreds;
168   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
169     // It is faster to get preds from a PHI than with pred_iterator.
170     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
171       BBPreds.insert(BBPN->getIncomingBlock(i));
172   } else {
173     BBPreds.insert(pred_begin(BB), pred_end(BB));
174   }
175   
176   // Walk the preds of DestBB.
177   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
178     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
179     if (BBPreds.count(Pred)) {   // Common predecessor?
180       BBI = DestBB->begin();
181       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
182         const Value *V1 = PN->getIncomingValueForBlock(Pred);
183         const Value *V2 = PN->getIncomingValueForBlock(BB);
184         
185         // If V2 is a phi node in BB, look up what the mapped value will be.
186         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
187           if (V2PN->getParent() == BB)
188             V2 = V2PN->getIncomingValueForBlock(Pred);
189         
190         // If there is a conflict, bail out.
191         if (V1 != V2) return false;
192       }
193     }
194   }
195
196   return true;
197 }
198
199
200 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
201 /// an unconditional branch in it.
202 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
203   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
204   BasicBlock *DestBB = BI->getSuccessor(0);
205   
206   DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
207   
208   // If the destination block has a single pred, then this is a trivial edge,
209   // just collapse it.
210   if (DestBB->getSinglePredecessor()) {
211     // If DestBB has single-entry PHI nodes, fold them.
212     while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
213       PN->replaceAllUsesWith(PN->getIncomingValue(0));
214       PN->eraseFromParent();
215     }
216     
217     // Splice all the PHI nodes from BB over to DestBB.
218     DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
219                                  BB->begin(), BI);
220     
221     // Anything that branched to BB now branches to DestBB.
222     BB->replaceAllUsesWith(DestBB);
223     
224     // Nuke BB.
225     BB->eraseFromParent();
226     
227     DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
228     return;
229   }
230   
231   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
232   // to handle the new incoming edges it is about to have.
233   PHINode *PN;
234   for (BasicBlock::iterator BBI = DestBB->begin();
235        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
236     // Remove the incoming value for BB, and remember it.
237     Value *InVal = PN->removeIncomingValue(BB, false);
238     
239     // Two options: either the InVal is a phi node defined in BB or it is some
240     // value that dominates BB.
241     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
242     if (InValPhi && InValPhi->getParent() == BB) {
243       // Add all of the input values of the input PHI as inputs of this phi.
244       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
245         PN->addIncoming(InValPhi->getIncomingValue(i),
246                         InValPhi->getIncomingBlock(i));
247     } else {
248       // Otherwise, add one instance of the dominating value for each edge that
249       // we will be adding.
250       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
251         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
252           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
253       } else {
254         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
255           PN->addIncoming(InVal, *PI);
256       }
257     }
258   }
259   
260   // The PHIs are now updated, change everything that refers to BB to use
261   // DestBB and remove BB.
262   BB->replaceAllUsesWith(DestBB);
263   BB->eraseFromParent();
264   
265   DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
266 }
267
268
269 /// SplitEdgeNicely - Split the critical edge from TI to its specified
270 /// successor if it will improve codegen.  We only do this if the successor has
271 /// phi nodes (otherwise critical edges are ok).  If there is already another
272 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
273 /// instead of introducing a new block.
274 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
275   BasicBlock *TIBB = TI->getParent();
276   BasicBlock *Dest = TI->getSuccessor(SuccNum);
277   assert(isa<PHINode>(Dest->begin()) &&
278          "This should only be called if Dest has a PHI!");
279   
280   // As a hack, never split backedges of loops.  Even though the copy for any
281   // PHIs inserted on the backedge would be dead for exits from the loop, we
282   // assume that the cost of *splitting* the backedge would be too high.
283   if (DontHackBackedge && Dest == TIBB)
284     return;
285   
286   /// TIPHIValues - This array is lazily computed to determine the values of
287   /// PHIs in Dest that TI would provide.
288   SmallVector<Value*, 32> TIPHIValues;
289   
290   // Check to see if Dest has any blocks that can be used as a split edge for
291   // this terminator.
292   for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
293     BasicBlock *Pred = *PI;
294     // To be usable, the pred has to end with an uncond branch to the dest.
295     BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
296     if (!PredBr || !PredBr->isUnconditional() ||
297         // Must be empty other than the branch.
298         &Pred->front() != PredBr ||
299         // Cannot be the entry block; its label does not get emitted.
300         Pred == &(Dest->getParent()->getEntryBlock()))
301       continue;
302     
303     // Finally, since we know that Dest has phi nodes in it, we have to make
304     // sure that jumping to Pred will have the same affect as going to Dest in
305     // terms of PHI values.
306     PHINode *PN;
307     unsigned PHINo = 0;
308     bool FoundMatch = true;
309     for (BasicBlock::iterator I = Dest->begin();
310          (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
311       if (PHINo == TIPHIValues.size())
312         TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
313       
314       // If the PHI entry doesn't work, we can't use this pred.
315       if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
316         FoundMatch = false;
317         break;
318       }
319     }
320     
321     // If we found a workable predecessor, change TI to branch to Succ.
322     if (FoundMatch) {
323       Dest->removePredecessor(TIBB);
324       TI->setSuccessor(SuccNum, Pred);
325       return;
326     }
327   }
328   
329   SplitCriticalEdge(TI, SuccNum, P, true);  
330 }
331
332 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
333 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
334 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
335 /// registers that must be created and coalesced.
336 ///
337 /// Return true if any changes are made.
338 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
339   // If this is a noop copy, 
340   MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
341   MVT::ValueType DstVT = TLI.getValueType(CI->getType());
342   
343   // This is an fp<->int conversion?
344   if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
345     return false;
346   
347   // If this is an extension, it will be a zero or sign extension, which
348   // isn't a noop.
349   if (SrcVT < DstVT) return false;
350   
351   // If these values will be promoted, find out what they will be promoted
352   // to.  This helps us consider truncates on PPC as noop copies when they
353   // are.
354   if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
355     SrcVT = TLI.getTypeToTransformTo(SrcVT);
356   if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
357     DstVT = TLI.getTypeToTransformTo(DstVT);
358   
359   // If, after promotion, these are the same types, this is a noop copy.
360   if (SrcVT != DstVT)
361     return false;
362   
363   BasicBlock *DefBB = CI->getParent();
364   
365   /// InsertedCasts - Only insert a cast in each block once.
366   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
367   
368   bool MadeChange = false;
369   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end(); 
370        UI != E; ) {
371     Use &TheUse = UI.getUse();
372     Instruction *User = cast<Instruction>(*UI);
373     
374     // Figure out which BB this cast is used in.  For PHI's this is the
375     // appropriate predecessor block.
376     BasicBlock *UserBB = User->getParent();
377     if (PHINode *PN = dyn_cast<PHINode>(User)) {
378       unsigned OpVal = UI.getOperandNo()/2;
379       UserBB = PN->getIncomingBlock(OpVal);
380     }
381     
382     // Preincrement use iterator so we don't invalidate it.
383     ++UI;
384     
385     // If this user is in the same block as the cast, don't change the cast.
386     if (UserBB == DefBB) continue;
387     
388     // If we have already inserted a cast into this block, use it.
389     CastInst *&InsertedCast = InsertedCasts[UserBB];
390
391     if (!InsertedCast) {
392       BasicBlock::iterator InsertPt = UserBB->begin();
393       while (isa<PHINode>(InsertPt)) ++InsertPt;
394       
395       InsertedCast = 
396         CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "", 
397                          InsertPt);
398       MadeChange = true;
399     }
400     
401     // Replace a use of the cast with a use of the new cast.
402     TheUse = InsertedCast;
403   }
404   
405   // If we removed all uses, nuke the cast.
406   if (CI->use_empty())
407     CI->eraseFromParent();
408   
409   return MadeChange;
410 }
411
412 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce 
413 /// the number of virtual registers that must be created and coalesced.  This is
414 /// a clear win except on targets with multiple condition code registers
415 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
416 ///
417 /// Return true if any changes are made.
418 static bool OptimizeCmpExpression(CmpInst *CI){
419
420   BasicBlock *DefBB = CI->getParent();
421   
422   /// InsertedCmp - Only insert a cmp in each block once.
423   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
424   
425   bool MadeChange = false;
426   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end(); 
427        UI != E; ) {
428     Use &TheUse = UI.getUse();
429     Instruction *User = cast<Instruction>(*UI);
430     
431     // Preincrement use iterator so we don't invalidate it.
432     ++UI;
433     
434     // Don't bother for PHI nodes.
435     if (isa<PHINode>(User))
436       continue;
437
438     // Figure out which BB this cmp is used in.
439     BasicBlock *UserBB = User->getParent();
440     
441     // If this user is in the same block as the cmp, don't change the cmp.
442     if (UserBB == DefBB) continue;
443     
444     // If we have already inserted a cmp into this block, use it.
445     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
446
447     if (!InsertedCmp) {
448       BasicBlock::iterator InsertPt = UserBB->begin();
449       while (isa<PHINode>(InsertPt)) ++InsertPt;
450       
451       InsertedCmp = 
452         CmpInst::create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0), 
453                         CI->getOperand(1), "", InsertPt);
454       MadeChange = true;
455     }
456     
457     // Replace a use of the cmp with a use of the new cmp.
458     TheUse = InsertedCmp;
459   }
460   
461   // If we removed all uses, nuke the cmp.
462   if (CI->use_empty())
463     CI->eraseFromParent();
464   
465   return MadeChange;
466 }
467
468 /// EraseDeadInstructions - Erase any dead instructions
469 static void EraseDeadInstructions(Value *V) {
470   Instruction *I = dyn_cast<Instruction>(V);
471   if (!I || !I->use_empty()) return;
472   
473   SmallPtrSet<Instruction*, 16> Insts;
474   Insts.insert(I);
475   
476   while (!Insts.empty()) {
477     I = *Insts.begin();
478     Insts.erase(I);
479     if (isInstructionTriviallyDead(I)) {
480       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
481         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
482           Insts.insert(U);
483       I->eraseFromParent();
484     }
485   }
486 }
487
488
489 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode which
490 /// holds actual Value*'s for register values.
491 struct ExtAddrMode : public TargetLowering::AddrMode {
492   Value *BaseReg;
493   Value *ScaledReg;
494   ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
495   void dump() const;
496 };
497
498 static std::ostream &operator<<(std::ostream &OS, const ExtAddrMode &AM) {
499   bool NeedPlus = false;
500   OS << "[";
501   if (AM.BaseGV)
502     OS << (NeedPlus ? " + " : "")
503        << "GV:%" << AM.BaseGV->getName(), NeedPlus = true;
504   
505   if (AM.BaseOffs)
506     OS << (NeedPlus ? " + " : "") << AM.BaseOffs, NeedPlus = true;
507   
508   if (AM.BaseReg)
509     OS << (NeedPlus ? " + " : "")
510        << "Base:%" << AM.BaseReg->getName(), NeedPlus = true;
511   if (AM.Scale)
512     OS << (NeedPlus ? " + " : "")
513        << AM.Scale << "*%" << AM.ScaledReg->getName(), NeedPlus = true;
514   
515   return OS << "]";
516 }
517
518 void ExtAddrMode::dump() const {
519   cerr << *this << "\n";
520 }
521
522 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
523                                    const Type *AccessTy, ExtAddrMode &AddrMode,
524                                    SmallVector<Instruction*, 16> &AddrModeInsts,
525                                    const TargetLowering &TLI, unsigned Depth);
526   
527 /// FindMaximalLegalAddressingMode - If we can, try to merge the computation of
528 /// Addr into the specified addressing mode.  If Addr can't be added to AddrMode
529 /// this returns false.  This assumes that Addr is either a pointer type or
530 /// intptr_t for the target.
531 static bool FindMaximalLegalAddressingMode(Value *Addr, const Type *AccessTy,
532                                            ExtAddrMode &AddrMode,
533                                    SmallVector<Instruction*, 16> &AddrModeInsts,
534                                            const TargetLowering &TLI,
535                                            unsigned Depth) {
536   
537   // If this is a global variable, fold it into the addressing mode if possible.
538   if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
539     if (AddrMode.BaseGV == 0) {
540       AddrMode.BaseGV = GV;
541       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
542         return true;
543       AddrMode.BaseGV = 0;
544     }
545   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
546     AddrMode.BaseOffs += CI->getSExtValue();
547     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
548       return true;
549     AddrMode.BaseOffs -= CI->getSExtValue();
550   } else if (isa<ConstantPointerNull>(Addr)) {
551     return true;
552   }
553   
554   // Look through constant exprs and instructions.
555   unsigned Opcode = ~0U;
556   User *AddrInst = 0;
557   if (Instruction *I = dyn_cast<Instruction>(Addr)) {
558     Opcode = I->getOpcode();
559     AddrInst = I;
560   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
561     Opcode = CE->getOpcode();
562     AddrInst = CE;
563   }
564
565   // Limit recursion to avoid exponential behavior.
566   if (Depth == 5) { AddrInst = 0; Opcode = ~0U; }
567
568   // If this is really an instruction, add it to our list of related
569   // instructions.
570   if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst))
571     AddrModeInsts.push_back(I);
572
573   switch (Opcode) {
574   case Instruction::PtrToInt:
575     // PtrToInt is always a noop, as we know that the int type is pointer sized.
576     if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
577                                        AddrMode, AddrModeInsts, TLI, Depth))
578       return true;
579     break;
580   case Instruction::IntToPtr:
581     // This inttoptr is a no-op if the integer type is pointer sized.
582     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
583         TLI.getPointerTy()) {
584       if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
585                                          AddrMode, AddrModeInsts, TLI, Depth))
586         return true;
587     }
588     break;
589   case Instruction::Add: {
590     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
591     ExtAddrMode BackupAddrMode = AddrMode;
592     unsigned OldSize = AddrModeInsts.size();
593     if (FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
594                                        AddrMode, AddrModeInsts, TLI, Depth+1) &&
595         FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
596                                        AddrMode, AddrModeInsts, TLI, Depth+1))
597       return true;
598
599     // Restore the old addr mode info.
600     AddrMode = BackupAddrMode;
601     AddrModeInsts.resize(OldSize);
602     
603     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
604     if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
605                                        AddrMode, AddrModeInsts, TLI, Depth+1) &&
606         FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
607                                        AddrMode, AddrModeInsts, TLI, Depth+1))
608       return true;
609     
610     // Otherwise we definitely can't merge the ADD in.
611     AddrMode = BackupAddrMode;
612     AddrModeInsts.resize(OldSize);
613     break;    
614   }
615   case Instruction::Or: {
616     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
617     if (!RHS) break;
618     // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
619     break;
620   }
621   case Instruction::Mul:
622   case Instruction::Shl: {
623     // Can only handle X*C and X << C, and can only handle this when the scale
624     // field is available.
625     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
626     if (!RHS) break;
627     int64_t Scale = RHS->getSExtValue();
628     if (Opcode == Instruction::Shl)
629       Scale = 1 << Scale;
630     
631     if (TryMatchingScaledValue(AddrInst->getOperand(0), Scale, AccessTy,
632                                AddrMode, AddrModeInsts, TLI, Depth))
633       return true;
634     break;
635   }
636   case Instruction::GetElementPtr: {
637     // Scan the GEP.  We check it if it contains constant offsets and at most
638     // one variable offset.
639     int VariableOperand = -1;
640     unsigned VariableScale = 0;
641     
642     int64_t ConstantOffset = 0;
643     const TargetData *TD = TLI.getTargetData();
644     gep_type_iterator GTI = gep_type_begin(AddrInst);
645     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
646       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
647         const StructLayout *SL = TD->getStructLayout(STy);
648         unsigned Idx =
649           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
650         ConstantOffset += SL->getElementOffset(Idx);
651       } else {
652         uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
653         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
654           ConstantOffset += CI->getSExtValue()*TypeSize;
655         } else if (TypeSize) {  // Scales of zero don't do anything.
656           // We only allow one variable index at the moment.
657           if (VariableOperand != -1) {
658             VariableOperand = -2;
659             break;
660           }
661           
662           // Remember the variable index.
663           VariableOperand = i;
664           VariableScale = TypeSize;
665         }
666       }
667     }
668
669     // If the GEP had multiple variable indices, punt.
670     if (VariableOperand == -2)
671       break;
672
673     // A common case is for the GEP to only do a constant offset.  In this case,
674     // just add it to the disp field and check validity.
675     if (VariableOperand == -1) {
676       AddrMode.BaseOffs += ConstantOffset;
677       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
678         // Check to see if we can fold the base pointer in too.
679         if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
680                                            AddrMode, AddrModeInsts, TLI,
681                                            Depth+1))
682           return true;
683       }
684       AddrMode.BaseOffs -= ConstantOffset;
685     } else {
686       // Check that this has no base reg yet.  If so, we won't have a place to
687       // put the base of the GEP (assuming it is not a null ptr).
688       bool SetBaseReg = false;
689       if (AddrMode.HasBaseReg) {
690         if (!isa<ConstantPointerNull>(AddrInst->getOperand(0)))
691           break;
692       } else {
693         AddrMode.HasBaseReg = true;
694         AddrMode.BaseReg = AddrInst->getOperand(0);
695         SetBaseReg = true;
696       }
697       
698       // See if the scale amount is valid for this target.
699       AddrMode.BaseOffs += ConstantOffset;
700       if (TryMatchingScaledValue(AddrInst->getOperand(VariableOperand),
701                                  VariableScale, AccessTy, AddrMode, 
702                                  AddrModeInsts, TLI, Depth)) {
703         if (!SetBaseReg) return true;
704
705         // If this match succeeded, we know that we can form an address with the
706         // GepBase as the basereg.  See if we can match *more*.
707         AddrMode.HasBaseReg = false;
708         AddrMode.BaseReg = 0;
709         if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
710                                            AddrMode, AddrModeInsts, TLI,
711                                            Depth+1))
712           return true;
713         // Strange, shouldn't happen.  Restore the base reg and succeed the easy
714         // way.        
715         AddrMode.HasBaseReg = true;
716         AddrMode.BaseReg = AddrInst->getOperand(0);
717         return true;
718       }
719       
720       AddrMode.BaseOffs -= ConstantOffset;
721       if (SetBaseReg) {
722         AddrMode.HasBaseReg = false;
723         AddrMode.BaseReg = 0;
724       }
725     }
726     break;    
727   }
728   }
729   
730   if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst)) {
731     assert(AddrModeInsts.back() == I && "Stack imbalance");
732     AddrModeInsts.pop_back();
733   }
734   
735   // Worse case, the target should support [reg] addressing modes. :)
736   if (!AddrMode.HasBaseReg) {
737     AddrMode.HasBaseReg = true;
738     // Still check for legality in case the target supports [imm] but not [i+r].
739     if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
740       AddrMode.BaseReg = Addr;
741       return true;
742     }
743     AddrMode.HasBaseReg = false;
744   }
745   
746   // If the base register is already taken, see if we can do [r+r].
747   if (AddrMode.Scale == 0) {
748     AddrMode.Scale = 1;
749     if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
750       AddrMode.ScaledReg = Addr;
751       return true;
752     }
753     AddrMode.Scale = 0;
754   }
755   // Couldn't match.
756   return false;
757 }
758
759 /// TryMatchingScaledValue - Try adding ScaleReg*Scale to the specified
760 /// addressing mode.  Return true if this addr mode is legal for the target,
761 /// false if not.
762 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
763                                    const Type *AccessTy, ExtAddrMode &AddrMode,
764                                    SmallVector<Instruction*, 16> &AddrModeInsts,
765                                    const TargetLowering &TLI, unsigned Depth) {
766   // If we already have a scale of this value, we can add to it, otherwise, we
767   // need an available scale field.
768   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
769     return false;
770   
771   ExtAddrMode InputAddrMode = AddrMode;
772   
773   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
774   // [A+B + A*7] -> [B+A*8].
775   AddrMode.Scale += Scale;
776   AddrMode.ScaledReg = ScaleReg;
777   
778   if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
779     // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
780     // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
781     // X*Scale + C*Scale to addr mode.
782     BinaryOperator *BinOp = dyn_cast<BinaryOperator>(ScaleReg);
783     if (BinOp && BinOp->getOpcode() == Instruction::Add &&
784         isa<ConstantInt>(BinOp->getOperand(1)) && InputAddrMode.ScaledReg ==0) {
785       
786       InputAddrMode.Scale = Scale;
787       InputAddrMode.ScaledReg = BinOp->getOperand(0);
788       InputAddrMode.BaseOffs += 
789         cast<ConstantInt>(BinOp->getOperand(1))->getSExtValue()*Scale;
790       if (TLI.isLegalAddressingMode(InputAddrMode, AccessTy)) {
791         AddrModeInsts.push_back(BinOp);
792         AddrMode = InputAddrMode;
793         return true;
794       }
795     }
796
797     // Otherwise, not (x+c)*scale, just return what we have.
798     return true;
799   }
800   
801   // Otherwise, back this attempt out.
802   AddrMode.Scale -= Scale;
803   if (AddrMode.Scale == 0) AddrMode.ScaledReg = 0;
804   
805   return false;
806 }
807
808
809 /// IsNonLocalValue - Return true if the specified values are defined in a
810 /// different basic block than BB.
811 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
812   if (Instruction *I = dyn_cast<Instruction>(V))
813     return I->getParent() != BB;
814   return false;
815 }
816
817 /// OptimizeLoadStoreInst - Load and Store Instructions have often have
818 /// addressing modes that can do significant amounts of computation.  As such,
819 /// instruction selection will try to get the load or store to do as much
820 /// computation as possible for the program.  The problem is that isel can only
821 /// see within a single block.  As such, we sink as much legal addressing mode
822 /// stuff into the block as possible.
823 bool CodeGenPrepare::OptimizeLoadStoreInst(Instruction *LdStInst, Value *Addr,
824                                            const Type *AccessTy,
825                                            DenseMap<Value*,Value*> &SunkAddrs) {
826   // Figure out what addressing mode will be built up for this operation.
827   SmallVector<Instruction*, 16> AddrModeInsts;
828   ExtAddrMode AddrMode;
829   bool Success = FindMaximalLegalAddressingMode(Addr, AccessTy, AddrMode,
830                                                 AddrModeInsts, *TLI, 0);
831   Success = Success; assert(Success && "Couldn't select *anything*?");
832   
833   // Check to see if any of the instructions supersumed by this addr mode are
834   // non-local to I's BB.
835   bool AnyNonLocal = false;
836   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
837     if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
838       AnyNonLocal = true;
839       break;
840     }
841   }
842   
843   // If all the instructions matched are already in this BB, don't do anything.
844   if (!AnyNonLocal) {
845     DEBUG(cerr << "CGP: Found      local addrmode: " << AddrMode << "\n");
846     return false;
847   }
848   
849   // Insert this computation right after this user.  Since our caller is
850   // scanning from the top of the BB to the bottom, reuse of the expr are
851   // guaranteed to happen later.
852   BasicBlock::iterator InsertPt = LdStInst;
853   
854   // Now that we determined the addressing expression we want to use and know
855   // that we have to sink it into this block.  Check to see if we have already
856   // done this for some other load/store instr in this block.  If so, reuse the
857   // computation.
858   Value *&SunkAddr = SunkAddrs[Addr];
859   if (SunkAddr) {
860     DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
861     if (SunkAddr->getType() != Addr->getType())
862       SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
863   } else {
864     DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
865     const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
866     
867     Value *Result = 0;
868     // Start with the scale value.
869     if (AddrMode.Scale) {
870       Value *V = AddrMode.ScaledReg;
871       if (V->getType() == IntPtrTy) {
872         // done.
873       } else if (isa<PointerType>(V->getType())) {
874         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
875       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
876                  cast<IntegerType>(V->getType())->getBitWidth()) {
877         V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
878       } else {
879         V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
880       }
881       if (AddrMode.Scale != 1)
882         V = BinaryOperator::createMul(V, ConstantInt::get(IntPtrTy,
883                                                           AddrMode.Scale),
884                                       "sunkaddr", InsertPt);
885       Result = V;
886     }
887
888     // Add in the base register.
889     if (AddrMode.BaseReg) {
890       Value *V = AddrMode.BaseReg;
891       if (V->getType() != IntPtrTy)
892         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
893       if (Result)
894         Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
895       else
896         Result = V;
897     }
898     
899     // Add in the BaseGV if present.
900     if (AddrMode.BaseGV) {
901       Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
902                                   InsertPt);
903       if (Result)
904         Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
905       else
906         Result = V;
907     }
908     
909     // Add in the Base Offset if present.
910     if (AddrMode.BaseOffs) {
911       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
912       if (Result)
913         Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
914       else
915         Result = V;
916     }
917
918     if (Result == 0)
919       SunkAddr = Constant::getNullValue(Addr->getType());
920     else
921       SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
922   }
923   
924   LdStInst->replaceUsesOfWith(Addr, SunkAddr);
925   
926   if (Addr->use_empty())
927     EraseDeadInstructions(Addr);
928   return true;
929 }
930
931 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
932   BasicBlock *DefBB = I->getParent();
933
934   // If both result of the {s|z}xt and its source are live out, rewrite all
935   // other uses of the source with result of extension.
936   Value *Src = I->getOperand(0);
937   if (Src->hasOneUse())
938     return false;
939
940   // Only do this xform if truncating is free.
941   if (!TLI->isTruncateFree(I->getType(), Src->getType()))
942     return false;
943
944   // Only safe to perform the optimization if the source is also defined in
945   // this block.
946   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
947     return false;
948
949   bool DefIsLiveOut = false;
950   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 
951        UI != E; ++UI) {
952     Instruction *User = cast<Instruction>(*UI);
953
954     // Figure out which BB this ext is used in.
955     BasicBlock *UserBB = User->getParent();
956     if (UserBB == DefBB) continue;
957     DefIsLiveOut = true;
958     break;
959   }
960   if (!DefIsLiveOut)
961     return false;
962
963   // Make sure non of the uses are PHI nodes.
964   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end(); 
965        UI != E; ++UI) {
966     Instruction *User = cast<Instruction>(*UI);
967     BasicBlock *UserBB = User->getParent();
968     if (UserBB == DefBB) continue;
969     // Be conservative. We don't want this xform to end up introducing
970     // reloads just before load / store instructions.
971     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
972       return false;
973   }
974
975   // InsertedTruncs - Only insert one trunc in each block once.
976   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
977
978   bool MadeChange = false;
979   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end(); 
980        UI != E; ++UI) {
981     Use &TheUse = UI.getUse();
982     Instruction *User = cast<Instruction>(*UI);
983
984     // Figure out which BB this ext is used in.
985     BasicBlock *UserBB = User->getParent();
986     if (UserBB == DefBB) continue;
987
988     // Both src and def are live in this block. Rewrite the use.
989     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
990
991     if (!InsertedTrunc) {
992       BasicBlock::iterator InsertPt = UserBB->begin();
993       while (isa<PHINode>(InsertPt)) ++InsertPt;
994       
995       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
996     }
997
998     // Replace a use of the {s|z}ext source with a use of the result.
999     TheUse = InsertedTrunc;
1000
1001     MadeChange = true;
1002   }
1003
1004   return MadeChange;
1005 }
1006
1007 // In this pass we look for GEP and cast instructions that are used
1008 // across basic blocks and rewrite them to improve basic-block-at-a-time
1009 // selection.
1010 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1011   bool MadeChange = false;
1012   
1013   // Split all critical edges where the dest block has a PHI and where the phi
1014   // has shared immediate operands.
1015   TerminatorInst *BBTI = BB.getTerminator();
1016   if (BBTI->getNumSuccessors() > 1) {
1017     for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1018       if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1019           isCriticalEdge(BBTI, i, true))
1020         SplitEdgeNicely(BBTI, i, this);
1021   }
1022   
1023   
1024   // Keep track of non-local addresses that have been sunk into this block.
1025   // This allows us to avoid inserting duplicate code for blocks with multiple
1026   // load/stores of the same address.
1027   DenseMap<Value*, Value*> SunkAddrs;
1028   
1029   for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1030     Instruction *I = BBI++;
1031     
1032     if (CastInst *CI = dyn_cast<CastInst>(I)) {
1033       // If the source of the cast is a constant, then this should have
1034       // already been constant folded.  The only reason NOT to constant fold
1035       // it is if something (e.g. LSR) was careful to place the constant
1036       // evaluation in a block other than then one that uses it (e.g. to hoist
1037       // the address of globals out of a loop).  If this is the case, we don't
1038       // want to forward-subst the cast.
1039       if (isa<Constant>(CI->getOperand(0)))
1040         continue;
1041       
1042       bool Change = false;
1043       if (TLI) {
1044         Change = OptimizeNoopCopyExpression(CI, *TLI);
1045         MadeChange |= Change;
1046       }
1047
1048       if (OptExtUses && !Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
1049         MadeChange |= OptimizeExtUses(I);
1050     } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1051       MadeChange |= OptimizeCmpExpression(CI);
1052     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1053       if (TLI)
1054         MadeChange |= OptimizeLoadStoreInst(I, I->getOperand(0), LI->getType(),
1055                                             SunkAddrs);
1056     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1057       if (TLI)
1058         MadeChange |= OptimizeLoadStoreInst(I, SI->getOperand(1),
1059                                             SI->getOperand(0)->getType(),
1060                                             SunkAddrs);
1061     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1062       if (GEPI->hasAllZeroIndices()) {
1063         /// The GEP operand must be a pointer, so must its result -> BitCast
1064         Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), 
1065                                           GEPI->getName(), GEPI);
1066         GEPI->replaceAllUsesWith(NC);
1067         GEPI->eraseFromParent();
1068         MadeChange = true;
1069         BBI = NC;
1070       }
1071     } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1072       // If we found an inline asm expession, and if the target knows how to
1073       // lower it to normal LLVM code, do so now.
1074       if (TLI && isa<InlineAsm>(CI->getCalledValue()))
1075         if (const TargetAsmInfo *TAI = 
1076             TLI->getTargetMachine().getTargetAsmInfo()) {
1077           if (TAI->ExpandInlineAsm(CI))
1078             BBI = BB.begin();
1079         }
1080     }
1081   }
1082     
1083   return MadeChange;
1084 }
1085