SelectionDAGISel.cpp revision 140d53c99c3a70b9d3858a3c87f8ecb098994748
1//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/CodeGen/SelectionDAGISel.h"
16#include "llvm/CallingConv.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
20#include "llvm/GlobalVariable.h"
21#include "llvm/Instructions.h"
22#include "llvm/Intrinsics.h"
23#include "llvm/CodeGen/IntrinsicLowering.h"
24#include "llvm/CodeGen/MachineDebugInfo.h"
25#include "llvm/CodeGen/MachineFunction.h"
26#include "llvm/CodeGen/MachineFrameInfo.h"
27#include "llvm/CodeGen/MachineInstrBuilder.h"
28#include "llvm/CodeGen/SelectionDAG.h"
29#include "llvm/CodeGen/SSARegMap.h"
30#include "llvm/Target/MRegisterInfo.h"
31#include "llvm/Target/TargetData.h"
32#include "llvm/Target/TargetFrameInfo.h"
33#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetLowering.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Transforms/Utils/BasicBlockUtils.h"
37#include "llvm/Support/CommandLine.h"
38#include "llvm/Support/MathExtras.h"
39#include "llvm/Support/Debug.h"
40#include <map>
41#include <iostream>
42using namespace llvm;
43
44#ifndef NDEBUG
45static cl::opt<bool>
46ViewDAGs("view-isel-dags", cl::Hidden,
47         cl::desc("Pop up a window to show isel dags as they are selected"));
48#else
49static const bool ViewDAGs = 0;
50#endif
51
52namespace llvm {
53  //===--------------------------------------------------------------------===//
54  /// FunctionLoweringInfo - This contains information that is global to a
55  /// function that is used when lowering a region of the function.
56  class FunctionLoweringInfo {
57  public:
58    TargetLowering &TLI;
59    Function &Fn;
60    MachineFunction &MF;
61    SSARegMap *RegMap;
62
63    FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
64
65    /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
66    std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
67
68    /// ValueMap - Since we emit code for the function a basic block at a time,
69    /// we must remember which virtual registers hold the values for
70    /// cross-basic-block values.
71    std::map<const Value*, unsigned> ValueMap;
72
73    /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
74    /// the entry block.  This allows the allocas to be efficiently referenced
75    /// anywhere in the function.
76    std::map<const AllocaInst*, int> StaticAllocaMap;
77
78    unsigned MakeReg(MVT::ValueType VT) {
79      return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
80    }
81
82    unsigned CreateRegForValue(const Value *V) {
83      MVT::ValueType VT = TLI.getValueType(V->getType());
84      // The common case is that we will only create one register for this
85      // value.  If we have that case, create and return the virtual register.
86      unsigned NV = TLI.getNumElements(VT);
87      if (NV == 1) {
88        // If we are promoting this value, pick the next largest supported type.
89        return MakeReg(TLI.getTypeToTransformTo(VT));
90      }
91
92      // If this value is represented with multiple target registers, make sure
93      // to create enough consequtive registers of the right (smaller) type.
94      unsigned NT = VT-1;  // Find the type to use.
95      while (TLI.getNumElements((MVT::ValueType)NT) != 1)
96        --NT;
97
98      unsigned R = MakeReg((MVT::ValueType)NT);
99      for (unsigned i = 1; i != NV; ++i)
100        MakeReg((MVT::ValueType)NT);
101      return R;
102    }
103
104    unsigned InitializeRegForValue(const Value *V) {
105      unsigned &R = ValueMap[V];
106      assert(R == 0 && "Already initialized this value register!");
107      return R = CreateRegForValue(V);
108    }
109  };
110}
111
112/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
113/// PHI nodes or outside of the basic block that defines it.
114static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
115  if (isa<PHINode>(I)) return true;
116  BasicBlock *BB = I->getParent();
117  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
118    if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
119      return true;
120  return false;
121}
122
123/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
124/// entry block, return true.
125static bool isOnlyUsedInEntryBlock(Argument *A) {
126  BasicBlock *Entry = A->getParent()->begin();
127  for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
128    if (cast<Instruction>(*UI)->getParent() != Entry)
129      return false;  // Use not in entry block.
130  return true;
131}
132
133FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
134                                           Function &fn, MachineFunction &mf)
135    : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
136
137  // Create a vreg for each argument register that is not dead and is used
138  // outside of the entry block for the function.
139  for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
140       AI != E; ++AI)
141    if (!isOnlyUsedInEntryBlock(AI))
142      InitializeRegForValue(AI);
143
144  // Initialize the mapping of values to registers.  This is only set up for
145  // instruction values that are used outside of the block that defines
146  // them.
147  Function::iterator BB = Fn.begin(), EB = Fn.end();
148  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
149    if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
150      if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
151        const Type *Ty = AI->getAllocatedType();
152        uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
153        unsigned Align =
154          std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
155                   AI->getAlignment());
156
157        // If the alignment of the value is smaller than the size of the value,
158        // and if the size of the value is particularly small (<= 8 bytes),
159        // round up to the size of the value for potentially better performance.
160        //
161        // FIXME: This could be made better with a preferred alignment hook in
162        // TargetData.  It serves primarily to 8-byte align doubles for X86.
163        if (Align < TySize && TySize <= 8) Align = TySize;
164        TySize *= CUI->getValue();   // Get total allocated size.
165        if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
166        StaticAllocaMap[AI] =
167          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
168      }
169
170  for (; BB != EB; ++BB)
171    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
172      if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
173        if (!isa<AllocaInst>(I) ||
174            !StaticAllocaMap.count(cast<AllocaInst>(I)))
175          InitializeRegForValue(I);
176
177  // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
178  // also creates the initial PHI MachineInstrs, though none of the input
179  // operands are populated.
180  for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
181    MachineBasicBlock *MBB = new MachineBasicBlock(BB);
182    MBBMap[BB] = MBB;
183    MF.getBasicBlockList().push_back(MBB);
184
185    // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
186    // appropriate.
187    PHINode *PN;
188    for (BasicBlock::iterator I = BB->begin();
189         (PN = dyn_cast<PHINode>(I)); ++I)
190      if (!PN->use_empty()) {
191        unsigned NumElements =
192          TLI.getNumElements(TLI.getValueType(PN->getType()));
193        unsigned PHIReg = ValueMap[PN];
194        assert(PHIReg &&"PHI node does not have an assigned virtual register!");
195        for (unsigned i = 0; i != NumElements; ++i)
196          BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
197      }
198  }
199}
200
201
202
203//===----------------------------------------------------------------------===//
204/// SelectionDAGLowering - This is the common target-independent lowering
205/// implementation that is parameterized by a TargetLowering object.
206/// Also, targets can overload any lowering method.
207///
208namespace llvm {
209class SelectionDAGLowering {
210  MachineBasicBlock *CurMBB;
211
212  std::map<const Value*, SDOperand> NodeMap;
213
214  /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
215  /// them up and then emit token factor nodes when possible.  This allows us to
216  /// get simple disambiguation between loads without worrying about alias
217  /// analysis.
218  std::vector<SDOperand> PendingLoads;
219
220public:
221  // TLI - This is information that describes the available target features we
222  // need for lowering.  This indicates when operations are unavailable,
223  // implemented with a libcall, etc.
224  TargetLowering &TLI;
225  SelectionDAG &DAG;
226  const TargetData &TD;
227
228  /// FuncInfo - Information about the function as a whole.
229  ///
230  FunctionLoweringInfo &FuncInfo;
231
232  SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
233                       FunctionLoweringInfo &funcinfo)
234    : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
235      FuncInfo(funcinfo) {
236  }
237
238  /// getRoot - Return the current virtual root of the Selection DAG.
239  ///
240  SDOperand getRoot() {
241    if (PendingLoads.empty())
242      return DAG.getRoot();
243
244    if (PendingLoads.size() == 1) {
245      SDOperand Root = PendingLoads[0];
246      DAG.setRoot(Root);
247      PendingLoads.clear();
248      return Root;
249    }
250
251    // Otherwise, we have to make a token factor node.
252    SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
253    PendingLoads.clear();
254    DAG.setRoot(Root);
255    return Root;
256  }
257
258  void visit(Instruction &I) { visit(I.getOpcode(), I); }
259
260  void visit(unsigned Opcode, User &I) {
261    switch (Opcode) {
262    default: assert(0 && "Unknown instruction type encountered!");
263             abort();
264      // Build the switch statement using the Instruction.def file.
265#define HANDLE_INST(NUM, OPCODE, CLASS) \
266    case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
267#include "llvm/Instruction.def"
268    }
269  }
270
271  void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
272
273
274  SDOperand getIntPtrConstant(uint64_t Val) {
275    return DAG.getConstant(Val, TLI.getPointerTy());
276  }
277
278  SDOperand getValue(const Value *V) {
279    SDOperand &N = NodeMap[V];
280    if (N.Val) return N;
281
282    const Type *VTy = V->getType();
283    MVT::ValueType VT = TLI.getValueType(VTy);
284    if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
285      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
286        visit(CE->getOpcode(), *CE);
287        assert(N.Val && "visit didn't populate the ValueMap!");
288        return N;
289      } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
290        return N = DAG.getGlobalAddress(GV, VT);
291      } else if (isa<ConstantPointerNull>(C)) {
292        return N = DAG.getConstant(0, TLI.getPointerTy());
293      } else if (isa<UndefValue>(C)) {
294        return N = DAG.getNode(ISD::UNDEF, VT);
295      } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
296        return N = DAG.getConstantFP(CFP->getValue(), VT);
297      } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
298        unsigned NumElements = PTy->getNumElements();
299        MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
300        MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
301
302        // Now that we know the number and type of the elements, push a
303        // Constant or ConstantFP node onto the ops list for each element of
304        // the packed constant.
305        std::vector<SDOperand> Ops;
306        if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
307          if (MVT::isFloatingPoint(PVT)) {
308            for (unsigned i = 0; i != NumElements; ++i) {
309              const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
310              Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
311            }
312          } else {
313            for (unsigned i = 0; i != NumElements; ++i) {
314              const ConstantIntegral *El =
315                cast<ConstantIntegral>(CP->getOperand(i));
316              Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
317            }
318          }
319        } else {
320          assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
321          SDOperand Op;
322          if (MVT::isFloatingPoint(PVT))
323            Op = DAG.getConstantFP(0, PVT);
324          else
325            Op = DAG.getConstant(0, PVT);
326          Ops.assign(NumElements, Op);
327        }
328
329        // Handle the case where we have a 1-element vector, in which
330        // case we want to immediately turn it into a scalar constant.
331        if (Ops.size() == 1) {
332          return N = Ops[0];
333        } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
334          return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
335        } else {
336          // If the packed type isn't legal, then create a ConstantVec node with
337          // generic Vector type instead.
338          return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
339        }
340      } else {
341        // Canonicalize all constant ints to be unsigned.
342        return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
343      }
344
345    if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
346      std::map<const AllocaInst*, int>::iterator SI =
347        FuncInfo.StaticAllocaMap.find(AI);
348      if (SI != FuncInfo.StaticAllocaMap.end())
349        return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
350    }
351
352    std::map<const Value*, unsigned>::const_iterator VMI =
353      FuncInfo.ValueMap.find(V);
354    assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
355
356    unsigned InReg = VMI->second;
357
358    // If this type is not legal, make it so now.
359    MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
360
361    N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
362    if (DestVT < VT) {
363      // Source must be expanded.  This input value is actually coming from the
364      // register pair VMI->second and VMI->second+1.
365      N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
366                      DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
367    } else {
368      if (DestVT > VT) { // Promotion case
369        if (MVT::isFloatingPoint(VT))
370          N = DAG.getNode(ISD::FP_ROUND, VT, N);
371        else
372          N = DAG.getNode(ISD::TRUNCATE, VT, N);
373      }
374    }
375
376    return N;
377  }
378
379  const SDOperand &setValue(const Value *V, SDOperand NewN) {
380    SDOperand &N = NodeMap[V];
381    assert(N.Val == 0 && "Already set a value for this node!");
382    return N = NewN;
383  }
384
385  // Terminator instructions.
386  void visitRet(ReturnInst &I);
387  void visitBr(BranchInst &I);
388  void visitUnreachable(UnreachableInst &I) { /* noop */ }
389
390  // These all get lowered before this pass.
391  void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
392  void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
393  void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
394  void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
395
396  //
397  void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
398  void visitShift(User &I, unsigned Opcode);
399  void visitAdd(User &I) {
400    visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
401  }
402  void visitSub(User &I);
403  void visitMul(User &I) {
404    visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
405  }
406  void visitDiv(User &I) {
407    const Type *Ty = I.getType();
408    visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
409  }
410  void visitRem(User &I) {
411    const Type *Ty = I.getType();
412    visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
413  }
414  void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
415  void visitOr (User &I) { visitBinary(I, ISD::OR,  0, 0); }
416  void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
417  void visitShl(User &I) { visitShift(I, ISD::SHL); }
418  void visitShr(User &I) {
419    visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
420  }
421
422  void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
423  void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
424  void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
425  void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
426  void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
427  void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
428  void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
429
430  void visitGetElementPtr(User &I);
431  void visitCast(User &I);
432  void visitSelect(User &I);
433  //
434
435  void visitMalloc(MallocInst &I);
436  void visitFree(FreeInst &I);
437  void visitAlloca(AllocaInst &I);
438  void visitLoad(LoadInst &I);
439  void visitStore(StoreInst &I);
440  void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
441  void visitCall(CallInst &I);
442  const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
443
444  void visitVAStart(CallInst &I);
445  void visitVAArg(VAArgInst &I);
446  void visitVAEnd(CallInst &I);
447  void visitVACopy(CallInst &I);
448  void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
449
450  void visitMemIntrinsic(CallInst &I, unsigned Op);
451
452  void visitUserOp1(Instruction &I) {
453    assert(0 && "UserOp1 should not exist at instruction selection time!");
454    abort();
455  }
456  void visitUserOp2(Instruction &I) {
457    assert(0 && "UserOp2 should not exist at instruction selection time!");
458    abort();
459  }
460};
461} // end namespace llvm
462
463void SelectionDAGLowering::visitRet(ReturnInst &I) {
464  if (I.getNumOperands() == 0) {
465    DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
466    return;
467  }
468
469  SDOperand Op1 = getValue(I.getOperand(0));
470  MVT::ValueType TmpVT;
471
472  switch (Op1.getValueType()) {
473  default: assert(0 && "Unknown value type!");
474  case MVT::i1:
475  case MVT::i8:
476  case MVT::i16:
477  case MVT::i32:
478    // If this is a machine where 32-bits is legal or expanded, promote to
479    // 32-bits, otherwise, promote to 64-bits.
480    if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
481      TmpVT = TLI.getTypeToTransformTo(MVT::i32);
482    else
483      TmpVT = MVT::i32;
484
485    // Extend integer types to result type.
486    if (I.getOperand(0)->getType()->isSigned())
487      Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
488    else
489      Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
490    break;
491  case MVT::f32:
492  case MVT::i64:
493  case MVT::f64:
494    break; // No extension needed!
495  }
496  // Allow targets to lower this further to meet ABI requirements
497  DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
498}
499
500void SelectionDAGLowering::visitBr(BranchInst &I) {
501  // Update machine-CFG edges.
502  MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
503
504  // Figure out which block is immediately after the current one.
505  MachineBasicBlock *NextBlock = 0;
506  MachineFunction::iterator BBI = CurMBB;
507  if (++BBI != CurMBB->getParent()->end())
508    NextBlock = BBI;
509
510  if (I.isUnconditional()) {
511    // If this is not a fall-through branch, emit the branch.
512    if (Succ0MBB != NextBlock)
513      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
514                              DAG.getBasicBlock(Succ0MBB)));
515  } else {
516    MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
517
518    SDOperand Cond = getValue(I.getCondition());
519    if (Succ1MBB == NextBlock) {
520      // If the condition is false, fall through.  This means we should branch
521      // if the condition is true to Succ #0.
522      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
523                              Cond, DAG.getBasicBlock(Succ0MBB)));
524    } else if (Succ0MBB == NextBlock) {
525      // If the condition is true, fall through.  This means we should branch if
526      // the condition is false to Succ #1.  Invert the condition first.
527      SDOperand True = DAG.getConstant(1, Cond.getValueType());
528      Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
529      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
530                              Cond, DAG.getBasicBlock(Succ1MBB)));
531    } else {
532      std::vector<SDOperand> Ops;
533      Ops.push_back(getRoot());
534      Ops.push_back(Cond);
535      Ops.push_back(DAG.getBasicBlock(Succ0MBB));
536      Ops.push_back(DAG.getBasicBlock(Succ1MBB));
537      DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
538    }
539  }
540}
541
542void SelectionDAGLowering::visitSub(User &I) {
543  // -0.0 - X --> fneg
544  if (I.getType()->isFloatingPoint()) {
545    if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
546      if (CFP->isExactlyValue(-0.0)) {
547        SDOperand Op2 = getValue(I.getOperand(1));
548        setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
549        return;
550      }
551  }
552  visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
553}
554
555void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
556                                       unsigned VecOp) {
557  const Type *Ty = I.getType();
558  SDOperand Op1 = getValue(I.getOperand(0));
559  SDOperand Op2 = getValue(I.getOperand(1));
560
561  if (Ty->isIntegral()) {
562    setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
563  } else if (Ty->isFloatingPoint()) {
564    setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
565  } else {
566    const PackedType *PTy = cast<PackedType>(Ty);
567    unsigned NumElements = PTy->getNumElements();
568    MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
569    MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
570
571    // Immediately scalarize packed types containing only one element, so that
572    // the Legalize pass does not have to deal with them.  Similarly, if the
573    // abstract vector is going to turn into one that the target natively
574    // supports, generate that type now so that Legalize doesn't have to deal
575    // with that either.  These steps ensure that Legalize only has to handle
576    // vector types in its Expand case.
577    unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
578    if (NumElements == 1) {
579      setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
580    } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
581      setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
582    } else {
583      SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
584      SDOperand Typ = DAG.getValueType(PVT);
585      setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
586    }
587  }
588}
589
590void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
591  SDOperand Op1 = getValue(I.getOperand(0));
592  SDOperand Op2 = getValue(I.getOperand(1));
593
594  Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
595
596  setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
597}
598
599void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
600                                      ISD::CondCode UnsignedOpcode) {
601  SDOperand Op1 = getValue(I.getOperand(0));
602  SDOperand Op2 = getValue(I.getOperand(1));
603  ISD::CondCode Opcode = SignedOpcode;
604  if (I.getOperand(0)->getType()->isUnsigned())
605    Opcode = UnsignedOpcode;
606  setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
607}
608
609void SelectionDAGLowering::visitSelect(User &I) {
610  SDOperand Cond     = getValue(I.getOperand(0));
611  SDOperand TrueVal  = getValue(I.getOperand(1));
612  SDOperand FalseVal = getValue(I.getOperand(2));
613  setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
614                           TrueVal, FalseVal));
615}
616
617void SelectionDAGLowering::visitCast(User &I) {
618  SDOperand N = getValue(I.getOperand(0));
619  MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
620  MVT::ValueType DestTy = TLI.getValueType(I.getType());
621
622  if (N.getValueType() == DestTy) {
623    setValue(&I, N);  // noop cast.
624  } else if (DestTy == MVT::i1) {
625    // Cast to bool is a comparison against zero, not truncation to zero.
626    SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
627                                       DAG.getConstantFP(0.0, N.getValueType());
628    setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
629  } else if (isInteger(SrcTy)) {
630    if (isInteger(DestTy)) {        // Int -> Int cast
631      if (DestTy < SrcTy)   // Truncating cast?
632        setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
633      else if (I.getOperand(0)->getType()->isSigned())
634        setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
635      else
636        setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
637    } else {                        // Int -> FP cast
638      if (I.getOperand(0)->getType()->isSigned())
639        setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
640      else
641        setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
642    }
643  } else {
644    assert(isFloatingPoint(SrcTy) && "Unknown value type!");
645    if (isFloatingPoint(DestTy)) {  // FP -> FP cast
646      if (DestTy < SrcTy)   // Rounding cast?
647        setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
648      else
649        setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
650    } else {                        // FP -> Int cast.
651      if (I.getType()->isSigned())
652        setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
653      else
654        setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
655    }
656  }
657}
658
659void SelectionDAGLowering::visitGetElementPtr(User &I) {
660  SDOperand N = getValue(I.getOperand(0));
661  const Type *Ty = I.getOperand(0)->getType();
662  const Type *UIntPtrTy = TD.getIntPtrType();
663
664  for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
665       OI != E; ++OI) {
666    Value *Idx = *OI;
667    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
668      unsigned Field = cast<ConstantUInt>(Idx)->getValue();
669      if (Field) {
670        // N = N + Offset
671        uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
672        N = DAG.getNode(ISD::ADD, N.getValueType(), N,
673                        getIntPtrConstant(Offset));
674      }
675      Ty = StTy->getElementType(Field);
676    } else {
677      Ty = cast<SequentialType>(Ty)->getElementType();
678
679      // If this is a constant subscript, handle it quickly.
680      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
681        if (CI->getRawValue() == 0) continue;
682
683        uint64_t Offs;
684        if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
685          Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
686        else
687          Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
688        N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
689        continue;
690      }
691
692      // N = N + Idx * ElementSize;
693      uint64_t ElementSize = TD.getTypeSize(Ty);
694      SDOperand IdxN = getValue(Idx);
695
696      // If the index is smaller or larger than intptr_t, truncate or extend
697      // it.
698      if (IdxN.getValueType() < N.getValueType()) {
699        if (Idx->getType()->isSigned())
700          IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
701        else
702          IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
703      } else if (IdxN.getValueType() > N.getValueType())
704        IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
705
706      // If this is a multiply by a power of two, turn it into a shl
707      // immediately.  This is a very common case.
708      if (isPowerOf2_64(ElementSize)) {
709        unsigned Amt = Log2_64(ElementSize);
710        IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
711                           DAG.getConstant(Amt, TLI.getShiftAmountTy()));
712        N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
713        continue;
714      }
715
716      SDOperand Scale = getIntPtrConstant(ElementSize);
717      IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
718      N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
719    }
720  }
721  setValue(&I, N);
722}
723
724void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
725  // If this is a fixed sized alloca in the entry block of the function,
726  // allocate it statically on the stack.
727  if (FuncInfo.StaticAllocaMap.count(&I))
728    return;   // getValue will auto-populate this.
729
730  const Type *Ty = I.getAllocatedType();
731  uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
732  unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
733                            I.getAlignment());
734
735  SDOperand AllocSize = getValue(I.getArraySize());
736  MVT::ValueType IntPtr = TLI.getPointerTy();
737  if (IntPtr < AllocSize.getValueType())
738    AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
739  else if (IntPtr > AllocSize.getValueType())
740    AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
741
742  AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
743                          getIntPtrConstant(TySize));
744
745  // Handle alignment.  If the requested alignment is less than or equal to the
746  // stack alignment, ignore it and round the size of the allocation up to the
747  // stack alignment size.  If the size is greater than the stack alignment, we
748  // note this in the DYNAMIC_STACKALLOC node.
749  unsigned StackAlign =
750    TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
751  if (Align <= StackAlign) {
752    Align = 0;
753    // Add SA-1 to the size.
754    AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
755                            getIntPtrConstant(StackAlign-1));
756    // Mask out the low bits for alignment purposes.
757    AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
758                            getIntPtrConstant(~(uint64_t)(StackAlign-1)));
759  }
760
761  std::vector<MVT::ValueType> VTs;
762  VTs.push_back(AllocSize.getValueType());
763  VTs.push_back(MVT::Other);
764  std::vector<SDOperand> Ops;
765  Ops.push_back(getRoot());
766  Ops.push_back(AllocSize);
767  Ops.push_back(getIntPtrConstant(Align));
768  SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
769  DAG.setRoot(setValue(&I, DSA).getValue(1));
770
771  // Inform the Frame Information that we have just allocated a variable-sized
772  // object.
773  CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
774}
775
776/// getStringValue - Turn an LLVM constant pointer that eventually points to a
777/// global into a string value.  Return an empty string if we can't do it.
778///
779static std::string getStringValue(Value *V, unsigned Offset = 0) {
780  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
781    if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
782      ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
783      if (Init->isString()) {
784        std::string Result = Init->getAsString();
785        if (Offset < Result.size()) {
786          // If we are pointing INTO The string, erase the beginning...
787          Result.erase(Result.begin(), Result.begin()+Offset);
788
789          // Take off the null terminator, and any string fragments after it.
790          std::string::size_type NullPos = Result.find_first_of((char)0);
791          if (NullPos != std::string::npos)
792            Result.erase(Result.begin()+NullPos, Result.end());
793          return Result;
794        }
795      }
796    }
797  } else if (Constant *C = dyn_cast<Constant>(V)) {
798    if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
799      return getStringValue(GV, Offset);
800    else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
801      if (CE->getOpcode() == Instruction::GetElementPtr) {
802        // Turn a gep into the specified offset.
803        if (CE->getNumOperands() == 3 &&
804            cast<Constant>(CE->getOperand(1))->isNullValue() &&
805            isa<ConstantInt>(CE->getOperand(2))) {
806          return getStringValue(CE->getOperand(0),
807                   Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
808        }
809      }
810    }
811  }
812  return "";
813}
814
815void SelectionDAGLowering::visitLoad(LoadInst &I) {
816  SDOperand Ptr = getValue(I.getOperand(0));
817
818  SDOperand Root;
819  if (I.isVolatile())
820    Root = getRoot();
821  else {
822    // Do not serialize non-volatile loads against each other.
823    Root = DAG.getRoot();
824  }
825
826  const Type *Ty = I.getType();
827  SDOperand L;
828
829  if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
830    unsigned NumElements = PTy->getNumElements();
831    MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
832    MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
833
834    // Immediately scalarize packed types containing only one element, so that
835    // the Legalize pass does not have to deal with them.
836    if (NumElements == 1) {
837      L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
838    } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
839      L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
840    } else {
841      L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
842                         DAG.getSrcValue(I.getOperand(0)));
843    }
844  } else {
845    L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
846                    DAG.getSrcValue(I.getOperand(0)));
847  }
848  setValue(&I, L);
849
850  if (I.isVolatile())
851    DAG.setRoot(L.getValue(1));
852  else
853    PendingLoads.push_back(L.getValue(1));
854}
855
856
857void SelectionDAGLowering::visitStore(StoreInst &I) {
858  Value *SrcV = I.getOperand(0);
859  SDOperand Src = getValue(SrcV);
860  SDOperand Ptr = getValue(I.getOperand(1));
861  DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
862                          DAG.getSrcValue(I.getOperand(1))));
863}
864
865/// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
866/// we want to emit this as a call to a named external function, return the name
867/// otherwise lower it and return null.
868const char *
869SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
870  switch (Intrinsic) {
871  case Intrinsic::vastart:  visitVAStart(I); return 0;
872  case Intrinsic::vaend:    visitVAEnd(I); return 0;
873  case Intrinsic::vacopy:   visitVACopy(I); return 0;
874  case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
875  case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
876  case Intrinsic::setjmp:
877    return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
878    break;
879  case Intrinsic::longjmp:
880    return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
881    break;
882  case Intrinsic::memcpy:  visitMemIntrinsic(I, ISD::MEMCPY); return 0;
883  case Intrinsic::memset:  visitMemIntrinsic(I, ISD::MEMSET); return 0;
884  case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
885
886  case Intrinsic::readport:
887  case Intrinsic::readio: {
888    std::vector<MVT::ValueType> VTs;
889    VTs.push_back(TLI.getValueType(I.getType()));
890    VTs.push_back(MVT::Other);
891    std::vector<SDOperand> Ops;
892    Ops.push_back(getRoot());
893    Ops.push_back(getValue(I.getOperand(1)));
894    SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
895                                ISD::READPORT : ISD::READIO, VTs, Ops);
896
897    setValue(&I, Tmp);
898    DAG.setRoot(Tmp.getValue(1));
899    return 0;
900  }
901  case Intrinsic::writeport:
902  case Intrinsic::writeio:
903    DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
904                            ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
905                            getRoot(), getValue(I.getOperand(1)),
906                            getValue(I.getOperand(2))));
907    return 0;
908
909  case Intrinsic::dbg_stoppoint: {
910    if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
911      return "llvm_debugger_stop";
912
913    std::string fname = "<unknown>";
914    std::vector<SDOperand> Ops;
915
916    // Input Chain
917    Ops.push_back(getRoot());
918
919    // line number
920    Ops.push_back(getValue(I.getOperand(2)));
921
922    // column
923    Ops.push_back(getValue(I.getOperand(3)));
924
925    // filename/working dir
926    // Pull the filename out of the the compilation unit.
927    const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
928    if (cunit && cunit->hasInitializer()) {
929      if (ConstantStruct *CS =
930            dyn_cast<ConstantStruct>(cunit->getInitializer())) {
931        if (CS->getNumOperands() > 0) {
932          Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
933          Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
934        }
935      }
936    }
937
938    if (Ops.size() == 5)  // Found filename/workingdir.
939      DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
940    setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
941    return 0;
942  }
943  case Intrinsic::dbg_region_start:
944    if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
945      return "llvm_dbg_region_start";
946    if (I.getType() != Type::VoidTy)
947      setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
948    return 0;
949  case Intrinsic::dbg_region_end:
950    if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
951      return "llvm_dbg_region_end";
952    if (I.getType() != Type::VoidTy)
953      setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
954    return 0;
955  case Intrinsic::dbg_func_start:
956    if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
957      return "llvm_dbg_subprogram";
958    if (I.getType() != Type::VoidTy)
959      setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
960    return 0;
961  case Intrinsic::dbg_declare:
962    if (I.getType() != Type::VoidTy)
963      setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
964    return 0;
965
966  case Intrinsic::isunordered:
967    setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
968                              getValue(I.getOperand(2)), ISD::SETUO));
969    return 0;
970
971  case Intrinsic::sqrt:
972    setValue(&I, DAG.getNode(ISD::FSQRT,
973                             getValue(I.getOperand(1)).getValueType(),
974                             getValue(I.getOperand(1))));
975    return 0;
976  case Intrinsic::pcmarker: {
977    SDOperand Tmp = getValue(I.getOperand(1));
978    DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
979    return 0;
980  }
981  case Intrinsic::readcyclecounter: {
982    std::vector<MVT::ValueType> VTs;
983    VTs.push_back(MVT::i64);
984    VTs.push_back(MVT::Other);
985    std::vector<SDOperand> Ops;
986    Ops.push_back(getRoot());
987    SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
988    setValue(&I, Tmp);
989    DAG.setRoot(Tmp.getValue(1));
990    return 0;
991  }
992  case Intrinsic::cttz:
993    setValue(&I, DAG.getNode(ISD::CTTZ,
994                             getValue(I.getOperand(1)).getValueType(),
995                             getValue(I.getOperand(1))));
996    return 0;
997  case Intrinsic::ctlz:
998    setValue(&I, DAG.getNode(ISD::CTLZ,
999                             getValue(I.getOperand(1)).getValueType(),
1000                             getValue(I.getOperand(1))));
1001    return 0;
1002  case Intrinsic::ctpop:
1003    setValue(&I, DAG.getNode(ISD::CTPOP,
1004                             getValue(I.getOperand(1)).getValueType(),
1005                             getValue(I.getOperand(1))));
1006    return 0;
1007  case Intrinsic::stacksave: {
1008    std::vector<MVT::ValueType> VTs;
1009    VTs.push_back(TLI.getPointerTy());
1010    VTs.push_back(MVT::Other);
1011    std::vector<SDOperand> Ops;
1012    Ops.push_back(getRoot());
1013    SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1014    setValue(&I, Tmp);
1015    DAG.setRoot(Tmp.getValue(1));
1016    return 0;
1017  }
1018  case Intrinsic::stackrestore:
1019    DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, DAG.getRoot(),
1020                            getValue(I.getOperand(1))));
1021    return 0;
1022  case Intrinsic::prefetch:
1023    // FIXME: Currently discarding prefetches.
1024    return 0;
1025  default:
1026    std::cerr << I;
1027    assert(0 && "This intrinsic is not implemented yet!");
1028    return 0;
1029  }
1030}
1031
1032
1033void SelectionDAGLowering::visitCall(CallInst &I) {
1034  const char *RenameFn = 0;
1035  if (Function *F = I.getCalledFunction()) {
1036    if (F->isExternal())
1037      if (unsigned IID = F->getIntrinsicID()) {
1038        RenameFn = visitIntrinsicCall(I, IID);
1039        if (!RenameFn)
1040          return;
1041      } else {    // Not an LLVM intrinsic.
1042        const std::string &Name = F->getName();
1043        if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1044          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1045              I.getOperand(1)->getType()->isFloatingPoint() &&
1046              I.getType() == I.getOperand(1)->getType()) {
1047            SDOperand Tmp = getValue(I.getOperand(1));
1048            setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1049            return;
1050          }
1051        } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1052          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1053              I.getOperand(1)->getType()->isFloatingPoint() &&
1054              I.getType() == I.getOperand(1)->getType()) {
1055            SDOperand Tmp = getValue(I.getOperand(1));
1056            setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1057            return;
1058          }
1059        } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1060          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1061              I.getOperand(1)->getType()->isFloatingPoint() &&
1062              I.getType() == I.getOperand(1)->getType()) {
1063            SDOperand Tmp = getValue(I.getOperand(1));
1064            setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1065            return;
1066          }
1067        }
1068      }
1069  }
1070
1071  SDOperand Callee;
1072  if (!RenameFn)
1073    Callee = getValue(I.getOperand(0));
1074  else
1075    Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1076  std::vector<std::pair<SDOperand, const Type*> > Args;
1077  Args.reserve(I.getNumOperands());
1078  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1079    Value *Arg = I.getOperand(i);
1080    SDOperand ArgNode = getValue(Arg);
1081    Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1082  }
1083
1084  const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1085  const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1086
1087  std::pair<SDOperand,SDOperand> Result =
1088    TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1089                    I.isTailCall(), Callee, Args, DAG);
1090  if (I.getType() != Type::VoidTy)
1091    setValue(&I, Result.first);
1092  DAG.setRoot(Result.second);
1093}
1094
1095void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1096  SDOperand Src = getValue(I.getOperand(0));
1097
1098  MVT::ValueType IntPtr = TLI.getPointerTy();
1099
1100  if (IntPtr < Src.getValueType())
1101    Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1102  else if (IntPtr > Src.getValueType())
1103    Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
1104
1105  // Scale the source by the type size.
1106  uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1107  Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1108                    Src, getIntPtrConstant(ElementSize));
1109
1110  std::vector<std::pair<SDOperand, const Type*> > Args;
1111  Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
1112
1113  std::pair<SDOperand,SDOperand> Result =
1114    TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
1115                    DAG.getExternalSymbol("malloc", IntPtr),
1116                    Args, DAG);
1117  setValue(&I, Result.first);  // Pointers always fit in registers
1118  DAG.setRoot(Result.second);
1119}
1120
1121void SelectionDAGLowering::visitFree(FreeInst &I) {
1122  std::vector<std::pair<SDOperand, const Type*> > Args;
1123  Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1124                                TLI.getTargetData().getIntPtrType()));
1125  MVT::ValueType IntPtr = TLI.getPointerTy();
1126  std::pair<SDOperand,SDOperand> Result =
1127    TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
1128                    DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1129  DAG.setRoot(Result.second);
1130}
1131
1132// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1133// mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
1134// instructions are special in various ways, which require special support to
1135// insert.  The specified MachineInstr is created but not inserted into any
1136// basic blocks, and the scheduler passes ownership of it to this method.
1137MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1138                                                       MachineBasicBlock *MBB) {
1139  std::cerr << "If a target marks an instruction with "
1140               "'usesCustomDAGSchedInserter', it must implement "
1141               "TargetLowering::InsertAtEndOfBasicBlock!\n";
1142  abort();
1143  return 0;
1144}
1145
1146SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1147                                        SelectionDAG &DAG) {
1148  return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1149}
1150
1151SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1152                                       SDOperand VAListP, Value *VAListV,
1153                                       SelectionDAG &DAG) {
1154  // We have no sane default behavior, just emit a useful error message and bail
1155  // out.
1156  std::cerr << "Variable arguments handling not implemented on this target!\n";
1157  abort();
1158  return SDOperand();
1159}
1160
1161SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
1162                                     SelectionDAG &DAG) {
1163  // Default to a noop.
1164  return Chain;
1165}
1166
1167SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1168                                      SDOperand SrcP, Value *SrcV,
1169                                      SDOperand DestP, Value *DestV,
1170                                      SelectionDAG &DAG) {
1171  // Default to copying the input list.
1172  SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1173                              SrcP, DAG.getSrcValue(SrcV));
1174  SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
1175                                 Val, DestP, DAG.getSrcValue(DestV));
1176  return Result;
1177}
1178
1179std::pair<SDOperand,SDOperand>
1180TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1181                           const Type *ArgTy, SelectionDAG &DAG) {
1182  // We have no sane default behavior, just emit a useful error message and bail
1183  // out.
1184  std::cerr << "Variable arguments handling not implemented on this target!\n";
1185  abort();
1186  return std::make_pair(SDOperand(), SDOperand());
1187}
1188
1189
1190void SelectionDAGLowering::visitVAStart(CallInst &I) {
1191  DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1192                               I.getOperand(1), DAG));
1193}
1194
1195void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1196  std::pair<SDOperand,SDOperand> Result =
1197    TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
1198                   I.getType(), DAG);
1199  setValue(&I, Result.first);
1200  DAG.setRoot(Result.second);
1201}
1202
1203void SelectionDAGLowering::visitVAEnd(CallInst &I) {
1204  DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
1205                             I.getOperand(1), DAG));
1206}
1207
1208void SelectionDAGLowering::visitVACopy(CallInst &I) {
1209  SDOperand Result =
1210    TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1211                    getValue(I.getOperand(1)), I.getOperand(1), DAG);
1212  DAG.setRoot(Result);
1213}
1214
1215
1216// It is always conservatively correct for llvm.returnaddress and
1217// llvm.frameaddress to return 0.
1218std::pair<SDOperand, SDOperand>
1219TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1220                                        unsigned Depth, SelectionDAG &DAG) {
1221  return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
1222}
1223
1224SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1225  assert(0 && "LowerOperation not implemented for this target!");
1226  abort();
1227  return SDOperand();
1228}
1229
1230void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1231  unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1232  std::pair<SDOperand,SDOperand> Result =
1233    TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
1234  setValue(&I, Result.first);
1235  DAG.setRoot(Result.second);
1236}
1237
1238void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1239#if 0
1240  // If the size of the cpy/move/set is constant (known)
1241  if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1242    uint64_t size = op3->getValue();
1243    switch (Op) {
1244      case ISD::MEMSET:
1245        if (size <= TLI.getMaxStoresPerMemSet()) {
1246          if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1247        uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1248            uint64_t align = op4.getValue();
1249            while (size > align) {
1250              size -=align;
1251            }
1252  Value *SrcV = I.getOperand(0);
1253  SDOperand Src = getValue(SrcV);
1254  SDOperand Ptr = getValue(I.getOperand(1));
1255  DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1256                          DAG.getSrcValue(I.getOperand(1))));
1257          }
1258          break;
1259        }
1260        break; // don't do this optimization, use a normal memset
1261      case ISD::MEMMOVE:
1262      case ISD::MEMCPY:
1263        break; // FIXME: not implemented yet
1264    }
1265  }
1266#endif
1267
1268  // Non-optimized version
1269  std::vector<SDOperand> Ops;
1270  Ops.push_back(getRoot());
1271  Ops.push_back(getValue(I.getOperand(1)));
1272  Ops.push_back(getValue(I.getOperand(2)));
1273  Ops.push_back(getValue(I.getOperand(3)));
1274  Ops.push_back(getValue(I.getOperand(4)));
1275  DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1276}
1277
1278//===----------------------------------------------------------------------===//
1279// SelectionDAGISel code
1280//===----------------------------------------------------------------------===//
1281
1282unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1283  return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1284}
1285
1286void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1287  // FIXME: we only modify the CFG to split critical edges.  This
1288  // updates dom and loop info.
1289}
1290
1291
1292/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1293/// casting to the type of GEPI.
1294static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1295                                   Value *Ptr, Value *PtrOffset) {
1296  if (V) return V;   // Already computed.
1297
1298  BasicBlock::iterator InsertPt;
1299  if (BB == GEPI->getParent()) {
1300    // If insert into the GEP's block, insert right after the GEP.
1301    InsertPt = GEPI;
1302    ++InsertPt;
1303  } else {
1304    // Otherwise, insert at the top of BB, after any PHI nodes
1305    InsertPt = BB->begin();
1306    while (isa<PHINode>(InsertPt)) ++InsertPt;
1307  }
1308
1309  // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1310  // BB so that there is only one value live across basic blocks (the cast
1311  // operand).
1312  if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1313    if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1314      Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1315
1316  // Add the offset, cast it to the right type.
1317  Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1318  Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1319  return V = Ptr;
1320}
1321
1322
1323/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1324/// selection, we want to be a bit careful about some things.  In particular, if
1325/// we have a GEP instruction that is used in a different block than it is
1326/// defined, the addressing expression of the GEP cannot be folded into loads or
1327/// stores that use it.  In this case, decompose the GEP and move constant
1328/// indices into blocks that use it.
1329static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1330                                  const TargetData &TD) {
1331  // If this GEP is only used inside the block it is defined in, there is no
1332  // need to rewrite it.
1333  bool isUsedOutsideDefBB = false;
1334  BasicBlock *DefBB = GEPI->getParent();
1335  for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
1336       UI != E; ++UI) {
1337    if (cast<Instruction>(*UI)->getParent() != DefBB) {
1338      isUsedOutsideDefBB = true;
1339      break;
1340    }
1341  }
1342  if (!isUsedOutsideDefBB) return;
1343
1344  // If this GEP has no non-zero constant indices, there is nothing we can do,
1345  // ignore it.
1346  bool hasConstantIndex = false;
1347  for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1348       E = GEPI->op_end(); OI != E; ++OI) {
1349    if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1350      if (CI->getRawValue()) {
1351        hasConstantIndex = true;
1352        break;
1353      }
1354  }
1355  // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1356  if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
1357
1358  // Otherwise, decompose the GEP instruction into multiplies and adds.  Sum the
1359  // constant offset (which we now know is non-zero) and deal with it later.
1360  uint64_t ConstantOffset = 0;
1361  const Type *UIntPtrTy = TD.getIntPtrType();
1362  Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1363  const Type *Ty = GEPI->getOperand(0)->getType();
1364
1365  for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1366       E = GEPI->op_end(); OI != E; ++OI) {
1367    Value *Idx = *OI;
1368    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1369      unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1370      if (Field)
1371        ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1372      Ty = StTy->getElementType(Field);
1373    } else {
1374      Ty = cast<SequentialType>(Ty)->getElementType();
1375
1376      // Handle constant subscripts.
1377      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1378        if (CI->getRawValue() == 0) continue;
1379
1380        if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1381          ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1382        else
1383          ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1384        continue;
1385      }
1386
1387      // Ptr = Ptr + Idx * ElementSize;
1388
1389      // Cast Idx to UIntPtrTy if needed.
1390      Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1391
1392      uint64_t ElementSize = TD.getTypeSize(Ty);
1393      // Mask off bits that should not be set.
1394      ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1395      Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1396
1397      // Multiply by the element size and add to the base.
1398      Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1399      Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1400    }
1401  }
1402
1403  // Make sure that the offset fits in uintptr_t.
1404  ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1405  Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1406
1407  // Okay, we have now emitted all of the variable index parts to the BB that
1408  // the GEP is defined in.  Loop over all of the using instructions, inserting
1409  // an "add Ptr, ConstantOffset" into each block that uses it and update the
1410  // instruction to use the newly computed value, making GEPI dead.  When the
1411  // user is a load or store instruction address, we emit the add into the user
1412  // block, otherwise we use a canonical version right next to the gep (these
1413  // won't be foldable as addresses, so we might as well share the computation).
1414
1415  std::map<BasicBlock*,Value*> InsertedExprs;
1416  while (!GEPI->use_empty()) {
1417    Instruction *User = cast<Instruction>(GEPI->use_back());
1418
1419    // If this use is not foldable into the addressing mode, use a version
1420    // emitted in the GEP block.
1421    Value *NewVal;
1422    if (!isa<LoadInst>(User) &&
1423        (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1424      NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
1425                                    Ptr, PtrOffset);
1426    } else {
1427      // Otherwise, insert the code in the User's block so it can be folded into
1428      // any users in that block.
1429      NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
1430                                    User->getParent(), GEPI,
1431                                    Ptr, PtrOffset);
1432    }
1433    User->replaceUsesOfWith(GEPI, NewVal);
1434  }
1435
1436  // Finally, the GEP is dead, remove it.
1437  GEPI->eraseFromParent();
1438}
1439
1440bool SelectionDAGISel::runOnFunction(Function &Fn) {
1441  MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1442  RegMap = MF.getSSARegMap();
1443  DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1444
1445  // First, split all critical edges for PHI nodes with incoming values that are
1446  // constants, this way the load of the constant into a vreg will not be placed
1447  // into MBBs that are used some other way.
1448  //
1449  // In this pass we also look for GEP instructions that are used across basic
1450  // blocks and rewrites them to improve basic-block-at-a-time selection.
1451  //
1452  for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1453    PHINode *PN;
1454    BasicBlock::iterator BBI;
1455    for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1456      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1457        if (isa<Constant>(PN->getIncomingValue(i)))
1458          SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1459
1460    for (BasicBlock::iterator E = BB->end(); BBI != E; )
1461      if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1462        OptimizeGEPExpression(GEPI, TLI.getTargetData());
1463  }
1464
1465  FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1466
1467  for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1468    SelectBasicBlock(I, MF, FuncInfo);
1469
1470  return true;
1471}
1472
1473
1474SDOperand SelectionDAGISel::
1475CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1476  SDOperand Op = SDL.getValue(V);
1477  assert((Op.getOpcode() != ISD::CopyFromReg ||
1478          cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1479         "Copy from a reg to the same reg!");
1480
1481  // If this type is not legal, we must make sure to not create an invalid
1482  // register use.
1483  MVT::ValueType SrcVT = Op.getValueType();
1484  MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1485  SelectionDAG &DAG = SDL.DAG;
1486  if (SrcVT == DestVT) {
1487    return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1488  } else if (SrcVT < DestVT) {
1489    // The src value is promoted to the register.
1490    if (MVT::isFloatingPoint(SrcVT))
1491      Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1492    else
1493      Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1494    return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1495  } else  {
1496    // The src value is expanded into multiple registers.
1497    SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1498                               Op, DAG.getConstant(0, MVT::i32));
1499    SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1500                               Op, DAG.getConstant(1, MVT::i32));
1501    Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1502    return DAG.getCopyToReg(Op, Reg+1, Hi);
1503  }
1504}
1505
1506void SelectionDAGISel::
1507LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1508               std::vector<SDOperand> &UnorderedChains) {
1509  // If this is the entry block, emit arguments.
1510  Function &F = *BB->getParent();
1511  FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1512  SDOperand OldRoot = SDL.DAG.getRoot();
1513  std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1514
1515  unsigned a = 0;
1516  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1517       AI != E; ++AI, ++a)
1518    if (!AI->use_empty()) {
1519      SDL.setValue(AI, Args[a]);
1520
1521      // If this argument is live outside of the entry block, insert a copy from
1522      // whereever we got it to the vreg that other BB's will reference it as.
1523      if (FuncInfo.ValueMap.count(AI)) {
1524        SDOperand Copy =
1525          CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1526        UnorderedChains.push_back(Copy);
1527      }
1528    }
1529
1530  // Next, if the function has live ins that need to be copied into vregs,
1531  // emit the copies now, into the top of the block.
1532  MachineFunction &MF = SDL.DAG.getMachineFunction();
1533  if (MF.livein_begin() != MF.livein_end()) {
1534    SSARegMap *RegMap = MF.getSSARegMap();
1535    const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1536    for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1537         E = MF.livein_end(); LI != E; ++LI)
1538      if (LI->second)
1539        MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1540                         LI->first, RegMap->getRegClass(LI->second));
1541  }
1542
1543  // Finally, if the target has anything special to do, allow it to do so.
1544  EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1545}
1546
1547
1548void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1549       std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1550                                    FunctionLoweringInfo &FuncInfo) {
1551  SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1552
1553  std::vector<SDOperand> UnorderedChains;
1554
1555  // Lower any arguments needed in this block if this is the entry block.
1556  if (LLVMBB == &LLVMBB->getParent()->front())
1557    LowerArguments(LLVMBB, SDL, UnorderedChains);
1558
1559  BB = FuncInfo.MBBMap[LLVMBB];
1560  SDL.setCurrentBasicBlock(BB);
1561
1562  // Lower all of the non-terminator instructions.
1563  for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1564       I != E; ++I)
1565    SDL.visit(*I);
1566
1567  // Ensure that all instructions which are used outside of their defining
1568  // blocks are available as virtual registers.
1569  for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1570    if (!I->use_empty() && !isa<PHINode>(I)) {
1571      std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1572      if (VMI != FuncInfo.ValueMap.end())
1573        UnorderedChains.push_back(
1574                           CopyValueToVirtualRegister(SDL, I, VMI->second));
1575    }
1576
1577  // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
1578  // ensure constants are generated when needed.  Remember the virtual registers
1579  // that need to be added to the Machine PHI nodes as input.  We cannot just
1580  // directly add them, because expansion might result in multiple MBB's for one
1581  // BB.  As such, the start of the BB might correspond to a different MBB than
1582  // the end.
1583  //
1584
1585  // Emit constants only once even if used by multiple PHI nodes.
1586  std::map<Constant*, unsigned> ConstantsOut;
1587
1588  // Check successor nodes PHI nodes that expect a constant to be available from
1589  // this block.
1590  TerminatorInst *TI = LLVMBB->getTerminator();
1591  for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1592    BasicBlock *SuccBB = TI->getSuccessor(succ);
1593    MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1594    PHINode *PN;
1595
1596    // At this point we know that there is a 1-1 correspondence between LLVM PHI
1597    // nodes and Machine PHI nodes, but the incoming operands have not been
1598    // emitted yet.
1599    for (BasicBlock::iterator I = SuccBB->begin();
1600         (PN = dyn_cast<PHINode>(I)); ++I)
1601      if (!PN->use_empty()) {
1602        unsigned Reg;
1603        Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1604        if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1605          unsigned &RegOut = ConstantsOut[C];
1606          if (RegOut == 0) {
1607            RegOut = FuncInfo.CreateRegForValue(C);
1608            UnorderedChains.push_back(
1609                             CopyValueToVirtualRegister(SDL, C, RegOut));
1610          }
1611          Reg = RegOut;
1612        } else {
1613          Reg = FuncInfo.ValueMap[PHIOp];
1614          if (Reg == 0) {
1615            assert(isa<AllocaInst>(PHIOp) &&
1616                   FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1617                   "Didn't codegen value into a register!??");
1618            Reg = FuncInfo.CreateRegForValue(PHIOp);
1619            UnorderedChains.push_back(
1620                             CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1621          }
1622        }
1623
1624        // Remember that this register needs to added to the machine PHI node as
1625        // the input for this MBB.
1626        unsigned NumElements =
1627          TLI.getNumElements(TLI.getValueType(PN->getType()));
1628        for (unsigned i = 0, e = NumElements; i != e; ++i)
1629          PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1630      }
1631  }
1632  ConstantsOut.clear();
1633
1634  // Turn all of the unordered chains into one factored node.
1635  if (!UnorderedChains.empty()) {
1636    SDOperand Root = SDL.getRoot();
1637    if (Root.getOpcode() != ISD::EntryToken) {
1638      unsigned i = 0, e = UnorderedChains.size();
1639      for (; i != e; ++i) {
1640        assert(UnorderedChains[i].Val->getNumOperands() > 1);
1641        if (UnorderedChains[i].Val->getOperand(0) == Root)
1642          break;  // Don't add the root if we already indirectly depend on it.
1643      }
1644
1645      if (i == e)
1646        UnorderedChains.push_back(Root);
1647    }
1648    DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1649  }
1650
1651  // Lower the terminator after the copies are emitted.
1652  SDL.visit(*LLVMBB->getTerminator());
1653
1654  // Make sure the root of the DAG is up-to-date.
1655  DAG.setRoot(SDL.getRoot());
1656}
1657
1658void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1659                                        FunctionLoweringInfo &FuncInfo) {
1660  SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
1661  CurDAG = &DAG;
1662  std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1663
1664  // First step, lower LLVM code to some DAG.  This DAG may use operations and
1665  // types that are not supported by the target.
1666  BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1667
1668  // Run the DAG combiner in pre-legalize mode.
1669  DAG.Combine(false);
1670
1671  DEBUG(std::cerr << "Lowered selection DAG:\n");
1672  DEBUG(DAG.dump());
1673
1674  // Second step, hack on the DAG until it only uses operations and types that
1675  // the target supports.
1676  DAG.Legalize();
1677
1678  DEBUG(std::cerr << "Legalized selection DAG:\n");
1679  DEBUG(DAG.dump());
1680
1681  // Run the DAG combiner in post-legalize mode.
1682  DAG.Combine(true);
1683
1684  if (ViewDAGs) DAG.viewGraph();
1685
1686  // Third, instruction select all of the operations to machine code, adding the
1687  // code to the MachineBasicBlock.
1688  InstructionSelectBasicBlock(DAG);
1689
1690  DEBUG(std::cerr << "Selected machine code:\n");
1691  DEBUG(BB->dump());
1692
1693  // Next, now that we know what the last MBB the LLVM BB expanded is, update
1694  // PHI nodes in successors.
1695  for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1696    MachineInstr *PHI = PHINodesToUpdate[i].first;
1697    assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1698           "This is not a machine PHI node that we are updating!");
1699    PHI->addRegOperand(PHINodesToUpdate[i].second);
1700    PHI->addMachineBasicBlockOperand(BB);
1701  }
1702
1703  // Finally, add the CFG edges from the last selected MBB to the successor
1704  // MBBs.
1705  TerminatorInst *TI = LLVMBB->getTerminator();
1706  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1707    MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1708    BB->addSuccessor(Succ0MBB);
1709  }
1710}
1711