DeadStoreElimination can treat byval parameters as if there were alloca's for the...
[oota-llvm.git] / lib / Transforms / Scalar / CodeGenPrepare.cpp
1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass munges the code in the input function to better prepare it for
11 // SelectionDAG-based code generation.  This works around limitations in it's
12 // basic-block-at-a-time approach.  It should eventually be removed.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "codegenprepare"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/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 }
41
42 namespace {  
43   class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
44     /// TLI - Keep a pointer of a TargetLowering to consult for determining
45     /// transformation profitability.
46     const TargetLowering *TLI;
47   public:
48     static char ID; // Pass identification, replacement for typeid
49     explicit CodeGenPrepare(const TargetLowering *tli = 0)
50       : FunctionPass((intptr_t)&ID), TLI(tli) {}
51     bool runOnFunction(Function &F);
52     
53   private:
54     bool EliminateMostlyEmptyBlocks(Function &F);
55     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
56     void EliminateMostlyEmptyBlock(BasicBlock *BB);
57     bool OptimizeBlock(BasicBlock &BB);
58     bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
59                                const Type *AccessTy,
60                                DenseMap<Value*,Value*> &SunkAddrs);
61     bool OptimizeExtUses(Instruction *I);
62   };
63 }
64
65 char CodeGenPrepare::ID = 0;
66 static RegisterPass<CodeGenPrepare> X("codegenprepare",
67                                       "Optimize for code generation");
68
69 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
70   return new CodeGenPrepare(TLI);
71 }
72
73
74 bool CodeGenPrepare::runOnFunction(Function &F) {
75   bool EverMadeChange = false;
76   
77   // First pass, eliminate blocks that contain only PHI nodes and an
78   // unconditional branch.
79   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
80   
81   bool MadeChange = true;
82   while (MadeChange) {
83     MadeChange = false;
84     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
85       MadeChange |= OptimizeBlock(*BB);
86     EverMadeChange |= MadeChange;
87   }
88   return EverMadeChange;
89 }
90
91 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
92 /// and an unconditional branch.  Passes before isel (e.g. LSR/loopsimplify) 
93 /// often split edges in ways that are non-optimal for isel.  Start by
94 /// eliminating these blocks so we can split them the way we want them.
95 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
96   bool MadeChange = false;
97   // Note that this intentionally skips the entry block.
98   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
99     BasicBlock *BB = I++;
100
101     // If this block doesn't end with an uncond branch, ignore it.
102     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
103     if (!BI || !BI->isUnconditional())
104       continue;
105     
106     // If the instruction before the branch isn't a phi node, then other stuff
107     // is happening here.
108     BasicBlock::iterator BBI = BI;
109     if (BBI != BB->begin()) {
110       --BBI;
111       if (!isa<PHINode>(BBI)) continue;
112     }
113     
114     // Do not break infinite loops.
115     BasicBlock *DestBB = BI->getSuccessor(0);
116     if (DestBB == BB)
117       continue;
118     
119     if (!CanMergeBlocks(BB, DestBB))
120       continue;
121     
122     EliminateMostlyEmptyBlock(BB);
123     MadeChange = true;
124   }
125   return MadeChange;
126 }
127
128 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
129 /// single uncond branch between them, and BB contains no other non-phi
130 /// instructions.
131 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
132                                     const BasicBlock *DestBB) const {
133   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
134   // the successor.  If there are more complex condition (e.g. preheaders),
135   // don't mess around with them.
136   BasicBlock::const_iterator BBI = BB->begin();
137   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
138     for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
139          UI != E; ++UI) {
140       const Instruction *User = cast<Instruction>(*UI);
141       if (User->getParent() != DestBB || !isa<PHINode>(User))
142         return false;
143       // If User is inside DestBB block and it is a PHINode then check 
144       // incoming value. If incoming value is not from BB then this is 
145       // a complex condition (e.g. preheaders) we want to avoid here.
146       if (User->getParent() == DestBB) {
147         if (const PHINode *UPN = dyn_cast<PHINode>(User))
148           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
149             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
150             if (Insn && Insn->getParent() == BB &&
151                 Insn->getParent() != UPN->getIncomingBlock(I))
152               return false;
153           }
154       }
155     }
156   }
157   
158   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
159   // and DestBB may have conflicting incoming values for the block.  If so, we
160   // can't merge the block.
161   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
162   if (!DestBBPN) return true;  // no conflict.
163   
164   // Collect the preds of BB.
165   SmallPtrSet<const BasicBlock*, 16> BBPreds;
166   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
167     // It is faster to get preds from a PHI than with pred_iterator.
168     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
169       BBPreds.insert(BBPN->getIncomingBlock(i));
170   } else {
171     BBPreds.insert(pred_begin(BB), pred_end(BB));
172   }
173   
174   // Walk the preds of DestBB.
175   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
176     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
177     if (BBPreds.count(Pred)) {   // Common predecessor?
178       BBI = DestBB->begin();
179       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
180         const Value *V1 = PN->getIncomingValueForBlock(Pred);
181         const Value *V2 = PN->getIncomingValueForBlock(BB);
182         
183         // If V2 is a phi node in BB, look up what the mapped value will be.
184         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
185           if (V2PN->getParent() == BB)
186             V2 = V2PN->getIncomingValueForBlock(Pred);
187         
188         // If there is a conflict, bail out.
189         if (V1 != V2) return false;
190       }
191     }
192   }
193
194   return true;
195 }
196
197
198 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
199 /// an unconditional branch in it.
200 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
201   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
202   BasicBlock *DestBB = BI->getSuccessor(0);
203   
204   DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
205   
206   // If the destination block has a single pred, then this is a trivial edge,
207   // just collapse it.
208   if (DestBB->getSinglePredecessor()) {
209     // If DestBB has single-entry PHI nodes, fold them.
210     while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
211       PN->replaceAllUsesWith(PN->getIncomingValue(0));
212       PN->eraseFromParent();
213     }
214     
215     // Splice all the PHI nodes from BB over to DestBB.
216     DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
217                                  BB->begin(), BI);
218     
219     // Anything that branched to BB now branches to DestBB.
220     BB->replaceAllUsesWith(DestBB);
221     
222     // Nuke BB.
223     BB->eraseFromParent();
224     
225     DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
226     return;
227   }
228   
229   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
230   // to handle the new incoming edges it is about to have.
231   PHINode *PN;
232   for (BasicBlock::iterator BBI = DestBB->begin();
233        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
234     // Remove the incoming value for BB, and remember it.
235     Value *InVal = PN->removeIncomingValue(BB, false);
236     
237     // Two options: either the InVal is a phi node defined in BB or it is some
238     // value that dominates BB.
239     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
240     if (InValPhi && InValPhi->getParent() == BB) {
241       // Add all of the input values of the input PHI as inputs of this phi.
242       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
243         PN->addIncoming(InValPhi->getIncomingValue(i),
244                         InValPhi->getIncomingBlock(i));
245     } else {
246       // Otherwise, add one instance of the dominating value for each edge that
247       // we will be adding.
248       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
249         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
250           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
251       } else {
252         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
253           PN->addIncoming(InVal, *PI);
254       }
255     }
256   }
257   
258   // The PHIs are now updated, change everything that refers to BB to use
259   // DestBB and remove BB.
260   BB->replaceAllUsesWith(DestBB);
261   BB->eraseFromParent();
262   
263   DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
264 }
265
266
267 /// SplitEdgeNicely - Split the critical edge from TI to its specified
268 /// successor if it will improve codegen.  We only do this if the successor has
269 /// phi nodes (otherwise critical edges are ok).  If there is already another
270 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
271 /// instead of introducing a new block.
272 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
273   BasicBlock *TIBB = TI->getParent();
274   BasicBlock *Dest = TI->getSuccessor(SuccNum);
275   assert(isa<PHINode>(Dest->begin()) &&
276          "This should only be called if Dest has a PHI!");
277   
278   // As a hack, never split backedges of loops.  Even though the copy for any
279   // PHIs inserted on the backedge would be dead for exits from the loop, we
280   // assume that the cost of *splitting* the backedge would be too high.
281   if (Dest == TIBB)
282     return;
283   
284   /// TIPHIValues - This array is lazily computed to determine the values of
285   /// PHIs in Dest that TI would provide.
286   SmallVector<Value*, 32> TIPHIValues;
287   
288   // Check to see if Dest has any blocks that can be used as a split edge for
289   // this terminator.
290   for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
291     BasicBlock *Pred = *PI;
292     // To be usable, the pred has to end with an uncond branch to the dest.
293     BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
294     if (!PredBr || !PredBr->isUnconditional() ||
295         // Must be empty other than the branch.
296         &Pred->front() != PredBr ||
297         // Cannot be the entry block; its label does not get emitted.
298         Pred == &(Dest->getParent()->getEntryBlock()))
299       continue;
300     
301     // Finally, since we know that Dest has phi nodes in it, we have to make
302     // sure that jumping to Pred will have the same affect as going to Dest in
303     // terms of PHI values.
304     PHINode *PN;
305     unsigned PHINo = 0;
306     bool FoundMatch = true;
307     for (BasicBlock::iterator I = Dest->begin();
308          (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
309       if (PHINo == TIPHIValues.size())
310         TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
311       
312       // If the PHI entry doesn't work, we can't use this pred.
313       if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
314         FoundMatch = false;
315         break;
316       }
317     }
318     
319     // If we found a workable predecessor, change TI to branch to Succ.
320     if (FoundMatch) {
321       Dest->removePredecessor(TIBB);
322       TI->setSuccessor(SuccNum, Pred);
323       return;
324     }
325   }
326   
327   SplitCriticalEdge(TI, SuccNum, P, true);  
328 }
329
330 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
331 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
332 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
333 /// registers that must be created and coalesced.
334 ///
335 /// Return true if any changes are made.
336 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
337   // If this is a noop copy, 
338   MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
339   MVT::ValueType DstVT = TLI.getValueType(CI->getType());
340   
341   // This is an fp<->int conversion?
342   if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
343     return false;
344   
345   // If this is an extension, it will be a zero or sign extension, which
346   // isn't a noop.
347   if (SrcVT < DstVT) return false;
348   
349   // If these values will be promoted, find out what they will be promoted
350   // to.  This helps us consider truncates on PPC as noop copies when they
351   // are.
352   if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
353     SrcVT = TLI.getTypeToTransformTo(SrcVT);
354   if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
355     DstVT = TLI.getTypeToTransformTo(DstVT);
356   
357   // If, after promotion, these are the same types, this is a noop copy.
358   if (SrcVT != DstVT)
359     return false;
360   
361   BasicBlock *DefBB = CI->getParent();
362   
363   /// InsertedCasts - Only insert a cast in each block once.
364   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
365   
366   bool MadeChange = false;
367   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end(); 
368        UI != E; ) {
369     Use &TheUse = UI.getUse();
370     Instruction *User = cast<Instruction>(*UI);
371     
372     // Figure out which BB this cast is used in.  For PHI's this is the
373     // appropriate predecessor block.
374     BasicBlock *UserBB = User->getParent();
375     if (PHINode *PN = dyn_cast<PHINode>(User)) {
376       unsigned OpVal = UI.getOperandNo()/2;
377       UserBB = PN->getIncomingBlock(OpVal);
378     }
379     
380     // Preincrement use iterator so we don't invalidate it.
381     ++UI;
382     
383     // If this user is in the same block as the cast, don't change the cast.
384     if (UserBB == DefBB) continue;
385     
386     // If we have already inserted a cast into this block, use it.
387     CastInst *&InsertedCast = InsertedCasts[UserBB];
388
389     if (!InsertedCast) {
390       BasicBlock::iterator InsertPt = UserBB->begin();
391       while (isa<PHINode>(InsertPt)) ++InsertPt;
392       
393       InsertedCast = 
394         CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "", 
395                          InsertPt);
396       MadeChange = true;
397     }
398     
399     // Replace a use of the cast with a use of the new cast.
400     TheUse = InsertedCast;
401   }
402   
403   // If we removed all uses, nuke the cast.
404   if (CI->use_empty()) {
405     CI->eraseFromParent();
406     MadeChange = true;
407   }
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