Convert the first batch of passes to use LLVMContext.
[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/IntrinsicInst.h"
24 #include "llvm/LLVMContext.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Target/TargetAsmInfo.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
31 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
32 #include "llvm/Transforms/Utils/Local.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/SmallSet.h"
35 #include "llvm/Assembly/Writer.h"
36 #include "llvm/Support/CallSite.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/GetElementPtrTypeIterator.h"
41 #include "llvm/Support/PatternMatch.h"
42 using namespace llvm;
43 using namespace llvm::PatternMatch;
44
45 static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
46                                        cl::init(false), cl::Hidden);
47
48 namespace {
49   class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
50     /// TLI - Keep a pointer of a TargetLowering to consult for determining
51     /// transformation profitability.
52     const TargetLowering *TLI;
53
54     /// BackEdges - Keep a set of all the loop back edges.
55     ///
56     SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
57   public:
58     static char ID; // Pass identification, replacement for typeid
59     explicit CodeGenPrepare(const TargetLowering *tli = 0)
60       : FunctionPass(&ID), TLI(tli) {}
61     bool runOnFunction(Function &F);
62
63   private:
64     bool EliminateMostlyEmptyBlocks(Function &F);
65     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
66     void EliminateMostlyEmptyBlock(BasicBlock *BB);
67     bool OptimizeBlock(BasicBlock &BB);
68     bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
69                             DenseMap<Value*,Value*> &SunkAddrs);
70     bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
71                                DenseMap<Value*,Value*> &SunkAddrs);
72     bool OptimizeExtUses(Instruction *I);
73     void findLoopBackEdges(const Function &F);
74   };
75 }
76
77 char CodeGenPrepare::ID = 0;
78 static RegisterPass<CodeGenPrepare> X("codegenprepare",
79                                       "Optimize for code generation");
80
81 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
82   return new CodeGenPrepare(TLI);
83 }
84
85 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
86 ///
87 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
88   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
89   FindFunctionBackedges(F, Edges);
90   
91   BackEdges.insert(Edges.begin(), Edges.end());
92 }
93
94
95 bool CodeGenPrepare::runOnFunction(Function &F) {
96   bool EverMadeChange = false;
97
98   // First pass, eliminate blocks that contain only PHI nodes and an
99   // unconditional branch.
100   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
101
102   // Now find loop back edges.
103   findLoopBackEdges(F);
104
105   bool MadeChange = true;
106   while (MadeChange) {
107     MadeChange = false;
108     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
109       MadeChange |= OptimizeBlock(*BB);
110     EverMadeChange |= MadeChange;
111   }
112   return EverMadeChange;
113 }
114
115 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
116 /// debug info directives, and an unconditional branch.  Passes before isel
117 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
118 /// isel.  Start by eliminating these blocks so we can split them the way we
119 /// want them.
120 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
121   bool MadeChange = false;
122   // Note that this intentionally skips the entry block.
123   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
124     BasicBlock *BB = I++;
125
126     // If this block doesn't end with an uncond branch, ignore it.
127     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
128     if (!BI || !BI->isUnconditional())
129       continue;
130
131     // If the instruction before the branch (skipping debug info) isn't a phi
132     // node, then other stuff is happening here.
133     BasicBlock::iterator BBI = BI;
134     if (BBI != BB->begin()) {
135       --BBI;
136       while (isa<DbgInfoIntrinsic>(BBI)) {
137         if (BBI == BB->begin())
138           break;
139         --BBI;
140       }
141       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
142         continue;
143     }
144
145     // Do not break infinite loops.
146     BasicBlock *DestBB = BI->getSuccessor(0);
147     if (DestBB == BB)
148       continue;
149
150     if (!CanMergeBlocks(BB, DestBB))
151       continue;
152
153     EliminateMostlyEmptyBlock(BB);
154     MadeChange = true;
155   }
156   return MadeChange;
157 }
158
159 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
160 /// single uncond branch between them, and BB contains no other non-phi
161 /// instructions.
162 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
163                                     const BasicBlock *DestBB) const {
164   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
165   // the successor.  If there are more complex condition (e.g. preheaders),
166   // don't mess around with them.
167   BasicBlock::const_iterator BBI = BB->begin();
168   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
169     for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
170          UI != E; ++UI) {
171       const Instruction *User = cast<Instruction>(*UI);
172       if (User->getParent() != DestBB || !isa<PHINode>(User))
173         return false;
174       // If User is inside DestBB block and it is a PHINode then check
175       // incoming value. If incoming value is not from BB then this is
176       // a complex condition (e.g. preheaders) we want to avoid here.
177       if (User->getParent() == DestBB) {
178         if (const PHINode *UPN = dyn_cast<PHINode>(User))
179           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
180             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
181             if (Insn && Insn->getParent() == BB &&
182                 Insn->getParent() != UPN->getIncomingBlock(I))
183               return false;
184           }
185       }
186     }
187   }
188
189   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
190   // and DestBB may have conflicting incoming values for the block.  If so, we
191   // can't merge the block.
192   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
193   if (!DestBBPN) return true;  // no conflict.
194
195   // Collect the preds of BB.
196   SmallPtrSet<const BasicBlock*, 16> BBPreds;
197   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
198     // It is faster to get preds from a PHI than with pred_iterator.
199     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
200       BBPreds.insert(BBPN->getIncomingBlock(i));
201   } else {
202     BBPreds.insert(pred_begin(BB), pred_end(BB));
203   }
204
205   // Walk the preds of DestBB.
206   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
207     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
208     if (BBPreds.count(Pred)) {   // Common predecessor?
209       BBI = DestBB->begin();
210       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
211         const Value *V1 = PN->getIncomingValueForBlock(Pred);
212         const Value *V2 = PN->getIncomingValueForBlock(BB);
213
214         // If V2 is a phi node in BB, look up what the mapped value will be.
215         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
216           if (V2PN->getParent() == BB)
217             V2 = V2PN->getIncomingValueForBlock(Pred);
218
219         // If there is a conflict, bail out.
220         if (V1 != V2) return false;
221       }
222     }
223   }
224
225   return true;
226 }
227
228
229 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
230 /// an unconditional branch in it.
231 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
232   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
233   BasicBlock *DestBB = BI->getSuccessor(0);
234
235   DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
236
237   // If the destination block has a single pred, then this is a trivial edge,
238   // just collapse it.
239   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
240     if (SinglePred != DestBB) {
241       // Remember if SinglePred was the entry block of the function.  If so, we
242       // will need to move BB back to the entry position.
243       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
244       MergeBasicBlockIntoOnlyPred(DestBB);
245
246       if (isEntry && BB != &BB->getParent()->getEntryBlock())
247         BB->moveBefore(&BB->getParent()->getEntryBlock());
248       
249       DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
250       return;
251     }
252   }
253
254   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
255   // to handle the new incoming edges it is about to have.
256   PHINode *PN;
257   for (BasicBlock::iterator BBI = DestBB->begin();
258        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
259     // Remove the incoming value for BB, and remember it.
260     Value *InVal = PN->removeIncomingValue(BB, false);
261
262     // Two options: either the InVal is a phi node defined in BB or it is some
263     // value that dominates BB.
264     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
265     if (InValPhi && InValPhi->getParent() == BB) {
266       // Add all of the input values of the input PHI as inputs of this phi.
267       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
268         PN->addIncoming(InValPhi->getIncomingValue(i),
269                         InValPhi->getIncomingBlock(i));
270     } else {
271       // Otherwise, add one instance of the dominating value for each edge that
272       // we will be adding.
273       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
274         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
275           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
276       } else {
277         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
278           PN->addIncoming(InVal, *PI);
279       }
280     }
281   }
282
283   // The PHIs are now updated, change everything that refers to BB to use
284   // DestBB and remove BB.
285   BB->replaceAllUsesWith(DestBB);
286   BB->eraseFromParent();
287
288   DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
289 }
290
291
292 /// SplitEdgeNicely - Split the critical edge from TI to its specified
293 /// successor if it will improve codegen.  We only do this if the successor has
294 /// phi nodes (otherwise critical edges are ok).  If there is already another
295 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
296 /// instead of introducing a new block.
297 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
298                      SmallSet<std::pair<const BasicBlock*,
299                                         const BasicBlock*>, 8> &BackEdges,
300                              Pass *P) {
301   BasicBlock *TIBB = TI->getParent();
302   BasicBlock *Dest = TI->getSuccessor(SuccNum);
303   assert(isa<PHINode>(Dest->begin()) &&
304          "This should only be called if Dest has a PHI!");
305
306   // Do not split edges to EH landing pads.
307   if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI)) {
308     if (Invoke->getSuccessor(1) == Dest)
309       return;
310   }
311
312   // As a hack, never split backedges of loops.  Even though the copy for any
313   // PHIs inserted on the backedge would be dead for exits from the loop, we
314   // assume that the cost of *splitting* the backedge would be too high.
315   if (BackEdges.count(std::make_pair(TIBB, Dest)))
316     return;
317
318   if (!FactorCommonPreds) {
319     /// TIPHIValues - This array is lazily computed to determine the values of
320     /// PHIs in Dest that TI would provide.
321     SmallVector<Value*, 32> TIPHIValues;
322
323     // Check to see if Dest has any blocks that can be used as a split edge for
324     // this terminator.
325     for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
326       BasicBlock *Pred = *PI;
327       // To be usable, the pred has to end with an uncond branch to the dest.
328       BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
329       if (!PredBr || !PredBr->isUnconditional())
330         continue;
331       // Must be empty other than the branch and debug info.
332       BasicBlock::iterator I = Pred->begin();
333       while (isa<DbgInfoIntrinsic>(I))
334         I++;
335       if (dyn_cast<Instruction>(I) != PredBr)
336         continue;
337       // Cannot be the entry block; its label does not get emitted.
338       if (Pred == &(Dest->getParent()->getEntryBlock()))
339         continue;
340
341       // Finally, since we know that Dest has phi nodes in it, we have to make
342       // sure that jumping to Pred will have the same effect as going to Dest in
343       // terms of PHI values.
344       PHINode *PN;
345       unsigned PHINo = 0;
346       bool FoundMatch = true;
347       for (BasicBlock::iterator I = Dest->begin();
348            (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
349         if (PHINo == TIPHIValues.size())
350           TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
351
352         // If the PHI entry doesn't work, we can't use this pred.
353         if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
354           FoundMatch = false;
355           break;
356         }
357       }
358
359       // If we found a workable predecessor, change TI to branch to Succ.
360       if (FoundMatch) {
361         Dest->removePredecessor(TIBB);
362         TI->setSuccessor(SuccNum, Pred);
363         return;
364       }
365     }
366
367     SplitCriticalEdge(TI, SuccNum, P, true);
368     return;
369   }
370
371   PHINode *PN;
372   SmallVector<Value*, 8> TIPHIValues;
373   for (BasicBlock::iterator I = Dest->begin();
374        (PN = dyn_cast<PHINode>(I)); ++I)
375     TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
376
377   SmallVector<BasicBlock*, 8> IdenticalPreds;
378   for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
379     BasicBlock *Pred = *PI;
380     if (BackEdges.count(std::make_pair(Pred, Dest)))
381       continue;
382     if (PI == TIBB)
383       IdenticalPreds.push_back(Pred);
384     else {
385       bool Identical = true;
386       unsigned PHINo = 0;
387       for (BasicBlock::iterator I = Dest->begin();
388            (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
389         if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
390           Identical = false;
391           break;
392         }
393       if (Identical)
394         IdenticalPreds.push_back(Pred);
395     }
396   }
397
398   assert(!IdenticalPreds.empty());
399   SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
400                          ".critedge", P);
401 }
402
403
404 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
405 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
406 /// sink it into user blocks to reduce the number of virtual
407 /// registers that must be created and coalesced.
408 ///
409 /// Return true if any changes are made.
410 ///
411 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
412   // If this is a noop copy,
413   MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
414   MVT DstVT = TLI.getValueType(CI->getType());
415
416   // This is an fp<->int conversion?
417   if (SrcVT.isInteger() != DstVT.isInteger())
418     return false;
419
420   // If this is an extension, it will be a zero or sign extension, which
421   // isn't a noop.
422   if (SrcVT.bitsLT(DstVT)) return false;
423
424   // If these values will be promoted, find out what they will be promoted
425   // to.  This helps us consider truncates on PPC as noop copies when they
426   // are.
427   if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
428     SrcVT = TLI.getTypeToTransformTo(SrcVT);
429   if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
430     DstVT = TLI.getTypeToTransformTo(DstVT);
431
432   // If, after promotion, these are the same types, this is a noop copy.
433   if (SrcVT != DstVT)
434     return false;
435
436   BasicBlock *DefBB = CI->getParent();
437
438   /// InsertedCasts - Only insert a cast in each block once.
439   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
440
441   bool MadeChange = false;
442   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
443        UI != E; ) {
444     Use &TheUse = UI.getUse();
445     Instruction *User = cast<Instruction>(*UI);
446
447     // Figure out which BB this cast is used in.  For PHI's this is the
448     // appropriate predecessor block.
449     BasicBlock *UserBB = User->getParent();
450     if (PHINode *PN = dyn_cast<PHINode>(User)) {
451       UserBB = PN->getIncomingBlock(UI);
452     }
453
454     // Preincrement use iterator so we don't invalidate it.
455     ++UI;
456
457     // If this user is in the same block as the cast, don't change the cast.
458     if (UserBB == DefBB) continue;
459
460     // If we have already inserted a cast into this block, use it.
461     CastInst *&InsertedCast = InsertedCasts[UserBB];
462
463     if (!InsertedCast) {
464       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
465
466       InsertedCast =
467         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
468                          InsertPt);
469       MadeChange = true;
470     }
471
472     // Replace a use of the cast with a use of the new cast.
473     TheUse = InsertedCast;
474   }
475
476   // If we removed all uses, nuke the cast.
477   if (CI->use_empty()) {
478     CI->eraseFromParent();
479     MadeChange = true;
480   }
481
482   return MadeChange;
483 }
484
485 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
486 /// the number of virtual registers that must be created and coalesced.  This is
487 /// a clear win except on targets with multiple condition code registers
488 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
489 ///
490 /// Return true if any changes are made.
491 static bool OptimizeCmpExpression(CmpInst *CI) {
492   BasicBlock *DefBB = CI->getParent();
493
494   /// InsertedCmp - Only insert a cmp in each block once.
495   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
496
497   bool MadeChange = false;
498   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
499        UI != E; ) {
500     Use &TheUse = UI.getUse();
501     Instruction *User = cast<Instruction>(*UI);
502
503     // Preincrement use iterator so we don't invalidate it.
504     ++UI;
505
506     // Don't bother for PHI nodes.
507     if (isa<PHINode>(User))
508       continue;
509
510     // Figure out which BB this cmp is used in.
511     BasicBlock *UserBB = User->getParent();
512
513     // If this user is in the same block as the cmp, don't change the cmp.
514     if (UserBB == DefBB) continue;
515
516     // If we have already inserted a cmp into this block, use it.
517     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
518
519     if (!InsertedCmp) {
520       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
521
522       InsertedCmp =
523         CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
524                         CI->getOperand(1), "", InsertPt);
525       MadeChange = true;
526     }
527
528     // Replace a use of the cmp with a use of the new cmp.
529     TheUse = InsertedCmp;
530   }
531
532   // If we removed all uses, nuke the cmp.
533   if (CI->use_empty())
534     CI->eraseFromParent();
535
536   return MadeChange;
537 }
538
539 //===----------------------------------------------------------------------===//
540 // Memory Optimization
541 //===----------------------------------------------------------------------===//
542
543 /// IsNonLocalValue - Return true if the specified values are defined in a
544 /// different basic block than BB.
545 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
546   if (Instruction *I = dyn_cast<Instruction>(V))
547     return I->getParent() != BB;
548   return false;
549 }
550
551 /// OptimizeMemoryInst - Load and Store Instructions have often have
552 /// addressing modes that can do significant amounts of computation.  As such,
553 /// instruction selection will try to get the load or store to do as much
554 /// computation as possible for the program.  The problem is that isel can only
555 /// see within a single block.  As such, we sink as much legal addressing mode
556 /// stuff into the block as possible.
557 ///
558 /// This method is used to optimize both load/store and inline asms with memory
559 /// operands.
560 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
561                                         const Type *AccessTy,
562                                         DenseMap<Value*,Value*> &SunkAddrs) {
563   // Figure out what addressing mode will be built up for this operation.
564   SmallVector<Instruction*, 16> AddrModeInsts;
565   ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
566                                                       AddrModeInsts, *TLI);
567
568   // Check to see if any of the instructions supersumed by this addr mode are
569   // non-local to I's BB.
570   bool AnyNonLocal = false;
571   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
572     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
573       AnyNonLocal = true;
574       break;
575     }
576   }
577
578   // If all the instructions matched are already in this BB, don't do anything.
579   if (!AnyNonLocal) {
580     DEBUG(cerr << "CGP: Found      local addrmode: " << AddrMode << "\n");
581     return false;
582   }
583
584   // Insert this computation right after this user.  Since our caller is
585   // scanning from the top of the BB to the bottom, reuse of the expr are
586   // guaranteed to happen later.
587   BasicBlock::iterator InsertPt = MemoryInst;
588
589   // Now that we determined the addressing expression we want to use and know
590   // that we have to sink it into this block.  Check to see if we have already
591   // done this for some other load/store instr in this block.  If so, reuse the
592   // computation.
593   Value *&SunkAddr = SunkAddrs[Addr];
594   if (SunkAddr) {
595     DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
596                << *MemoryInst);
597     if (SunkAddr->getType() != Addr->getType())
598       SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
599   } else {
600     DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
601                << *MemoryInst);
602     const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
603
604     Value *Result = 0;
605     // Start with the scale value.
606     if (AddrMode.Scale) {
607       Value *V = AddrMode.ScaledReg;
608       if (V->getType() == IntPtrTy) {
609         // done.
610       } else if (isa<PointerType>(V->getType())) {
611         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
612       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
613                  cast<IntegerType>(V->getType())->getBitWidth()) {
614         V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
615       } else {
616         V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
617       }
618       if (AddrMode.Scale != 1)
619         V = BinaryOperator::CreateMul(V, Context->getConstantInt(IntPtrTy,
620                                                                 AddrMode.Scale),
621                                       "sunkaddr", InsertPt);
622       Result = V;
623     }
624
625     // Add in the base register.
626     if (AddrMode.BaseReg) {
627       Value *V = AddrMode.BaseReg;
628       if (isa<PointerType>(V->getType()))
629         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
630       if (V->getType() != IntPtrTy)
631         V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
632                                         "sunkaddr", InsertPt);
633       if (Result)
634         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
635       else
636         Result = V;
637     }
638
639     // Add in the BaseGV if present.
640     if (AddrMode.BaseGV) {
641       Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
642                                   InsertPt);
643       if (Result)
644         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
645       else
646         Result = V;
647     }
648
649     // Add in the Base Offset if present.
650     if (AddrMode.BaseOffs) {
651       Value *V = Context->getConstantInt(IntPtrTy, AddrMode.BaseOffs);
652       if (Result)
653         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
654       else
655         Result = V;
656     }
657
658     if (Result == 0)
659       SunkAddr = Context->getNullValue(Addr->getType());
660     else
661       SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
662   }
663
664   MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
665
666   if (Addr->use_empty())
667     RecursivelyDeleteTriviallyDeadInstructions(Addr);
668   return true;
669 }
670
671 /// OptimizeInlineAsmInst - If there are any memory operands, use
672 /// OptimizeMemoryInst to sink their address computing into the block when
673 /// possible / profitable.
674 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
675                                            DenseMap<Value*,Value*> &SunkAddrs) {
676   bool MadeChange = false;
677   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
678
679   // Do a prepass over the constraints, canonicalizing them, and building up the
680   // ConstraintOperands list.
681   std::vector<InlineAsm::ConstraintInfo>
682     ConstraintInfos = IA->ParseConstraints();
683
684   /// ConstraintOperands - Information about all of the constraints.
685   std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
686   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
687   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
688     ConstraintOperands.
689       push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
690     TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
691
692     // Compute the value type for each operand.
693     switch (OpInfo.Type) {
694     case InlineAsm::isOutput:
695       if (OpInfo.isIndirect)
696         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
697       break;
698     case InlineAsm::isInput:
699       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
700       break;
701     case InlineAsm::isClobber:
702       // Nothing to do.
703       break;
704     }
705
706     // Compute the constraint code and ConstraintType to use.
707     TLI->ComputeConstraintToUse(OpInfo, SDValue(),
708                              OpInfo.ConstraintType == TargetLowering::C_Memory);
709
710     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
711         OpInfo.isIndirect) {
712       Value *OpVal = OpInfo.CallOperandVal;
713       MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
714     }
715   }
716
717   return MadeChange;
718 }
719
720 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
721   BasicBlock *DefBB = I->getParent();
722
723   // If both result of the {s|z}xt and its source are live out, rewrite all
724   // other uses of the source with result of extension.
725   Value *Src = I->getOperand(0);
726   if (Src->hasOneUse())
727     return false;
728
729   // Only do this xform if truncating is free.
730   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
731     return false;
732
733   // Only safe to perform the optimization if the source is also defined in
734   // this block.
735   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
736     return false;
737
738   bool DefIsLiveOut = false;
739   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
740        UI != E; ++UI) {
741     Instruction *User = cast<Instruction>(*UI);
742
743     // Figure out which BB this ext is used in.
744     BasicBlock *UserBB = User->getParent();
745     if (UserBB == DefBB) continue;
746     DefIsLiveOut = true;
747     break;
748   }
749   if (!DefIsLiveOut)
750     return false;
751
752   // Make sure non of the uses are PHI nodes.
753   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
754        UI != E; ++UI) {
755     Instruction *User = cast<Instruction>(*UI);
756     BasicBlock *UserBB = User->getParent();
757     if (UserBB == DefBB) continue;
758     // Be conservative. We don't want this xform to end up introducing
759     // reloads just before load / store instructions.
760     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
761       return false;
762   }
763
764   // InsertedTruncs - Only insert one trunc in each block once.
765   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
766
767   bool MadeChange = false;
768   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
769        UI != E; ++UI) {
770     Use &TheUse = UI.getUse();
771     Instruction *User = cast<Instruction>(*UI);
772
773     // Figure out which BB this ext is used in.
774     BasicBlock *UserBB = User->getParent();
775     if (UserBB == DefBB) continue;
776
777     // Both src and def are live in this block. Rewrite the use.
778     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
779
780     if (!InsertedTrunc) {
781       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
782
783       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
784     }
785
786     // Replace a use of the {s|z}ext source with a use of the result.
787     TheUse = InsertedTrunc;
788
789     MadeChange = true;
790   }
791
792   return MadeChange;
793 }
794
795 // In this pass we look for GEP and cast instructions that are used
796 // across basic blocks and rewrite them to improve basic-block-at-a-time
797 // selection.
798 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
799   bool MadeChange = false;
800
801   // Split all critical edges where the dest block has a PHI.
802   TerminatorInst *BBTI = BB.getTerminator();
803   if (BBTI->getNumSuccessors() > 1) {
804     for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
805       BasicBlock *SuccBB = BBTI->getSuccessor(i);
806       if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
807         SplitEdgeNicely(BBTI, i, BackEdges, this);
808     }
809   }
810
811   // Keep track of non-local addresses that have been sunk into this block.
812   // This allows us to avoid inserting duplicate code for blocks with multiple
813   // load/stores of the same address.
814   DenseMap<Value*, Value*> SunkAddrs;
815
816   for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
817     Instruction *I = BBI++;
818
819     if (CastInst *CI = dyn_cast<CastInst>(I)) {
820       // If the source of the cast is a constant, then this should have
821       // already been constant folded.  The only reason NOT to constant fold
822       // it is if something (e.g. LSR) was careful to place the constant
823       // evaluation in a block other than then one that uses it (e.g. to hoist
824       // the address of globals out of a loop).  If this is the case, we don't
825       // want to forward-subst the cast.
826       if (isa<Constant>(CI->getOperand(0)))
827         continue;
828
829       bool Change = false;
830       if (TLI) {
831         Change = OptimizeNoopCopyExpression(CI, *TLI);
832         MadeChange |= Change;
833       }
834
835       if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
836         MadeChange |= OptimizeExtUses(I);
837     } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
838       MadeChange |= OptimizeCmpExpression(CI);
839     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
840       if (TLI)
841         MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
842                                          SunkAddrs);
843     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
844       if (TLI)
845         MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
846                                          SI->getOperand(0)->getType(),
847                                          SunkAddrs);
848     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
849       if (GEPI->hasAllZeroIndices()) {
850         /// The GEP operand must be a pointer, so must its result -> BitCast
851         Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
852                                           GEPI->getName(), GEPI);
853         GEPI->replaceAllUsesWith(NC);
854         GEPI->eraseFromParent();
855         MadeChange = true;
856         BBI = NC;
857       }
858     } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
859       // If we found an inline asm expession, and if the target knows how to
860       // lower it to normal LLVM code, do so now.
861       if (TLI && isa<InlineAsm>(CI->getCalledValue()))
862         if (const TargetAsmInfo *TAI =
863             TLI->getTargetMachine().getTargetAsmInfo()) {
864           if (TAI->ExpandInlineAsm(CI)) {
865             BBI = BB.begin();
866             // Avoid processing instructions out of order, which could cause
867             // reuse before a value is defined.
868             SunkAddrs.clear();
869           } else
870             // Sink address computing for memory operands into the block.
871             MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
872         }
873     }
874   }
875
876   return MadeChange;
877 }