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