Fix rdar://6505632, an llc crash on 483.xalancbmk
[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/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/PatternMatch.h"
38 using namespace llvm;
39 using namespace llvm::PatternMatch;
40
41 static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
42                                        cl::init(false), cl::Hidden);
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
50     /// BackEdges - Keep a set of all the loop back edges.
51     ///
52     SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> BackEdges;
53   public:
54     static char ID; // Pass identification, replacement for typeid
55     explicit CodeGenPrepare(const TargetLowering *tli = 0)
56       : FunctionPass(&ID), TLI(tli) {}
57     bool runOnFunction(Function &F);
58
59   private:
60     bool EliminateMostlyEmptyBlocks(Function &F);
61     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
62     void EliminateMostlyEmptyBlock(BasicBlock *BB);
63     bool OptimizeBlock(BasicBlock &BB);
64     bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
65                             DenseMap<Value*,Value*> &SunkAddrs);
66     bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
67                                DenseMap<Value*,Value*> &SunkAddrs);
68     bool OptimizeExtUses(Instruction *I);
69     void findLoopBackEdges(Function &F);
70   };
71 }
72
73 char CodeGenPrepare::ID = 0;
74 static RegisterPass<CodeGenPrepare> X("codegenprepare",
75                                       "Optimize for code generation");
76
77 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
78   return new CodeGenPrepare(TLI);
79 }
80
81 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
82 ///
83 void CodeGenPrepare::findLoopBackEdges(Function &F) {
84   SmallPtrSet<BasicBlock*, 8> Visited;
85   SmallVector<std::pair<BasicBlock*, succ_iterator>, 8> VisitStack;
86   SmallPtrSet<BasicBlock*, 8> InStack;
87
88   BasicBlock *BB = &F.getEntryBlock();
89   if (succ_begin(BB) == succ_end(BB))
90     return;
91   Visited.insert(BB);
92   VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
93   InStack.insert(BB);
94   do {
95     std::pair<BasicBlock*, succ_iterator> &Top = VisitStack.back();
96     BasicBlock *ParentBB = Top.first;
97     succ_iterator &I = Top.second;
98
99     bool FoundNew = false;
100     while (I != succ_end(ParentBB)) {
101       BB = *I++;
102       if (Visited.insert(BB)) {
103         FoundNew = true;
104         break;
105       }
106       // Successor is in VisitStack, it's a back edge.
107       if (InStack.count(BB))
108         BackEdges.insert(std::make_pair(ParentBB, BB));
109     }
110
111     if (FoundNew) {
112       // Go down one level if there is a unvisited successor.
113       InStack.insert(BB);
114       VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
115     } else {
116       // Go up one level.
117       std::pair<BasicBlock*, succ_iterator> &Pop = VisitStack.back();
118       InStack.erase(Pop.first);
119       VisitStack.pop_back();
120     }
121   } while (!VisitStack.empty());
122 }
123
124
125 bool CodeGenPrepare::runOnFunction(Function &F) {
126   bool EverMadeChange = false;
127
128   // First pass, eliminate blocks that contain only PHI nodes and an
129   // unconditional branch.
130   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
131
132   // Now find loop back edges.
133   findLoopBackEdges(F);
134
135   bool MadeChange = true;
136   while (MadeChange) {
137     MadeChange = false;
138     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
139       MadeChange |= OptimizeBlock(*BB);
140     EverMadeChange |= MadeChange;
141   }
142   return EverMadeChange;
143 }
144
145 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
146 /// and an unconditional branch.  Passes before isel (e.g. LSR/loopsimplify)
147 /// often split edges in ways that are non-optimal for isel.  Start by
148 /// eliminating these blocks so we can split them the way we want them.
149 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
150   bool MadeChange = false;
151   // Note that this intentionally skips the entry block.
152   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
153     BasicBlock *BB = I++;
154
155     // If this block doesn't end with an uncond branch, ignore it.
156     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
157     if (!BI || !BI->isUnconditional())
158       continue;
159
160     // If the instruction before the branch isn't a phi node, then other stuff
161     // is happening here.
162     BasicBlock::iterator BBI = BI;
163     if (BBI != BB->begin()) {
164       --BBI;
165       if (!isa<PHINode>(BBI)) continue;
166     }
167
168     // Do not break infinite loops.
169     BasicBlock *DestBB = BI->getSuccessor(0);
170     if (DestBB == BB)
171       continue;
172
173     if (!CanMergeBlocks(BB, DestBB))
174       continue;
175
176     EliminateMostlyEmptyBlock(BB);
177     MadeChange = true;
178   }
179   return MadeChange;
180 }
181
182 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
183 /// single uncond branch between them, and BB contains no other non-phi
184 /// instructions.
185 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
186                                     const BasicBlock *DestBB) const {
187   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
188   // the successor.  If there are more complex condition (e.g. preheaders),
189   // don't mess around with them.
190   BasicBlock::const_iterator BBI = BB->begin();
191   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
192     for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
193          UI != E; ++UI) {
194       const Instruction *User = cast<Instruction>(*UI);
195       if (User->getParent() != DestBB || !isa<PHINode>(User))
196         return false;
197       // If User is inside DestBB block and it is a PHINode then check
198       // incoming value. If incoming value is not from BB then this is
199       // a complex condition (e.g. preheaders) we want to avoid here.
200       if (User->getParent() == DestBB) {
201         if (const PHINode *UPN = dyn_cast<PHINode>(User))
202           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
203             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
204             if (Insn && Insn->getParent() == BB &&
205                 Insn->getParent() != UPN->getIncomingBlock(I))
206               return false;
207           }
208       }
209     }
210   }
211
212   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
213   // and DestBB may have conflicting incoming values for the block.  If so, we
214   // can't merge the block.
215   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
216   if (!DestBBPN) return true;  // no conflict.
217
218   // Collect the preds of BB.
219   SmallPtrSet<const BasicBlock*, 16> BBPreds;
220   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
221     // It is faster to get preds from a PHI than with pred_iterator.
222     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
223       BBPreds.insert(BBPN->getIncomingBlock(i));
224   } else {
225     BBPreds.insert(pred_begin(BB), pred_end(BB));
226   }
227
228   // Walk the preds of DestBB.
229   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
230     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
231     if (BBPreds.count(Pred)) {   // Common predecessor?
232       BBI = DestBB->begin();
233       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
234         const Value *V1 = PN->getIncomingValueForBlock(Pred);
235         const Value *V2 = PN->getIncomingValueForBlock(BB);
236
237         // If V2 is a phi node in BB, look up what the mapped value will be.
238         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
239           if (V2PN->getParent() == BB)
240             V2 = V2PN->getIncomingValueForBlock(Pred);
241
242         // If there is a conflict, bail out.
243         if (V1 != V2) return false;
244       }
245     }
246   }
247
248   return true;
249 }
250
251
252 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
253 /// an unconditional branch in it.
254 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
255   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
256   BasicBlock *DestBB = BI->getSuccessor(0);
257
258   DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
259
260   // If the destination block has a single pred, then this is a trivial edge,
261   // just collapse it.
262   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
263     if (SinglePred != DestBB) {
264       // Remember if SinglePred was the entry block of the function.  If so, we
265       // will need to move BB back to the entry position.
266       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
267       MergeBasicBlockIntoOnlyPred(DestBB);
268
269       if (isEntry && BB != &BB->getParent()->getEntryBlock())
270         BB->moveBefore(&BB->getParent()->getEntryBlock());
271       
272       DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
273       return;
274     }
275   }
276
277   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
278   // to handle the new incoming edges it is about to have.
279   PHINode *PN;
280   for (BasicBlock::iterator BBI = DestBB->begin();
281        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
282     // Remove the incoming value for BB, and remember it.
283     Value *InVal = PN->removeIncomingValue(BB, false);
284
285     // Two options: either the InVal is a phi node defined in BB or it is some
286     // value that dominates BB.
287     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
288     if (InValPhi && InValPhi->getParent() == BB) {
289       // Add all of the input values of the input PHI as inputs of this phi.
290       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
291         PN->addIncoming(InValPhi->getIncomingValue(i),
292                         InValPhi->getIncomingBlock(i));
293     } else {
294       // Otherwise, add one instance of the dominating value for each edge that
295       // we will be adding.
296       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
297         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
298           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
299       } else {
300         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
301           PN->addIncoming(InVal, *PI);
302       }
303     }
304   }
305
306   // The PHIs are now updated, change everything that refers to BB to use
307   // DestBB and remove BB.
308   BB->replaceAllUsesWith(DestBB);
309   BB->eraseFromParent();
310
311   DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
312 }
313
314
315 /// SplitEdgeNicely - Split the critical edge from TI to its specified
316 /// successor if it will improve codegen.  We only do this if the successor has
317 /// phi nodes (otherwise critical edges are ok).  If there is already another
318 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
319 /// instead of introducing a new block.
320 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
321                      SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> &BackEdges,
322                              Pass *P) {
323   BasicBlock *TIBB = TI->getParent();
324   BasicBlock *Dest = TI->getSuccessor(SuccNum);
325   assert(isa<PHINode>(Dest->begin()) &&
326          "This should only be called if Dest has a PHI!");
327
328   // As a hack, never split backedges of loops.  Even though the copy for any
329   // PHIs inserted on the backedge would be dead for exits from the loop, we
330   // assume that the cost of *splitting* the backedge would be too high.
331   if (BackEdges.count(std::make_pair(TIBB, Dest)))
332     return;
333
334   if (!FactorCommonPreds) {
335     /// TIPHIValues - This array is lazily computed to determine the values of
336     /// PHIs in Dest that TI would provide.
337     SmallVector<Value*, 32> TIPHIValues;
338
339     // Check to see if Dest has any blocks that can be used as a split edge for
340     // this terminator.
341     for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
342       BasicBlock *Pred = *PI;
343       // To be usable, the pred has to end with an uncond branch to the dest.
344       BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
345       if (!PredBr || !PredBr->isUnconditional() ||
346           // Must be empty other than the branch.
347           &Pred->front() != PredBr ||
348           // Cannot be the entry block; its label does not get emitted.
349           Pred == &(Dest->getParent()->getEntryBlock()))
350         continue;
351
352       // Finally, since we know that Dest has phi nodes in it, we have to make
353       // sure that jumping to Pred will have the same affect as going to Dest in
354       // terms of PHI values.
355       PHINode *PN;
356       unsigned PHINo = 0;
357       bool FoundMatch = true;
358       for (BasicBlock::iterator I = Dest->begin();
359            (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
360         if (PHINo == TIPHIValues.size())
361           TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
362
363         // If the PHI entry doesn't work, we can't use this pred.
364         if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
365           FoundMatch = false;
366           break;
367         }
368       }
369
370       // If we found a workable predecessor, change TI to branch to Succ.
371       if (FoundMatch) {
372         Dest->removePredecessor(TIBB);
373         TI->setSuccessor(SuccNum, Pred);
374         return;
375       }
376     }
377
378     SplitCriticalEdge(TI, SuccNum, P, true);
379     return;
380   }
381
382   PHINode *PN;
383   SmallVector<Value*, 8> TIPHIValues;
384   for (BasicBlock::iterator I = Dest->begin();
385        (PN = dyn_cast<PHINode>(I)); ++I)
386     TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
387
388   SmallVector<BasicBlock*, 8> IdenticalPreds;
389   for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
390     BasicBlock *Pred = *PI;
391     if (BackEdges.count(std::make_pair(Pred, Dest)))
392       continue;
393     if (PI == TIBB)
394       IdenticalPreds.push_back(Pred);
395     else {
396       bool Identical = true;
397       unsigned PHINo = 0;
398       for (BasicBlock::iterator I = Dest->begin();
399            (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
400         if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
401           Identical = false;
402           break;
403         }
404       if (Identical)
405         IdenticalPreds.push_back(Pred);
406     }
407   }
408
409   assert(!IdenticalPreds.empty());
410   SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
411                          ".critedge", P);
412 }
413
414
415 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
416 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
417 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
418 /// registers that must be created and coalesced.
419 ///
420 /// Return true if any changes are made.
421 ///
422 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
423   // If this is a noop copy,
424   MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
425   MVT DstVT = TLI.getValueType(CI->getType());
426
427   // This is an fp<->int conversion?
428   if (SrcVT.isInteger() != DstVT.isInteger())
429     return false;
430
431   // If this is an extension, it will be a zero or sign extension, which
432   // isn't a noop.
433   if (SrcVT.bitsLT(DstVT)) return false;
434
435   // If these values will be promoted, find out what they will be promoted
436   // to.  This helps us consider truncates on PPC as noop copies when they
437   // are.
438   if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
439     SrcVT = TLI.getTypeToTransformTo(SrcVT);
440   if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
441     DstVT = TLI.getTypeToTransformTo(DstVT);
442
443   // If, after promotion, these are the same types, this is a noop copy.
444   if (SrcVT != DstVT)
445     return false;
446
447   BasicBlock *DefBB = CI->getParent();
448
449   /// InsertedCasts - Only insert a cast in each block once.
450   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
451
452   bool MadeChange = false;
453   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
454        UI != E; ) {
455     Use &TheUse = UI.getUse();
456     Instruction *User = cast<Instruction>(*UI);
457
458     // Figure out which BB this cast is used in.  For PHI's this is the
459     // appropriate predecessor block.
460     BasicBlock *UserBB = User->getParent();
461     if (PHINode *PN = dyn_cast<PHINode>(User)) {
462       unsigned OpVal = UI.getOperandNo()/2;
463       UserBB = PN->getIncomingBlock(OpVal);
464     }
465
466     // Preincrement use iterator so we don't invalidate it.
467     ++UI;
468
469     // If this user is in the same block as the cast, don't change the cast.
470     if (UserBB == DefBB) continue;
471
472     // If we have already inserted a cast into this block, use it.
473     CastInst *&InsertedCast = InsertedCasts[UserBB];
474
475     if (!InsertedCast) {
476       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
477
478       InsertedCast =
479         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
480                          InsertPt);
481       MadeChange = true;
482     }
483
484     // Replace a use of the cast with a use of the new cast.
485     TheUse = InsertedCast;
486   }
487
488   // If we removed all uses, nuke the cast.
489   if (CI->use_empty()) {
490     CI->eraseFromParent();
491     MadeChange = true;
492   }
493
494   return MadeChange;
495 }
496
497 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
498 /// the number of virtual registers that must be created and coalesced.  This is
499 /// a clear win except on targets with multiple condition code registers
500 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
501 ///
502 /// Return true if any changes are made.
503 static bool OptimizeCmpExpression(CmpInst *CI) {
504   BasicBlock *DefBB = CI->getParent();
505
506   /// InsertedCmp - Only insert a cmp in each block once.
507   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
508
509   bool MadeChange = false;
510   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
511        UI != E; ) {
512     Use &TheUse = UI.getUse();
513     Instruction *User = cast<Instruction>(*UI);
514
515     // Preincrement use iterator so we don't invalidate it.
516     ++UI;
517
518     // Don't bother for PHI nodes.
519     if (isa<PHINode>(User))
520       continue;
521
522     // Figure out which BB this cmp is used in.
523     BasicBlock *UserBB = User->getParent();
524
525     // If this user is in the same block as the cmp, don't change the cmp.
526     if (UserBB == DefBB) continue;
527
528     // If we have already inserted a cmp into this block, use it.
529     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
530
531     if (!InsertedCmp) {
532       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
533
534       InsertedCmp =
535         CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
536                         CI->getOperand(1), "", InsertPt);
537       MadeChange = true;
538     }
539
540     // Replace a use of the cmp with a use of the new cmp.
541     TheUse = InsertedCmp;
542   }
543
544   // If we removed all uses, nuke the cmp.
545   if (CI->use_empty())
546     CI->eraseFromParent();
547
548   return MadeChange;
549 }
550
551 //===----------------------------------------------------------------------===//
552 // Addressing Mode Analysis and Optimization
553 //===----------------------------------------------------------------------===//
554
555 namespace {
556   /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
557   /// which holds actual Value*'s for register values.
558   struct ExtAddrMode : public TargetLowering::AddrMode {
559     Value *BaseReg;
560     Value *ScaledReg;
561     ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
562     void print(OStream &OS) const;
563     void dump() const {
564       print(cerr);
565       cerr << '\n';
566     }
567   };
568 } // end anonymous namespace
569
570 static inline OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
571   AM.print(OS);
572   return OS;
573 }
574
575 void ExtAddrMode::print(OStream &OS) const {
576   bool NeedPlus = false;
577   OS << "[";
578   if (BaseGV)
579     OS << (NeedPlus ? " + " : "")
580        << "GV:%" << BaseGV->getName(), NeedPlus = true;
581
582   if (BaseOffs)
583     OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
584
585   if (BaseReg)
586     OS << (NeedPlus ? " + " : "")
587        << "Base:%" << BaseReg->getName(), NeedPlus = true;
588   if (Scale)
589     OS << (NeedPlus ? " + " : "")
590        << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
591
592   OS << ']';
593 }
594
595 namespace {
596 /// AddressingModeMatcher - This class exposes a single public method, which is
597 /// used to construct a "maximal munch" of the addressing mode for the target
598 /// specified by TLI for an access to "V" with an access type of AccessTy.  This
599 /// returns the addressing mode that is actually matched by value, but also
600 /// returns the list of instructions involved in that addressing computation in
601 /// AddrModeInsts.
602 class AddressingModeMatcher {
603   SmallVectorImpl<Instruction*> &AddrModeInsts;
604   const TargetLowering &TLI;
605
606   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
607   /// the memory instruction that we're computing this address for.
608   const Type *AccessTy;
609   Instruction *MemoryInst;
610   
611   /// AddrMode - This is the addressing mode that we're building up.  This is
612   /// part of the return value of this addressing mode matching stuff.
613   ExtAddrMode &AddrMode;
614   
615   /// IgnoreProfitability - This is set to true when we should not do
616   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
617   /// always returns true.
618   bool IgnoreProfitability;
619   
620   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
621                         const TargetLowering &T, const Type *AT,
622                         Instruction *MI, ExtAddrMode &AM)
623     : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
624     IgnoreProfitability = false;
625   }
626 public:
627   
628   /// Match - Find the maximal addressing mode that a load/store of V can fold,
629   /// give an access type of AccessTy.  This returns a list of involved
630   /// instructions in AddrModeInsts.
631   static ExtAddrMode Match(Value *V, const Type *AccessTy,
632                            Instruction *MemoryInst,
633                            SmallVectorImpl<Instruction*> &AddrModeInsts,
634                            const TargetLowering &TLI) {
635     ExtAddrMode Result;
636
637     bool Success = 
638       AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
639                             MemoryInst, Result).MatchAddr(V, 0);
640     Success = Success; assert(Success && "Couldn't select *anything*?");
641     return Result;
642   }
643 private:
644   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
645   bool MatchAddr(Value *V, unsigned Depth);
646   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
647   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
648                                             ExtAddrMode &AMBefore,
649                                             ExtAddrMode &AMAfter);
650   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
651 };
652 } // end anonymous namespace
653
654 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
655 /// Return true and update AddrMode if this addr mode is legal for the target,
656 /// false if not.
657 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
658                                              unsigned Depth) {
659   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
660   // mode.  Just process that directly.
661   if (Scale == 1)
662     return MatchAddr(ScaleReg, Depth);
663   
664   // If the scale is 0, it takes nothing to add this.
665   if (Scale == 0)
666     return true;
667   
668   // If we already have a scale of this value, we can add to it, otherwise, we
669   // need an available scale field.
670   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
671     return false;
672
673   ExtAddrMode TestAddrMode = AddrMode;
674
675   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
676   // [A+B + A*7] -> [B+A*8].
677   TestAddrMode.Scale += Scale;
678   TestAddrMode.ScaledReg = ScaleReg;
679
680   // If the new address isn't legal, bail out.
681   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
682     return false;
683
684   // It was legal, so commit it.
685   AddrMode = TestAddrMode;
686   
687   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
688   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
689   // X*Scale + C*Scale to addr mode.
690   ConstantInt *CI; Value *AddLHS;
691   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
692       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
693     TestAddrMode.ScaledReg = AddLHS;
694     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
695       
696     // If this addressing mode is legal, commit it and remember that we folded
697     // this instruction.
698     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
699       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
700       AddrMode = TestAddrMode;
701       return true;
702     }
703   }
704
705   // Otherwise, not (x+c)*scale, just return what we have.
706   return true;
707 }
708
709 /// MightBeFoldableInst - This is a little filter, which returns true if an
710 /// addressing computation involving I might be folded into a load/store
711 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
712 /// the set of instructions that MatchOperationAddr can.
713 static bool MightBeFoldableInst(Instruction *I) {
714   switch (I->getOpcode()) {
715   case Instruction::BitCast:
716     // Don't touch identity bitcasts.
717     if (I->getType() == I->getOperand(0)->getType())
718       return false;
719     return isa<PointerType>(I->getType()) || isa<IntegerType>(I->getType());
720   case Instruction::PtrToInt:
721     // PtrToInt is always a noop, as we know that the int type is pointer sized.
722     return true;
723   case Instruction::IntToPtr:
724     // We know the input is intptr_t, so this is foldable.
725     return true;
726   case Instruction::Add:
727     return true;
728   case Instruction::Mul:
729   case Instruction::Shl:
730     // Can only handle X*C and X << C.
731     return isa<ConstantInt>(I->getOperand(1));
732   case Instruction::GetElementPtr:
733     return true;
734   default:
735     return false;
736   }
737 }
738
739
740 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
741 /// fold the operation into the addressing mode.  If so, update the addressing
742 /// mode and return true, otherwise return false without modifying AddrMode.
743 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
744                                                unsigned Depth) {
745   // Avoid exponential behavior on extremely deep expression trees.
746   if (Depth >= 5) return false;
747   
748   switch (Opcode) {
749   case Instruction::PtrToInt:
750     // PtrToInt is always a noop, as we know that the int type is pointer sized.
751     return MatchAddr(AddrInst->getOperand(0), Depth);
752   case Instruction::IntToPtr:
753     // This inttoptr is a no-op if the integer type is pointer sized.
754     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
755         TLI.getPointerTy())
756       return MatchAddr(AddrInst->getOperand(0), Depth);
757     return false;
758   case Instruction::BitCast:
759     // BitCast is always a noop, and we can handle it as long as it is
760     // int->int or pointer->pointer (we don't want int<->fp or something).
761     if ((isa<PointerType>(AddrInst->getOperand(0)->getType()) ||
762          isa<IntegerType>(AddrInst->getOperand(0)->getType())) &&
763         // Don't touch identity bitcasts.  These were probably put here by LSR,
764         // and we don't want to mess around with them.  Assume it knows what it
765         // is doing.
766         AddrInst->getOperand(0)->getType() != AddrInst->getType())
767       return MatchAddr(AddrInst->getOperand(0), Depth);
768     return false;
769   case Instruction::Add: {
770     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
771     ExtAddrMode BackupAddrMode = AddrMode;
772     unsigned OldSize = AddrModeInsts.size();
773     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
774         MatchAddr(AddrInst->getOperand(0), Depth+1))
775       return true;
776     
777     // Restore the old addr mode info.
778     AddrMode = BackupAddrMode;
779     AddrModeInsts.resize(OldSize);
780     
781     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
782     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
783         MatchAddr(AddrInst->getOperand(1), Depth+1))
784       return true;
785     
786     // Otherwise we definitely can't merge the ADD in.
787     AddrMode = BackupAddrMode;
788     AddrModeInsts.resize(OldSize);
789     break;
790   }
791   //case Instruction::Or:
792   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
793   //break;
794   case Instruction::Mul:
795   case Instruction::Shl: {
796     // Can only handle X*C and X << C.
797     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
798     if (!RHS) return false;
799     int64_t Scale = RHS->getSExtValue();
800     if (Opcode == Instruction::Shl)
801       Scale = 1 << Scale;
802     
803     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
804   }
805   case Instruction::GetElementPtr: {
806     // Scan the GEP.  We check it if it contains constant offsets and at most
807     // one variable offset.
808     int VariableOperand = -1;
809     unsigned VariableScale = 0;
810     
811     int64_t ConstantOffset = 0;
812     const TargetData *TD = TLI.getTargetData();
813     gep_type_iterator GTI = gep_type_begin(AddrInst);
814     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
815       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
816         const StructLayout *SL = TD->getStructLayout(STy);
817         unsigned Idx =
818           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
819         ConstantOffset += SL->getElementOffset(Idx);
820       } else {
821         uint64_t TypeSize = TD->getTypePaddedSize(GTI.getIndexedType());
822         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
823           ConstantOffset += CI->getSExtValue()*TypeSize;
824         } else if (TypeSize) {  // Scales of zero don't do anything.
825           // We only allow one variable index at the moment.
826           if (VariableOperand != -1)
827             return false;
828           
829           // Remember the variable index.
830           VariableOperand = i;
831           VariableScale = TypeSize;
832         }
833       }
834     }
835     
836     // A common case is for the GEP to only do a constant offset.  In this case,
837     // just add it to the disp field and check validity.
838     if (VariableOperand == -1) {
839       AddrMode.BaseOffs += ConstantOffset;
840       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
841         // Check to see if we can fold the base pointer in too.
842         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
843           return true;
844       }
845       AddrMode.BaseOffs -= ConstantOffset;
846       return false;
847     }
848
849     // Save the valid addressing mode in case we can't match.
850     ExtAddrMode BackupAddrMode = AddrMode;
851     
852     // Check that this has no base reg yet.  If so, we won't have a place to
853     // put the base of the GEP (assuming it is not a null ptr).
854     bool SetBaseReg = true;
855     if (isa<ConstantPointerNull>(AddrInst->getOperand(0)))
856       SetBaseReg = false;   // null pointer base doesn't need representation.
857     else if (AddrMode.HasBaseReg)
858       return false;  // Base register already specified, can't match GEP.
859     else {
860       // Otherwise, we'll use the GEP base as the BaseReg.
861       AddrMode.HasBaseReg = true;
862       AddrMode.BaseReg = AddrInst->getOperand(0);
863     }
864     
865     // See if the scale and offset amount is valid for this target.
866     AddrMode.BaseOffs += ConstantOffset;
867     
868     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
869                           Depth)) {
870       AddrMode = BackupAddrMode;
871       return false;
872     }
873     
874     // If we have a null as the base of the GEP, folding in the constant offset
875     // plus variable scale is all we can do.
876     if (!SetBaseReg) return true;
877       
878     // If this match succeeded, we know that we can form an address with the
879     // GepBase as the basereg.  Match the base pointer of the GEP more
880     // aggressively by zeroing out BaseReg and rematching.  If the base is
881     // (for example) another GEP, this allows merging in that other GEP into
882     // the addressing mode we're forming.
883     AddrMode.HasBaseReg = false;
884     AddrMode.BaseReg = 0;
885     bool Success = MatchAddr(AddrInst->getOperand(0), Depth+1);
886     assert(Success && "MatchAddr should be able to fill in BaseReg!");
887     Success=Success;
888     return true;
889   }
890   }
891   return false;
892 }
893
894 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
895 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
896 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
897 /// or intptr_t for the target.
898 ///
899 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
900   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
901     // Fold in immediates if legal for the target.
902     AddrMode.BaseOffs += CI->getSExtValue();
903     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
904       return true;
905     AddrMode.BaseOffs -= CI->getSExtValue();
906   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
907     // If this is a global variable, try to fold it into the addressing mode.
908     if (AddrMode.BaseGV == 0) {
909       AddrMode.BaseGV = GV;
910       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
911         return true;
912       AddrMode.BaseGV = 0;
913     }
914   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
915     ExtAddrMode BackupAddrMode = AddrMode;
916     unsigned OldSize = AddrModeInsts.size();
917
918     // Check to see if it is possible to fold this operation.
919     if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
920       // Okay, it's possible to fold this.  Check to see if it is actually
921       // *profitable* to do so.  We use a simple cost model to avoid increasing
922       // register pressure too much.
923       if (I->hasOneUse() ||
924           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
925         AddrModeInsts.push_back(I);
926         return true;
927       }
928       
929       // It isn't profitable to do this, roll back.
930       //cerr << "NOT FOLDING: " << *I;
931       AddrMode = BackupAddrMode;
932       AddrModeInsts.resize(OldSize);
933     }
934   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
935     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
936       return true;
937   } else if (isa<ConstantPointerNull>(Addr)) {
938     // Null pointer gets folded without affecting the addressing mode.
939     return true;
940   }
941
942   // Worse case, the target should support [reg] addressing modes. :)
943   if (!AddrMode.HasBaseReg) {
944     AddrMode.HasBaseReg = true;
945     AddrMode.BaseReg = Addr;
946     // Still check for legality in case the target supports [imm] but not [i+r].
947     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
948       return true;
949     AddrMode.HasBaseReg = false;
950     AddrMode.BaseReg = 0;
951   }
952
953   // If the base register is already taken, see if we can do [r+r].
954   if (AddrMode.Scale == 0) {
955     AddrMode.Scale = 1;
956     AddrMode.ScaledReg = Addr;
957     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
958       return true;
959     AddrMode.Scale = 0;
960     AddrMode.ScaledReg = 0;
961   }
962   // Couldn't match.
963   return false;
964 }
965
966
967 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
968 /// inline asm call are due to memory operands.  If so, return true, otherwise
969 /// return false.
970 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
971                                     const TargetLowering &TLI) {
972   std::vector<InlineAsm::ConstraintInfo>
973   Constraints = IA->ParseConstraints();
974   
975   unsigned ArgNo = 1;   // ArgNo - The operand of the CallInst.
976   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
977     TargetLowering::AsmOperandInfo OpInfo(Constraints[i]);
978     
979     // Compute the value type for each operand.
980     switch (OpInfo.Type) {
981       case InlineAsm::isOutput:
982         if (OpInfo.isIndirect)
983           OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
984         break;
985       case InlineAsm::isInput:
986         OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
987         break;
988       case InlineAsm::isClobber:
989         // Nothing to do.
990         break;
991     }
992     
993     // Compute the constraint code and ConstraintType to use.
994     TLI.ComputeConstraintToUse(OpInfo, SDValue(),
995                              OpInfo.ConstraintType == TargetLowering::C_Memory);
996     
997     // If this asm operand is our Value*, and if it isn't an indirect memory
998     // operand, we can't fold it!
999     if (OpInfo.CallOperandVal == OpVal &&
1000         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
1001          !OpInfo.isIndirect))
1002       return false;
1003   }
1004   
1005   return true;
1006 }
1007
1008
1009 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
1010 /// memory use.  If we find an obviously non-foldable instruction, return true.
1011 /// Add the ultimately found memory instructions to MemoryUses.
1012 static bool FindAllMemoryUses(Instruction *I,
1013                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
1014                               SmallPtrSet<Instruction*, 16> &ConsideredInsts,
1015                               const TargetLowering &TLI) {
1016   // If we already considered this instruction, we're done.
1017   if (!ConsideredInsts.insert(I))
1018     return false;
1019   
1020   // If this is an obviously unfoldable instruction, bail out.
1021   if (!MightBeFoldableInst(I))
1022     return true;
1023
1024   // Loop over all the uses, recursively processing them.
1025   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1026        UI != E; ++UI) {
1027     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1028       MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
1029       continue;
1030     }
1031     
1032     if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
1033       if (UI.getOperandNo() == 0) return true; // Storing addr, not into addr.
1034       MemoryUses.push_back(std::make_pair(SI, UI.getOperandNo()));
1035       continue;
1036     }
1037     
1038     if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
1039       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
1040       if (IA == 0) return true;
1041       
1042       // If this is a memory operand, we're cool, otherwise bail out.
1043       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
1044         return true;
1045       continue;
1046     }
1047     
1048     if (FindAllMemoryUses(cast<Instruction>(*UI), MemoryUses, ConsideredInsts,
1049                           TLI))
1050       return true;
1051   }
1052
1053   return false;
1054 }
1055
1056
1057 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
1058 /// the use site that we're folding it into.  If so, there is no cost to
1059 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
1060 /// that we know are live at the instruction already.
1061 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
1062                                                    Value *KnownLive2) {
1063   // If Val is either of the known-live values, we know it is live!
1064   if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
1065     return true;
1066   
1067   // All values other than instructions and arguments (e.g. constants) are live.
1068   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
1069   
1070   // If Val is a constant sized alloca in the entry block, it is live, this is
1071   // true because it is just a reference to the stack/frame pointer, which is
1072   // live for the whole function.
1073   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
1074     if (AI->isStaticAlloca())
1075       return true;
1076   
1077   // Check to see if this value is already used in the memory instruction's
1078   // block.  If so, it's already live into the block at the very least, so we
1079   // can reasonably fold it.
1080   BasicBlock *MemBB = MemoryInst->getParent();
1081   for (Value::use_iterator UI = Val->use_begin(), E = Val->use_end();
1082        UI != E; ++UI)
1083     // We know that uses of arguments and instructions have to be instructions.
1084     if (cast<Instruction>(*UI)->getParent() == MemBB)
1085       return true;
1086   
1087   return false;
1088 }
1089
1090
1091
1092 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
1093 /// mode of the machine to fold the specified instruction into a load or store
1094 /// that ultimately uses it.  However, the specified instruction has multiple
1095 /// uses.  Given this, it may actually increase register pressure to fold it
1096 /// into the load.  For example, consider this code:
1097 ///
1098 ///     X = ...
1099 ///     Y = X+1
1100 ///     use(Y)   -> nonload/store
1101 ///     Z = Y+1
1102 ///     load Z
1103 ///
1104 /// In this case, Y has multiple uses, and can be folded into the load of Z
1105 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
1106 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
1107 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
1108 /// number of computations either.
1109 ///
1110 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
1111 /// X was live across 'load Z' for other reasons, we actually *would* want to
1112 /// fold the addressing mode in the Z case.  This would make Y die earlier.
1113 bool AddressingModeMatcher::
1114 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1115                                      ExtAddrMode &AMAfter) {
1116   if (IgnoreProfitability) return true;
1117   
1118   // AMBefore is the addressing mode before this instruction was folded into it,
1119   // and AMAfter is the addressing mode after the instruction was folded.  Get
1120   // the set of registers referenced by AMAfter and subtract out those
1121   // referenced by AMBefore: this is the set of values which folding in this
1122   // address extends the lifetime of.
1123   //
1124   // Note that there are only two potential values being referenced here,
1125   // BaseReg and ScaleReg (global addresses are always available, as are any
1126   // folded immediates).
1127   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
1128   
1129   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1130   // lifetime wasn't extended by adding this instruction.
1131   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1132     BaseReg = 0;
1133   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1134     ScaledReg = 0;
1135
1136   // If folding this instruction (and it's subexprs) didn't extend any live
1137   // ranges, we're ok with it.
1138   if (BaseReg == 0 && ScaledReg == 0)
1139     return true;
1140
1141   // If all uses of this instruction are ultimately load/store/inlineasm's,
1142   // check to see if their addressing modes will include this instruction.  If
1143   // so, we can fold it into all uses, so it doesn't matter if it has multiple
1144   // uses.
1145   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1146   SmallPtrSet<Instruction*, 16> ConsideredInsts;
1147   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
1148     return false;  // Has a non-memory, non-foldable use!
1149   
1150   // Now that we know that all uses of this instruction are part of a chain of
1151   // computation involving only operations that could theoretically be folded
1152   // into a memory use, loop over each of these uses and see if they could
1153   // *actually* fold the instruction.
1154   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1155   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1156     Instruction *User = MemoryUses[i].first;
1157     unsigned OpNo = MemoryUses[i].second;
1158     
1159     // Get the access type of this use.  If the use isn't a pointer, we don't
1160     // know what it accesses.
1161     Value *Address = User->getOperand(OpNo);
1162     if (!isa<PointerType>(Address->getType()))
1163       return false;
1164     const Type *AddressAccessTy =
1165       cast<PointerType>(Address->getType())->getElementType();
1166     
1167     // Do a match against the root of this address, ignoring profitability. This
1168     // will tell us if the addressing mode for the memory operation will
1169     // *actually* cover the shared instruction.
1170     ExtAddrMode Result;
1171     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
1172                                   MemoryInst, Result);
1173     Matcher.IgnoreProfitability = true;
1174     bool Success = Matcher.MatchAddr(Address, 0);
1175     Success = Success; assert(Success && "Couldn't select *anything*?");
1176
1177     // If the match didn't cover I, then it won't be shared by it.
1178     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1179                   I) == MatchedAddrModeInsts.end())
1180       return false;
1181     
1182     MatchedAddrModeInsts.clear();
1183   }
1184   
1185   return true;
1186 }
1187
1188
1189 //===----------------------------------------------------------------------===//
1190 // Memory Optimization
1191 //===----------------------------------------------------------------------===//
1192
1193 /// IsNonLocalValue - Return true if the specified values are defined in a
1194 /// different basic block than BB.
1195 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1196   if (Instruction *I = dyn_cast<Instruction>(V))
1197     return I->getParent() != BB;
1198   return false;
1199 }
1200
1201 /// OptimizeMemoryInst - Load and Store Instructions have often have
1202 /// addressing modes that can do significant amounts of computation.  As such,
1203 /// instruction selection will try to get the load or store to do as much
1204 /// computation as possible for the program.  The problem is that isel can only
1205 /// see within a single block.  As such, we sink as much legal addressing mode
1206 /// stuff into the block as possible.
1207 ///
1208 /// This method is used to optimize both load/store and inline asms with memory
1209 /// operands.
1210 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
1211                                         const Type *AccessTy,
1212                                         DenseMap<Value*,Value*> &SunkAddrs) {
1213   // Figure out what addressing mode will be built up for this operation.
1214   SmallVector<Instruction*, 16> AddrModeInsts;
1215   ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
1216                                                       AddrModeInsts, *TLI);
1217
1218   // Check to see if any of the instructions supersumed by this addr mode are
1219   // non-local to I's BB.
1220   bool AnyNonLocal = false;
1221   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
1222     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
1223       AnyNonLocal = true;
1224       break;
1225     }
1226   }
1227
1228   // If all the instructions matched are already in this BB, don't do anything.
1229   if (!AnyNonLocal) {
1230     DEBUG(cerr << "CGP: Found      local addrmode: " << AddrMode << "\n");
1231     return false;
1232   }
1233
1234   // Insert this computation right after this user.  Since our caller is
1235   // scanning from the top of the BB to the bottom, reuse of the expr are
1236   // guaranteed to happen later.
1237   BasicBlock::iterator InsertPt = MemoryInst;
1238
1239   // Now that we determined the addressing expression we want to use and know
1240   // that we have to sink it into this block.  Check to see if we have already
1241   // done this for some other load/store instr in this block.  If so, reuse the
1242   // computation.
1243   Value *&SunkAddr = SunkAddrs[Addr];
1244   if (SunkAddr) {
1245     DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
1246     if (SunkAddr->getType() != Addr->getType())
1247       SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
1248   } else {
1249     DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
1250     const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
1251
1252     Value *Result = 0;
1253     // Start with the scale value.
1254     if (AddrMode.Scale) {
1255       Value *V = AddrMode.ScaledReg;
1256       if (V->getType() == IntPtrTy) {
1257         // done.
1258       } else if (isa<PointerType>(V->getType())) {
1259         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1260       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1261                  cast<IntegerType>(V->getType())->getBitWidth()) {
1262         V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
1263       } else {
1264         V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
1265       }
1266       if (AddrMode.Scale != 1)
1267         V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
1268                                                           AddrMode.Scale),
1269                                       "sunkaddr", InsertPt);
1270       Result = V;
1271     }
1272
1273     // Add in the base register.
1274     if (AddrMode.BaseReg) {
1275       Value *V = AddrMode.BaseReg;
1276       if (V->getType() != IntPtrTy)
1277         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1278       if (Result)
1279         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
1280       else
1281         Result = V;
1282     }
1283
1284     // Add in the BaseGV if present.
1285     if (AddrMode.BaseGV) {
1286       Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
1287                                   InsertPt);
1288       if (Result)
1289         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
1290       else
1291         Result = V;
1292     }
1293
1294     // Add in the Base Offset if present.
1295     if (AddrMode.BaseOffs) {
1296       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1297       if (Result)
1298         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
1299       else
1300         Result = V;
1301     }
1302
1303     if (Result == 0)
1304       SunkAddr = Constant::getNullValue(Addr->getType());
1305     else
1306       SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
1307   }
1308
1309   MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
1310
1311   if (Addr->use_empty())
1312     RecursivelyDeleteTriviallyDeadInstructions(Addr);
1313   return true;
1314 }
1315
1316 /// OptimizeInlineAsmInst - If there are any memory operands, use
1317 /// OptimizeMemoryInst to sink their address computing into the block when
1318 /// possible / profitable.
1319 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
1320                                            DenseMap<Value*,Value*> &SunkAddrs) {
1321   bool MadeChange = false;
1322   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
1323
1324   // Do a prepass over the constraints, canonicalizing them, and building up the
1325   // ConstraintOperands list.
1326   std::vector<InlineAsm::ConstraintInfo>
1327     ConstraintInfos = IA->ParseConstraints();
1328
1329   /// ConstraintOperands - Information about all of the constraints.
1330   std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
1331   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
1332   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
1333     ConstraintOperands.
1334       push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
1335     TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
1336
1337     // Compute the value type for each operand.
1338     switch (OpInfo.Type) {
1339     case InlineAsm::isOutput:
1340       if (OpInfo.isIndirect)
1341         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1342       break;
1343     case InlineAsm::isInput:
1344       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1345       break;
1346     case InlineAsm::isClobber:
1347       // Nothing to do.
1348       break;
1349     }
1350
1351     // Compute the constraint code and ConstraintType to use.
1352     TLI->ComputeConstraintToUse(OpInfo, SDValue(),
1353                              OpInfo.ConstraintType == TargetLowering::C_Memory);
1354
1355     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1356         OpInfo.isIndirect) {
1357       Value *OpVal = OpInfo.CallOperandVal;
1358       MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
1359     }
1360   }
1361
1362   return MadeChange;
1363 }
1364
1365 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1366   BasicBlock *DefBB = I->getParent();
1367
1368   // If both result of the {s|z}xt and its source are live out, rewrite all
1369   // other uses of the source with result of extension.
1370   Value *Src = I->getOperand(0);
1371   if (Src->hasOneUse())
1372     return false;
1373
1374   // Only do this xform if truncating is free.
1375   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1376     return false;
1377
1378   // Only safe to perform the optimization if the source is also defined in
1379   // this block.
1380   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1381     return false;
1382
1383   bool DefIsLiveOut = false;
1384   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1385        UI != E; ++UI) {
1386     Instruction *User = cast<Instruction>(*UI);
1387
1388     // Figure out which BB this ext is used in.
1389     BasicBlock *UserBB = User->getParent();
1390     if (UserBB == DefBB) continue;
1391     DefIsLiveOut = true;
1392     break;
1393   }
1394   if (!DefIsLiveOut)
1395     return false;
1396
1397   // Make sure non of the uses are PHI nodes.
1398   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1399        UI != E; ++UI) {
1400     Instruction *User = cast<Instruction>(*UI);
1401     BasicBlock *UserBB = User->getParent();
1402     if (UserBB == DefBB) continue;
1403     // Be conservative. We don't want this xform to end up introducing
1404     // reloads just before load / store instructions.
1405     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1406       return false;
1407   }
1408
1409   // InsertedTruncs - Only insert one trunc in each block once.
1410   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1411
1412   bool MadeChange = false;
1413   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1414        UI != E; ++UI) {
1415     Use &TheUse = UI.getUse();
1416     Instruction *User = cast<Instruction>(*UI);
1417
1418     // Figure out which BB this ext is used in.
1419     BasicBlock *UserBB = User->getParent();
1420     if (UserBB == DefBB) continue;
1421
1422     // Both src and def are live in this block. Rewrite the use.
1423     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1424
1425     if (!InsertedTrunc) {
1426       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
1427
1428       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1429     }
1430
1431     // Replace a use of the {s|z}ext source with a use of the result.
1432     TheUse = InsertedTrunc;
1433
1434     MadeChange = true;
1435   }
1436
1437   return MadeChange;
1438 }
1439
1440 // In this pass we look for GEP and cast instructions that are used
1441 // across basic blocks and rewrite them to improve basic-block-at-a-time
1442 // selection.
1443 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1444   bool MadeChange = false;
1445
1446   // Split all critical edges where the dest block has a PHI.
1447   TerminatorInst *BBTI = BB.getTerminator();
1448   if (BBTI->getNumSuccessors() > 1) {
1449     for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
1450       BasicBlock *SuccBB = BBTI->getSuccessor(i);
1451       if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
1452         SplitEdgeNicely(BBTI, i, BackEdges, this);
1453     }
1454   }
1455
1456   // Keep track of non-local addresses that have been sunk into this block.
1457   // This allows us to avoid inserting duplicate code for blocks with multiple
1458   // load/stores of the same address.
1459   DenseMap<Value*, Value*> SunkAddrs;
1460
1461   for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1462     Instruction *I = BBI++;
1463
1464     if (CastInst *CI = dyn_cast<CastInst>(I)) {
1465       // If the source of the cast is a constant, then this should have
1466       // already been constant folded.  The only reason NOT to constant fold
1467       // it is if something (e.g. LSR) was careful to place the constant
1468       // evaluation in a block other than then one that uses it (e.g. to hoist
1469       // the address of globals out of a loop).  If this is the case, we don't
1470       // want to forward-subst the cast.
1471       if (isa<Constant>(CI->getOperand(0)))
1472         continue;
1473
1474       bool Change = false;
1475       if (TLI) {
1476         Change = OptimizeNoopCopyExpression(CI, *TLI);
1477         MadeChange |= Change;
1478       }
1479
1480       if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
1481         MadeChange |= OptimizeExtUses(I);
1482     } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1483       MadeChange |= OptimizeCmpExpression(CI);
1484     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1485       if (TLI)
1486         MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1487                                          SunkAddrs);
1488     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1489       if (TLI)
1490         MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1491                                          SI->getOperand(0)->getType(),
1492                                          SunkAddrs);
1493     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1494       if (GEPI->hasAllZeroIndices()) {
1495         /// The GEP operand must be a pointer, so must its result -> BitCast
1496         Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1497                                           GEPI->getName(), GEPI);
1498         GEPI->replaceAllUsesWith(NC);
1499         GEPI->eraseFromParent();
1500         MadeChange = true;
1501         BBI = NC;
1502       }
1503     } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1504       // If we found an inline asm expession, and if the target knows how to
1505       // lower it to normal LLVM code, do so now.
1506       if (TLI && isa<InlineAsm>(CI->getCalledValue()))
1507         if (const TargetAsmInfo *TAI =
1508             TLI->getTargetMachine().getTargetAsmInfo()) {
1509           if (TAI->ExpandInlineAsm(CI))
1510             BBI = BB.begin();
1511           else
1512             // Sink address computing for memory operands into the block.
1513             MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
1514         }
1515     }
1516   }
1517
1518   return MadeChange;
1519 }