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