Now that instruction optzns can update the iterator as they go, we can
[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/Pass.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/ProfileInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLowering.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/Transforms/Utils/BuildLibCalls.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Assembly/Writer.h"
38 #include "llvm/Support/CallSite.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/GetElementPtrTypeIterator.h"
42 #include "llvm/Support/PatternMatch.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/IRBuilder.h"
45 #include "llvm/Support/ValueHandle.h"
46 using namespace llvm;
47 using namespace llvm::PatternMatch;
48
49 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
50 STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
51 STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
52 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
53                       "sunken Cmps");
54 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
55                        "of sunken Casts");
56 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
57                           "computations were sunk");
58 STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
59 STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
60
61 static cl::opt<bool>
62 CriticalEdgeSplit("cgp-critical-edge-splitting",
63                   cl::desc("Split critical edges during codegen prepare"),
64                   cl::init(false), cl::Hidden);
65
66 namespace {
67   class CodeGenPrepare : public FunctionPass {
68     /// TLI - Keep a pointer of a TargetLowering to consult for determining
69     /// transformation profitability.
70     const TargetLowering *TLI;
71     DominatorTree *DT;
72     ProfileInfo *PFI;
73     
74     /// CurInstIterator - As we scan instructions optimizing them, this is the
75     /// next instruction to optimize.  Xforms that can invalidate this should
76     /// update it.
77     BasicBlock::iterator CurInstIterator;
78
79     /// BackEdges - Keep a set of all the loop back edges.
80     ///
81     SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
82
83     // Keeps track of non-local addresses that have been sunk into a block. This
84     // allows us to avoid inserting duplicate code for blocks with multiple
85     // load/stores of the same address.
86     DenseMap<Value*, Value*> SunkAddrs;
87
88   public:
89     static char ID; // Pass identification, replacement for typeid
90     explicit CodeGenPrepare(const TargetLowering *tli = 0)
91       : FunctionPass(ID), TLI(tli) {
92         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
93       }
94     bool runOnFunction(Function &F);
95
96     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97       AU.addPreserved<DominatorTree>();
98       AU.addPreserved<ProfileInfo>();
99     }
100
101     virtual void releaseMemory() {
102       BackEdges.clear();
103     }
104
105   private:
106     bool EliminateMostlyEmptyBlocks(Function &F);
107     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
108     void EliminateMostlyEmptyBlock(BasicBlock *BB);
109     bool OptimizeBlock(BasicBlock &BB);
110     bool OptimizeInst(Instruction *I);
111     bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
112                             DenseMap<Value*,Value*> &SunkAddrs);
113     bool OptimizeInlineAsmInst(CallInst *CS);
114     bool OptimizeCallInst(CallInst *CI);
115     bool MoveExtToFormExtLoad(Instruction *I);
116     bool OptimizeExtUses(Instruction *I);
117     void findLoopBackEdges(const Function &F);
118   };
119 }
120
121 char CodeGenPrepare::ID = 0;
122 INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
123                 "Optimize for code generation", false, false)
124
125 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
126   return new CodeGenPrepare(TLI);
127 }
128
129 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
130 ///
131 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
132   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
133   FindFunctionBackedges(F, Edges);
134   
135   BackEdges.insert(Edges.begin(), Edges.end());
136 }
137
138
139 bool CodeGenPrepare::runOnFunction(Function &F) {
140   bool EverMadeChange = false;
141
142   DT = getAnalysisIfAvailable<DominatorTree>();
143   PFI = getAnalysisIfAvailable<ProfileInfo>();
144   // First pass, eliminate blocks that contain only PHI nodes and an
145   // unconditional branch.
146   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
147
148   // Now find loop back edges, but only if they are being used to decide which
149   // critical edges to split.
150   if (CriticalEdgeSplit)
151     findLoopBackEdges(F);
152
153   bool MadeChange = true;
154   while (MadeChange) {
155     MadeChange = false;
156     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
157       MadeChange |= OptimizeBlock(*BB);
158     EverMadeChange |= MadeChange;
159   }
160
161   SunkAddrs.clear();
162
163   return EverMadeChange;
164 }
165
166 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
167 /// debug info directives, and an unconditional branch.  Passes before isel
168 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
169 /// isel.  Start by eliminating these blocks so we can split them the way we
170 /// want them.
171 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
172   bool MadeChange = false;
173   // Note that this intentionally skips the entry block.
174   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
175     BasicBlock *BB = I++;
176
177     // If this block doesn't end with an uncond branch, ignore it.
178     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
179     if (!BI || !BI->isUnconditional())
180       continue;
181
182     // If the instruction before the branch (skipping debug info) isn't a phi
183     // node, then other stuff is happening here.
184     BasicBlock::iterator BBI = BI;
185     if (BBI != BB->begin()) {
186       --BBI;
187       while (isa<DbgInfoIntrinsic>(BBI)) {
188         if (BBI == BB->begin())
189           break;
190         --BBI;
191       }
192       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
193         continue;
194     }
195
196     // Do not break infinite loops.
197     BasicBlock *DestBB = BI->getSuccessor(0);
198     if (DestBB == BB)
199       continue;
200
201     if (!CanMergeBlocks(BB, DestBB))
202       continue;
203
204     EliminateMostlyEmptyBlock(BB);
205     MadeChange = true;
206   }
207   return MadeChange;
208 }
209
210 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
211 /// single uncond branch between them, and BB contains no other non-phi
212 /// instructions.
213 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
214                                     const BasicBlock *DestBB) const {
215   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
216   // the successor.  If there are more complex condition (e.g. preheaders),
217   // don't mess around with them.
218   BasicBlock::const_iterator BBI = BB->begin();
219   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
220     for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
221          UI != E; ++UI) {
222       const Instruction *User = cast<Instruction>(*UI);
223       if (User->getParent() != DestBB || !isa<PHINode>(User))
224         return false;
225       // If User is inside DestBB block and it is a PHINode then check
226       // incoming value. If incoming value is not from BB then this is
227       // a complex condition (e.g. preheaders) we want to avoid here.
228       if (User->getParent() == DestBB) {
229         if (const PHINode *UPN = dyn_cast<PHINode>(User))
230           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
231             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
232             if (Insn && Insn->getParent() == BB &&
233                 Insn->getParent() != UPN->getIncomingBlock(I))
234               return false;
235           }
236       }
237     }
238   }
239
240   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
241   // and DestBB may have conflicting incoming values for the block.  If so, we
242   // can't merge the block.
243   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
244   if (!DestBBPN) return true;  // no conflict.
245
246   // Collect the preds of BB.
247   SmallPtrSet<const BasicBlock*, 16> BBPreds;
248   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
249     // It is faster to get preds from a PHI than with pred_iterator.
250     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
251       BBPreds.insert(BBPN->getIncomingBlock(i));
252   } else {
253     BBPreds.insert(pred_begin(BB), pred_end(BB));
254   }
255
256   // Walk the preds of DestBB.
257   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
258     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
259     if (BBPreds.count(Pred)) {   // Common predecessor?
260       BBI = DestBB->begin();
261       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
262         const Value *V1 = PN->getIncomingValueForBlock(Pred);
263         const Value *V2 = PN->getIncomingValueForBlock(BB);
264
265         // If V2 is a phi node in BB, look up what the mapped value will be.
266         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
267           if (V2PN->getParent() == BB)
268             V2 = V2PN->getIncomingValueForBlock(Pred);
269
270         // If there is a conflict, bail out.
271         if (V1 != V2) return false;
272       }
273     }
274   }
275
276   return true;
277 }
278
279
280 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
281 /// an unconditional branch in it.
282 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
283   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
284   BasicBlock *DestBB = BI->getSuccessor(0);
285
286   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
287
288   // If the destination block has a single pred, then this is a trivial edge,
289   // just collapse it.
290   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
291     if (SinglePred != DestBB) {
292       // Remember if SinglePred was the entry block of the function.  If so, we
293       // will need to move BB back to the entry position.
294       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
295       MergeBasicBlockIntoOnlyPred(DestBB, this);
296
297       if (isEntry && BB != &BB->getParent()->getEntryBlock())
298         BB->moveBefore(&BB->getParent()->getEntryBlock());
299       
300       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
301       return;
302     }
303   }
304
305   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
306   // to handle the new incoming edges it is about to have.
307   PHINode *PN;
308   for (BasicBlock::iterator BBI = DestBB->begin();
309        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
310     // Remove the incoming value for BB, and remember it.
311     Value *InVal = PN->removeIncomingValue(BB, false);
312
313     // Two options: either the InVal is a phi node defined in BB or it is some
314     // value that dominates BB.
315     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
316     if (InValPhi && InValPhi->getParent() == BB) {
317       // Add all of the input values of the input PHI as inputs of this phi.
318       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
319         PN->addIncoming(InValPhi->getIncomingValue(i),
320                         InValPhi->getIncomingBlock(i));
321     } else {
322       // Otherwise, add one instance of the dominating value for each edge that
323       // we will be adding.
324       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
325         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
326           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
327       } else {
328         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
329           PN->addIncoming(InVal, *PI);
330       }
331     }
332   }
333
334   // The PHIs are now updated, change everything that refers to BB to use
335   // DestBB and remove BB.
336   BB->replaceAllUsesWith(DestBB);
337   if (DT) {
338     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
339     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
340     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
341     DT->changeImmediateDominator(DestBB, NewIDom);
342     DT->eraseNode(BB);
343   }
344   if (PFI) {
345     PFI->replaceAllUses(BB, DestBB);
346     PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
347   }
348   BB->eraseFromParent();
349   ++NumBlocksElim;
350
351   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
352 }
353
354 /// FindReusablePredBB - Check all of the predecessors of the block DestPHI
355 /// lives in to see if there is a block that we can reuse as a critical edge
356 /// from TIBB.
357 static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
358   BasicBlock *Dest = DestPHI->getParent();
359   
360   /// TIPHIValues - This array is lazily computed to determine the values of
361   /// PHIs in Dest that TI would provide.
362   SmallVector<Value*, 32> TIPHIValues;
363   
364   /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
365   unsigned TIBBEntryNo = 0;
366   
367   // Check to see if Dest has any blocks that can be used as a split edge for
368   // this terminator.
369   for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
370     BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
371     // To be usable, the pred has to end with an uncond branch to the dest.
372     BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
373     if (!PredBr || !PredBr->isUnconditional())
374       continue;
375     // Must be empty other than the branch and debug info.
376     BasicBlock::iterator I = Pred->begin();
377     while (isa<DbgInfoIntrinsic>(I))
378       I++;
379     if (&*I != PredBr)
380       continue;
381     // Cannot be the entry block; its label does not get emitted.
382     if (Pred == &Dest->getParent()->getEntryBlock())
383       continue;
384     
385     // Finally, since we know that Dest has phi nodes in it, we have to make
386     // sure that jumping to Pred will have the same effect as going to Dest in
387     // terms of PHI values.
388     PHINode *PN;
389     unsigned PHINo = 0;
390     unsigned PredEntryNo = pi;
391     
392     bool FoundMatch = true;
393     for (BasicBlock::iterator I = Dest->begin();
394          (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
395       if (PHINo == TIPHIValues.size()) {
396         if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
397           TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
398         TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
399       }
400       
401       // If the PHI entry doesn't work, we can't use this pred.
402       if (PN->getIncomingBlock(PredEntryNo) != Pred)
403         PredEntryNo = PN->getBasicBlockIndex(Pred);
404       
405       if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
406         FoundMatch = false;
407         break;
408       }
409     }
410     
411     // If we found a workable predecessor, change TI to branch to Succ.
412     if (FoundMatch)
413       return Pred;
414   }
415   return 0;  
416 }
417
418
419 /// SplitEdgeNicely - Split the critical edge from TI to its specified
420 /// successor if it will improve codegen.  We only do this if the successor has
421 /// phi nodes (otherwise critical edges are ok).  If there is already another
422 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
423 /// instead of introducing a new block.
424 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
425                      SmallSet<std::pair<const BasicBlock*,
426                                         const BasicBlock*>, 8> &BackEdges,
427                              Pass *P) {
428   BasicBlock *TIBB = TI->getParent();
429   BasicBlock *Dest = TI->getSuccessor(SuccNum);
430   assert(isa<PHINode>(Dest->begin()) &&
431          "This should only be called if Dest has a PHI!");
432   PHINode *DestPHI = cast<PHINode>(Dest->begin());
433
434   // Do not split edges to EH landing pads.
435   if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
436     if (Invoke->getSuccessor(1) == Dest)
437       return;
438
439   // As a hack, never split backedges of loops.  Even though the copy for any
440   // PHIs inserted on the backedge would be dead for exits from the loop, we
441   // assume that the cost of *splitting* the backedge would be too high.
442   if (BackEdges.count(std::make_pair(TIBB, Dest)))
443     return;
444
445   if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
446     ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
447     if (PFI)
448       PFI->splitEdge(TIBB, Dest, ReuseBB);
449     Dest->removePredecessor(TIBB);
450     TI->setSuccessor(SuccNum, ReuseBB);
451     return;
452   }
453
454   SplitCriticalEdge(TI, SuccNum, P, true);
455 }
456
457
458 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
459 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
460 /// sink it into user blocks to reduce the number of virtual
461 /// registers that must be created and coalesced.
462 ///
463 /// Return true if any changes are made.
464 ///
465 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
466   // If this is a noop copy,
467   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
468   EVT DstVT = TLI.getValueType(CI->getType());
469
470   // This is an fp<->int conversion?
471   if (SrcVT.isInteger() != DstVT.isInteger())
472     return false;
473
474   // If this is an extension, it will be a zero or sign extension, which
475   // isn't a noop.
476   if (SrcVT.bitsLT(DstVT)) return false;
477
478   // If these values will be promoted, find out what they will be promoted
479   // to.  This helps us consider truncates on PPC as noop copies when they
480   // are.
481   if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
482     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
483   if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
484     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
485
486   // If, after promotion, these are the same types, this is a noop copy.
487   if (SrcVT != DstVT)
488     return false;
489
490   BasicBlock *DefBB = CI->getParent();
491
492   /// InsertedCasts - Only insert a cast in each block once.
493   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
494
495   bool MadeChange = false;
496   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
497        UI != E; ) {
498     Use &TheUse = UI.getUse();
499     Instruction *User = cast<Instruction>(*UI);
500
501     // Figure out which BB this cast is used in.  For PHI's this is the
502     // appropriate predecessor block.
503     BasicBlock *UserBB = User->getParent();
504     if (PHINode *PN = dyn_cast<PHINode>(User)) {
505       UserBB = PN->getIncomingBlock(UI);
506     }
507
508     // Preincrement use iterator so we don't invalidate it.
509     ++UI;
510
511     // If this user is in the same block as the cast, don't change the cast.
512     if (UserBB == DefBB) continue;
513
514     // If we have already inserted a cast into this block, use it.
515     CastInst *&InsertedCast = InsertedCasts[UserBB];
516
517     if (!InsertedCast) {
518       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
519
520       InsertedCast =
521         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
522                          InsertPt);
523       MadeChange = true;
524     }
525
526     // Replace a use of the cast with a use of the new cast.
527     TheUse = InsertedCast;
528     ++NumCastUses;
529   }
530
531   // If we removed all uses, nuke the cast.
532   if (CI->use_empty()) {
533     CI->eraseFromParent();
534     MadeChange = true;
535   }
536
537   return MadeChange;
538 }
539
540 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
541 /// the number of virtual registers that must be created and coalesced.  This is
542 /// a clear win except on targets with multiple condition code registers
543 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
544 ///
545 /// Return true if any changes are made.
546 static bool OptimizeCmpExpression(CmpInst *CI) {
547   BasicBlock *DefBB = CI->getParent();
548
549   /// InsertedCmp - Only insert a cmp in each block once.
550   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
551
552   bool MadeChange = false;
553   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
554        UI != E; ) {
555     Use &TheUse = UI.getUse();
556     Instruction *User = cast<Instruction>(*UI);
557
558     // Preincrement use iterator so we don't invalidate it.
559     ++UI;
560
561     // Don't bother for PHI nodes.
562     if (isa<PHINode>(User))
563       continue;
564
565     // Figure out which BB this cmp is used in.
566     BasicBlock *UserBB = User->getParent();
567
568     // If this user is in the same block as the cmp, don't change the cmp.
569     if (UserBB == DefBB) continue;
570
571     // If we have already inserted a cmp into this block, use it.
572     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
573
574     if (!InsertedCmp) {
575       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
576
577       InsertedCmp =
578         CmpInst::Create(CI->getOpcode(),
579                         CI->getPredicate(),  CI->getOperand(0),
580                         CI->getOperand(1), "", InsertPt);
581       MadeChange = true;
582     }
583
584     // Replace a use of the cmp with a use of the new cmp.
585     TheUse = InsertedCmp;
586     ++NumCmpUses;
587   }
588
589   // If we removed all uses, nuke the cmp.
590   if (CI->use_empty())
591     CI->eraseFromParent();
592
593   return MadeChange;
594 }
595
596 namespace {
597 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
598 protected:
599   void replaceCall(Value *With) {
600     CI->replaceAllUsesWith(With);
601     CI->eraseFromParent();
602   }
603   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
604       if (ConstantInt *SizeCI =
605                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
606         return SizeCI->isAllOnesValue();
607     return false;
608   }
609 };
610 } // end anonymous namespace
611
612 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
613   BasicBlock *BB = CI->getParent();
614   
615   // Lower inline assembly if we can.
616   // If we found an inline asm expession, and if the target knows how to
617   // lower it to normal LLVM code, do so now.
618   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
619     if (TLI->ExpandInlineAsm(CI)) {
620       // Avoid invalidating the iterator.
621       CurInstIterator = BB->begin();
622       // Avoid processing instructions out of order, which could cause
623       // reuse before a value is defined.
624       SunkAddrs.clear();
625       return true;
626     }
627     // Sink address computing for memory operands into the block.
628     if (OptimizeInlineAsmInst(CI))
629       return true;
630   }
631   
632   // Lower all uses of llvm.objectsize.*
633   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
634   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
635     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
636     const Type *ReturnTy = CI->getType();
637     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);    
638     
639     // Substituting this can cause recursive simplifications, which can
640     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
641     // happens.
642     WeakVH IterHandle(CurInstIterator);
643     
644     ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0, DT);
645
646     // If the iterator instruction was recursively deleted, start over at the
647     // start of the block.
648     if (IterHandle != CurInstIterator)
649       CurInstIterator = BB->begin();
650     return true;
651   }
652
653   // From here on out we're working with named functions.
654   if (CI->getCalledFunction() == 0) return false;
655   
656   // We'll need TargetData from here on out.
657   const TargetData *TD = TLI ? TLI->getTargetData() : 0;
658   if (!TD) return false;
659   
660   // Lower all default uses of _chk calls.  This is very similar
661   // to what InstCombineCalls does, but here we are only lowering calls
662   // that have the default "don't know" as the objectsize.  Anything else
663   // should be left alone.
664   CodeGenPrepareFortifiedLibCalls Simplifier;
665   return Simplifier.fold(CI, TD);
666 }
667
668 //===----------------------------------------------------------------------===//
669 // Memory Optimization
670 //===----------------------------------------------------------------------===//
671
672 /// IsNonLocalValue - Return true if the specified values are defined in a
673 /// different basic block than BB.
674 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
675   if (Instruction *I = dyn_cast<Instruction>(V))
676     return I->getParent() != BB;
677   return false;
678 }
679
680 /// OptimizeMemoryInst - Load and Store Instructions often have
681 /// addressing modes that can do significant amounts of computation.  As such,
682 /// instruction selection will try to get the load or store to do as much
683 /// computation as possible for the program.  The problem is that isel can only
684 /// see within a single block.  As such, we sink as much legal addressing mode
685 /// stuff into the block as possible.
686 ///
687 /// This method is used to optimize both load/store and inline asms with memory
688 /// operands.
689 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
690                                         const Type *AccessTy,
691                                         DenseMap<Value*,Value*> &SunkAddrs) {
692   Value *Repl = Addr;
693   
694   // Try to collapse single-value PHI nodes.  This is necessary to undo 
695   // unprofitable PRE transformations.
696   SmallVector<Value*, 8> worklist;
697   SmallPtrSet<Value*, 16> Visited;
698   worklist.push_back(Addr);
699   
700   // Use a worklist to iteratively look through PHI nodes, and ensure that
701   // the addressing mode obtained from the non-PHI roots of the graph
702   // are equivalent.
703   Value *Consensus = 0;
704   unsigned NumUses = 0;
705   SmallVector<Instruction*, 16> AddrModeInsts;
706   ExtAddrMode AddrMode;
707   while (!worklist.empty()) {
708     Value *V = worklist.back();
709     worklist.pop_back();
710     
711     // Break use-def graph loops.
712     if (Visited.count(V)) {
713       Consensus = 0;
714       break;
715     }
716     
717     Visited.insert(V);
718     
719     // For a PHI node, push all of its incoming values.
720     if (PHINode *P = dyn_cast<PHINode>(V)) {
721       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
722         worklist.push_back(P->getIncomingValue(i));
723       continue;
724     }
725     
726     // For non-PHIs, determine the addressing mode being computed.
727     SmallVector<Instruction*, 16> NewAddrModeInsts;
728     ExtAddrMode NewAddrMode =
729       AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
730                                    NewAddrModeInsts, *TLI);
731     
732     // Ensure that the obtained addressing mode is equivalent to that obtained
733     // for all other roots of the PHI traversal.  Also, when choosing one
734     // such root as representative, select the one with the most uses in order
735     // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
736     if (!Consensus || NewAddrMode == AddrMode) {
737       if (V->getNumUses() > NumUses) {
738         Consensus = V;
739         NumUses = V->getNumUses();
740         AddrMode = NewAddrMode;
741         AddrModeInsts = NewAddrModeInsts;
742       }
743       continue;
744     }
745     
746     Consensus = 0;
747     break;
748   }
749   
750   // If the addressing mode couldn't be determined, or if multiple different
751   // ones were determined, bail out now.
752   if (!Consensus) return false;
753   
754   // Check to see if any of the instructions supersumed by this addr mode are
755   // non-local to I's BB.
756   bool AnyNonLocal = false;
757   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
758     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
759       AnyNonLocal = true;
760       break;
761     }
762   }
763
764   // If all the instructions matched are already in this BB, don't do anything.
765   if (!AnyNonLocal) {
766     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
767     return false;
768   }
769
770   // Insert this computation right after this user.  Since our caller is
771   // scanning from the top of the BB to the bottom, reuse of the expr are
772   // guaranteed to happen later.
773   BasicBlock::iterator InsertPt = MemoryInst;
774
775   // Now that we determined the addressing expression we want to use and know
776   // that we have to sink it into this block.  Check to see if we have already
777   // done this for some other load/store instr in this block.  If so, reuse the
778   // computation.
779   Value *&SunkAddr = SunkAddrs[Addr];
780   if (SunkAddr) {
781     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
782                  << *MemoryInst);
783     if (SunkAddr->getType() != Addr->getType())
784       SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
785   } else {
786     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
787                  << *MemoryInst);
788     const Type *IntPtrTy =
789           TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
790
791     Value *Result = 0;
792
793     // Start with the base register. Do this first so that subsequent address
794     // matching finds it last, which will prevent it from trying to match it
795     // as the scaled value in case it happens to be a mul. That would be
796     // problematic if we've sunk a different mul for the scale, because then
797     // we'd end up sinking both muls.
798     if (AddrMode.BaseReg) {
799       Value *V = AddrMode.BaseReg;
800       if (V->getType()->isPointerTy())
801         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
802       if (V->getType() != IntPtrTy)
803         V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
804                                         "sunkaddr", InsertPt);
805       Result = V;
806     }
807
808     // Add the scale value.
809     if (AddrMode.Scale) {
810       Value *V = AddrMode.ScaledReg;
811       if (V->getType() == IntPtrTy) {
812         // done.
813       } else if (V->getType()->isPointerTy()) {
814         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
815       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
816                  cast<IntegerType>(V->getType())->getBitWidth()) {
817         V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
818       } else {
819         V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
820       }
821       if (AddrMode.Scale != 1)
822         V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
823                                                                 AddrMode.Scale),
824                                       "sunkaddr", InsertPt);
825       if (Result)
826         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
827       else
828         Result = V;
829     }
830
831     // Add in the BaseGV if present.
832     if (AddrMode.BaseGV) {
833       Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
834                                   InsertPt);
835       if (Result)
836         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
837       else
838         Result = V;
839     }
840
841     // Add in the Base Offset if present.
842     if (AddrMode.BaseOffs) {
843       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
844       if (Result)
845         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
846       else
847         Result = V;
848     }
849
850     if (Result == 0)
851       SunkAddr = Constant::getNullValue(Addr->getType());
852     else
853       SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
854   }
855
856   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
857
858   if (Repl->use_empty()) {
859     RecursivelyDeleteTriviallyDeadInstructions(Repl);
860     // This address is now available for reassignment, so erase the table entry;
861     // we don't want to match some completely different instruction.
862     SunkAddrs[Addr] = 0;
863   }
864   ++NumMemoryInsts;
865   return true;
866 }
867
868 /// OptimizeInlineAsmInst - If there are any memory operands, use
869 /// OptimizeMemoryInst to sink their address computing into the block when
870 /// possible / profitable.
871 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
872   bool MadeChange = false;
873
874   TargetLowering::AsmOperandInfoVector 
875     TargetConstraints = TLI->ParseConstraints(CS);
876   unsigned ArgNo = 0;
877   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
878     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
879     
880     // Compute the constraint code and ConstraintType to use.
881     TLI->ComputeConstraintToUse(OpInfo, SDValue());
882
883     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
884         OpInfo.isIndirect) {
885       Value *OpVal = CS->getArgOperand(ArgNo++);
886       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType(), SunkAddrs);
887     } else if (OpInfo.Type == InlineAsm::isInput)
888       ArgNo++;
889   }
890
891   return MadeChange;
892 }
893
894 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
895 /// basic block as the load, unless conditions are unfavorable. This allows
896 /// SelectionDAG to fold the extend into the load.
897 ///
898 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
899   // Look for a load being extended.
900   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
901   if (!LI) return false;
902
903   // If they're already in the same block, there's nothing to do.
904   if (LI->getParent() == I->getParent())
905     return false;
906
907   // If the load has other users and the truncate is not free, this probably
908   // isn't worthwhile.
909   if (!LI->hasOneUse() &&
910       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
911               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
912       !TLI->isTruncateFree(I->getType(), LI->getType()))
913     return false;
914
915   // Check whether the target supports casts folded into loads.
916   unsigned LType;
917   if (isa<ZExtInst>(I))
918     LType = ISD::ZEXTLOAD;
919   else {
920     assert(isa<SExtInst>(I) && "Unexpected ext type!");
921     LType = ISD::SEXTLOAD;
922   }
923   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
924     return false;
925
926   // Move the extend into the same block as the load, so that SelectionDAG
927   // can fold it.
928   I->removeFromParent();
929   I->insertAfter(LI);
930   ++NumExtsMoved;
931   return true;
932 }
933
934 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
935   BasicBlock *DefBB = I->getParent();
936
937   // If the result of a {s|z}ext and its source are both live out, rewrite all
938   // other uses of the source with result of extension.
939   Value *Src = I->getOperand(0);
940   if (Src->hasOneUse())
941     return false;
942
943   // Only do this xform if truncating is free.
944   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
945     return false;
946
947   // Only safe to perform the optimization if the source is also defined in
948   // this block.
949   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
950     return false;
951
952   bool DefIsLiveOut = false;
953   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
954        UI != E; ++UI) {
955     Instruction *User = cast<Instruction>(*UI);
956
957     // Figure out which BB this ext is used in.
958     BasicBlock *UserBB = User->getParent();
959     if (UserBB == DefBB) continue;
960     DefIsLiveOut = true;
961     break;
962   }
963   if (!DefIsLiveOut)
964     return false;
965
966   // Make sure non of the uses are PHI nodes.
967   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
968        UI != E; ++UI) {
969     Instruction *User = cast<Instruction>(*UI);
970     BasicBlock *UserBB = User->getParent();
971     if (UserBB == DefBB) continue;
972     // Be conservative. We don't want this xform to end up introducing
973     // reloads just before load / store instructions.
974     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
975       return false;
976   }
977
978   // InsertedTruncs - Only insert one trunc in each block once.
979   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
980
981   bool MadeChange = false;
982   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
983        UI != E; ++UI) {
984     Use &TheUse = UI.getUse();
985     Instruction *User = cast<Instruction>(*UI);
986
987     // Figure out which BB this ext is used in.
988     BasicBlock *UserBB = User->getParent();
989     if (UserBB == DefBB) continue;
990
991     // Both src and def are live in this block. Rewrite the use.
992     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
993
994     if (!InsertedTrunc) {
995       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
996
997       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
998     }
999
1000     // Replace a use of the {s|z}ext source with a use of the result.
1001     TheUse = InsertedTrunc;
1002     ++NumExtUses;
1003     MadeChange = true;
1004   }
1005
1006   return MadeChange;
1007 }
1008
1009 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1010   bool MadeChange = false;
1011
1012   if (PHINode *P = dyn_cast<PHINode>(I)) {
1013     // It is possible for very late stage optimizations (such as SimplifyCFG)
1014     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
1015     // trivial PHI, go ahead and zap it here.
1016     if (Value *V = SimplifyInstruction(P)) {
1017       P->replaceAllUsesWith(V);
1018       P->eraseFromParent();
1019       ++NumPHIsElim;
1020     }
1021   } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
1022     // If the source of the cast is a constant, then this should have
1023     // already been constant folded.  The only reason NOT to constant fold
1024     // it is if something (e.g. LSR) was careful to place the constant
1025     // evaluation in a block other than then one that uses it (e.g. to hoist
1026     // the address of globals out of a loop).  If this is the case, we don't
1027     // want to forward-subst the cast.
1028     if (isa<Constant>(CI->getOperand(0)))
1029       return false;
1030
1031     bool Change = false;
1032     if (TLI) {
1033       Change = OptimizeNoopCopyExpression(CI, *TLI);
1034       MadeChange |= Change;
1035     }
1036
1037     if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
1038       MadeChange |= MoveExtToFormExtLoad(I);
1039       MadeChange |= OptimizeExtUses(I);
1040     }
1041   } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1042     MadeChange |= OptimizeCmpExpression(CI);
1043   } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1044     if (TLI)
1045       MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1046                                        SunkAddrs);
1047   } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1048     if (TLI)
1049       MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1050                                        SI->getOperand(0)->getType(),
1051                                        SunkAddrs);
1052   } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1053     if (GEPI->hasAllZeroIndices()) {
1054       /// The GEP operand must be a pointer, so must its result -> BitCast
1055       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1056                                         GEPI->getName(), GEPI);
1057       GEPI->replaceAllUsesWith(NC);
1058       GEPI->eraseFromParent();
1059       ++NumGEPsElim;
1060       MadeChange = true;
1061       OptimizeInst(NC);
1062     }
1063   } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1064     MadeChange |= OptimizeCallInst(CI);
1065   }
1066
1067   return MadeChange;
1068 }
1069
1070 // In this pass we look for GEP and cast instructions that are used
1071 // across basic blocks and rewrite them to improve basic-block-at-a-time
1072 // selection.
1073 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1074   bool MadeChange = false;
1075
1076   // Split all critical edges where the dest block has a PHI.
1077   if (CriticalEdgeSplit) {
1078     TerminatorInst *BBTI = BB.getTerminator();
1079     if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
1080       for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
1081         BasicBlock *SuccBB = BBTI->getSuccessor(i);
1082         if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
1083           SplitEdgeNicely(BBTI, i, BackEdges, this);
1084       }
1085     }
1086   }
1087
1088   SunkAddrs.clear();
1089
1090   CurInstIterator = BB.begin();
1091   for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1092     MadeChange |= OptimizeInst(CurInstIterator++);
1093
1094   return MadeChange;
1095 }