SelectionDAGISel.cpp revision 87bc3bd1213ced06eade93e3267178198d41a381
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/CodeGen/ScheduleDAG.h"
17#include "llvm/CallingConv.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
21#include "llvm/GlobalVariable.h"
22#include "llvm/InlineAsm.h"
23#include "llvm/Instructions.h"
24#include "llvm/Intrinsics.h"
25#include "llvm/CodeGen/IntrinsicLowering.h"
26#include "llvm/CodeGen/MachineDebugInfo.h"
27#include "llvm/CodeGen/MachineFunction.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstrBuilder.h"
30#include "llvm/CodeGen/SelectionDAG.h"
31#include "llvm/CodeGen/SSARegMap.h"
32#include "llvm/Target/MRegisterInfo.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Target/TargetFrameInfo.h"
35#include "llvm/Target/TargetInstrInfo.h"
36#include "llvm/Target/TargetLowering.h"
37#include "llvm/Target/TargetMachine.h"
38#include "llvm/Transforms/Utils/BasicBlockUtils.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/MathExtras.h"
41#include "llvm/Support/Debug.h"
42#include <map>
43#include <set>
44#include <iostream>
45using namespace llvm;
46
47#ifndef NDEBUG
48static cl::opt<bool>
49ViewISelDAGs("view-isel-dags", cl::Hidden,
50          cl::desc("Pop up a window to show isel dags as they are selected"));
51static cl::opt<bool>
52ViewSchedDAGs("view-sched-dags", cl::Hidden,
53          cl::desc("Pop up a window to show sched dags as they are processed"));
54#else
55static const bool ViewISelDAGs = 0;
56static const bool ViewSchedDAGs = 0;
57#endif
58
59namespace {
60  cl::opt<SchedHeuristics>
61  ISHeuristic(
62    "sched",
63    cl::desc("Choose scheduling style"),
64    cl::init(defaultScheduling),
65    cl::values(
66      clEnumValN(defaultScheduling, "default",
67                 "Target preferred scheduling style"),
68      clEnumValN(noScheduling, "none",
69                 "No scheduling: breadth first sequencing"),
70      clEnumValN(simpleScheduling, "simple",
71                 "Simple two pass scheduling: minimize critical path "
72                 "and maximize processor utilization"),
73      clEnumValN(simpleNoItinScheduling, "simple-noitin",
74                 "Simple two pass scheduling: Same as simple "
75                 "except using generic latency"),
76      clEnumValN(listSchedulingBURR, "list-burr",
77                 "Bottom up register reduction list scheduling"),
78      clEnumValEnd));
79} // namespace
80
81namespace {
82  /// RegsForValue - This struct represents the physical registers that a
83  /// particular value is assigned and the type information about the value.
84  /// This is needed because values can be promoted into larger registers and
85  /// expanded into multiple smaller registers than the value.
86  struct RegsForValue {
87    /// Regs - This list hold the register (for legal and promoted values)
88    /// or register set (for expanded values) that the value should be assigned
89    /// to.
90    std::vector<unsigned> Regs;
91
92    /// RegVT - The value type of each register.
93    ///
94    MVT::ValueType RegVT;
95
96    /// ValueVT - The value type of the LLVM value, which may be promoted from
97    /// RegVT or made from merging the two expanded parts.
98    MVT::ValueType ValueVT;
99
100    RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
101
102    RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
103      : RegVT(regvt), ValueVT(valuevt) {
104        Regs.push_back(Reg);
105    }
106    RegsForValue(const std::vector<unsigned> &regs,
107                 MVT::ValueType regvt, MVT::ValueType valuevt)
108      : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
109    }
110
111    /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
112    /// this value and returns the result as a ValueVT value.  This uses
113    /// Chain/Flag as the input and updates them for the output Chain/Flag.
114    SDOperand getCopyFromRegs(SelectionDAG &DAG,
115                              SDOperand &Chain, SDOperand &Flag) const;
116
117    /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
118    /// specified value into the registers specified by this object.  This uses
119    /// Chain/Flag as the input and updates them for the output Chain/Flag.
120    void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
121                       SDOperand &Chain, SDOperand &Flag) const;
122
123    /// AddInlineAsmOperands - Add this value to the specified inlineasm node
124    /// operand list.  This adds the code marker and includes the number of
125    /// values added into it.
126    void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
127                              std::vector<SDOperand> &Ops) const;
128  };
129}
130
131namespace llvm {
132  //===--------------------------------------------------------------------===//
133  /// FunctionLoweringInfo - This contains information that is global to a
134  /// function that is used when lowering a region of the function.
135  class FunctionLoweringInfo {
136  public:
137    TargetLowering &TLI;
138    Function &Fn;
139    MachineFunction &MF;
140    SSARegMap *RegMap;
141
142    FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
143
144    /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
145    std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
146
147    /// ValueMap - Since we emit code for the function a basic block at a time,
148    /// we must remember which virtual registers hold the values for
149    /// cross-basic-block values.
150    std::map<const Value*, unsigned> ValueMap;
151
152    /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
153    /// the entry block.  This allows the allocas to be efficiently referenced
154    /// anywhere in the function.
155    std::map<const AllocaInst*, int> StaticAllocaMap;
156
157    unsigned MakeReg(MVT::ValueType VT) {
158      return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
159    }
160
161    unsigned CreateRegForValue(const Value *V) {
162      MVT::ValueType VT = TLI.getValueType(V->getType());
163      // The common case is that we will only create one register for this
164      // value.  If we have that case, create and return the virtual register.
165      unsigned NV = TLI.getNumElements(VT);
166      if (NV == 1) {
167        // If we are promoting this value, pick the next largest supported type.
168        return MakeReg(TLI.getTypeToTransformTo(VT));
169      }
170
171      // If this value is represented with multiple target registers, make sure
172      // to create enough consecutive registers of the right (smaller) type.
173      unsigned NT = VT-1;  // Find the type to use.
174      while (TLI.getNumElements((MVT::ValueType)NT) != 1)
175        --NT;
176
177      unsigned R = MakeReg((MVT::ValueType)NT);
178      for (unsigned i = 1; i != NV; ++i)
179        MakeReg((MVT::ValueType)NT);
180      return R;
181    }
182
183    unsigned InitializeRegForValue(const Value *V) {
184      unsigned &R = ValueMap[V];
185      assert(R == 0 && "Already initialized this value register!");
186      return R = CreateRegForValue(V);
187    }
188  };
189}
190
191/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
192/// PHI nodes or outside of the basic block that defines it.
193static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
194  if (isa<PHINode>(I)) return true;
195  BasicBlock *BB = I->getParent();
196  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
197    if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
198      return true;
199  return false;
200}
201
202/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
203/// entry block, return true.
204static bool isOnlyUsedInEntryBlock(Argument *A) {
205  BasicBlock *Entry = A->getParent()->begin();
206  for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
207    if (cast<Instruction>(*UI)->getParent() != Entry)
208      return false;  // Use not in entry block.
209  return true;
210}
211
212FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
213                                           Function &fn, MachineFunction &mf)
214    : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
215
216  // Create a vreg for each argument register that is not dead and is used
217  // outside of the entry block for the function.
218  for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
219       AI != E; ++AI)
220    if (!isOnlyUsedInEntryBlock(AI))
221      InitializeRegForValue(AI);
222
223  // Initialize the mapping of values to registers.  This is only set up for
224  // instruction values that are used outside of the block that defines
225  // them.
226  Function::iterator BB = Fn.begin(), EB = Fn.end();
227  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
228    if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
229      if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
230        const Type *Ty = AI->getAllocatedType();
231        uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
232        unsigned Align =
233          std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
234                   AI->getAlignment());
235
236        // If the alignment of the value is smaller than the size of the value,
237        // and if the size of the value is particularly small (<= 8 bytes),
238        // round up to the size of the value for potentially better performance.
239        //
240        // FIXME: This could be made better with a preferred alignment hook in
241        // TargetData.  It serves primarily to 8-byte align doubles for X86.
242        if (Align < TySize && TySize <= 8) Align = TySize;
243        TySize *= CUI->getValue();   // Get total allocated size.
244        if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
245        StaticAllocaMap[AI] =
246          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
247      }
248
249  for (; BB != EB; ++BB)
250    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
251      if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
252        if (!isa<AllocaInst>(I) ||
253            !StaticAllocaMap.count(cast<AllocaInst>(I)))
254          InitializeRegForValue(I);
255
256  // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
257  // also creates the initial PHI MachineInstrs, though none of the input
258  // operands are populated.
259  for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
260    MachineBasicBlock *MBB = new MachineBasicBlock(BB);
261    MBBMap[BB] = MBB;
262    MF.getBasicBlockList().push_back(MBB);
263
264    // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
265    // appropriate.
266    PHINode *PN;
267    for (BasicBlock::iterator I = BB->begin();
268         (PN = dyn_cast<PHINode>(I)); ++I)
269      if (!PN->use_empty()) {
270        unsigned NumElements =
271          TLI.getNumElements(TLI.getValueType(PN->getType()));
272        unsigned PHIReg = ValueMap[PN];
273        assert(PHIReg &&"PHI node does not have an assigned virtual register!");
274        for (unsigned i = 0; i != NumElements; ++i)
275          BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
276      }
277  }
278}
279
280
281
282//===----------------------------------------------------------------------===//
283/// SelectionDAGLowering - This is the common target-independent lowering
284/// implementation that is parameterized by a TargetLowering object.
285/// Also, targets can overload any lowering method.
286///
287namespace llvm {
288class SelectionDAGLowering {
289  MachineBasicBlock *CurMBB;
290
291  std::map<const Value*, SDOperand> NodeMap;
292
293  /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
294  /// them up and then emit token factor nodes when possible.  This allows us to
295  /// get simple disambiguation between loads without worrying about alias
296  /// analysis.
297  std::vector<SDOperand> PendingLoads;
298
299public:
300  // TLI - This is information that describes the available target features we
301  // need for lowering.  This indicates when operations are unavailable,
302  // implemented with a libcall, etc.
303  TargetLowering &TLI;
304  SelectionDAG &DAG;
305  const TargetData &TD;
306
307  /// FuncInfo - Information about the function as a whole.
308  ///
309  FunctionLoweringInfo &FuncInfo;
310
311  SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
312                       FunctionLoweringInfo &funcinfo)
313    : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
314      FuncInfo(funcinfo) {
315  }
316
317  /// getRoot - Return the current virtual root of the Selection DAG.
318  ///
319  SDOperand getRoot() {
320    if (PendingLoads.empty())
321      return DAG.getRoot();
322
323    if (PendingLoads.size() == 1) {
324      SDOperand Root = PendingLoads[0];
325      DAG.setRoot(Root);
326      PendingLoads.clear();
327      return Root;
328    }
329
330    // Otherwise, we have to make a token factor node.
331    SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
332    PendingLoads.clear();
333    DAG.setRoot(Root);
334    return Root;
335  }
336
337  void visit(Instruction &I) { visit(I.getOpcode(), I); }
338
339  void visit(unsigned Opcode, User &I) {
340    switch (Opcode) {
341    default: assert(0 && "Unknown instruction type encountered!");
342             abort();
343      // Build the switch statement using the Instruction.def file.
344#define HANDLE_INST(NUM, OPCODE, CLASS) \
345    case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
346#include "llvm/Instruction.def"
347    }
348  }
349
350  void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
351
352
353  SDOperand getIntPtrConstant(uint64_t Val) {
354    return DAG.getConstant(Val, TLI.getPointerTy());
355  }
356
357  SDOperand getValue(const Value *V) {
358    SDOperand &N = NodeMap[V];
359    if (N.Val) return N;
360
361    const Type *VTy = V->getType();
362    MVT::ValueType VT = TLI.getValueType(VTy);
363    if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
364      if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
365        visit(CE->getOpcode(), *CE);
366        assert(N.Val && "visit didn't populate the ValueMap!");
367        return N;
368      } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
369        return N = DAG.getGlobalAddress(GV, VT);
370      } else if (isa<ConstantPointerNull>(C)) {
371        return N = DAG.getConstant(0, TLI.getPointerTy());
372      } else if (isa<UndefValue>(C)) {
373        return N = DAG.getNode(ISD::UNDEF, VT);
374      } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
375        return N = DAG.getConstantFP(CFP->getValue(), VT);
376      } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
377        unsigned NumElements = PTy->getNumElements();
378        MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
379        MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
380
381        // Now that we know the number and type of the elements, push a
382        // Constant or ConstantFP node onto the ops list for each element of
383        // the packed constant.
384        std::vector<SDOperand> Ops;
385        if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
386          if (MVT::isFloatingPoint(PVT)) {
387            for (unsigned i = 0; i != NumElements; ++i) {
388              const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
389              Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
390            }
391          } else {
392            for (unsigned i = 0; i != NumElements; ++i) {
393              const ConstantIntegral *El =
394                cast<ConstantIntegral>(CP->getOperand(i));
395              Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
396            }
397          }
398        } else {
399          assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
400          SDOperand Op;
401          if (MVT::isFloatingPoint(PVT))
402            Op = DAG.getConstantFP(0, PVT);
403          else
404            Op = DAG.getConstant(0, PVT);
405          Ops.assign(NumElements, Op);
406        }
407
408        // Handle the case where we have a 1-element vector, in which
409        // case we want to immediately turn it into a scalar constant.
410        if (Ops.size() == 1) {
411          return N = Ops[0];
412        } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
413          return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
414        } else {
415          // If the packed type isn't legal, then create a ConstantVec node with
416          // generic Vector type instead.
417          return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
418        }
419      } else {
420        // Canonicalize all constant ints to be unsigned.
421        return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
422      }
423
424    if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
425      std::map<const AllocaInst*, int>::iterator SI =
426        FuncInfo.StaticAllocaMap.find(AI);
427      if (SI != FuncInfo.StaticAllocaMap.end())
428        return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
429    }
430
431    std::map<const Value*, unsigned>::const_iterator VMI =
432      FuncInfo.ValueMap.find(V);
433    assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
434
435    unsigned InReg = VMI->second;
436
437    // If this type is not legal, make it so now.
438    MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
439
440    N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
441    if (DestVT < VT) {
442      // Source must be expanded.  This input value is actually coming from the
443      // register pair VMI->second and VMI->second+1.
444      N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
445                      DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
446    } else {
447      if (DestVT > VT) { // Promotion case
448        if (MVT::isFloatingPoint(VT))
449          N = DAG.getNode(ISD::FP_ROUND, VT, N);
450        else
451          N = DAG.getNode(ISD::TRUNCATE, VT, N);
452      }
453    }
454
455    return N;
456  }
457
458  const SDOperand &setValue(const Value *V, SDOperand NewN) {
459    SDOperand &N = NodeMap[V];
460    assert(N.Val == 0 && "Already set a value for this node!");
461    return N = NewN;
462  }
463
464  RegsForValue GetRegistersForValue(const std::string &ConstrCode,
465                                    MVT::ValueType VT,
466                                    bool OutReg, bool InReg,
467                                    std::set<unsigned> &OutputRegs,
468                                    std::set<unsigned> &InputRegs);
469
470  // Terminator instructions.
471  void visitRet(ReturnInst &I);
472  void visitBr(BranchInst &I);
473  void visitUnreachable(UnreachableInst &I) { /* noop */ }
474
475  // These all get lowered before this pass.
476  void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
477  void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
478  void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
479  void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
480  void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
481
482  //
483  void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
484  void visitShift(User &I, unsigned Opcode);
485  void visitAdd(User &I) {
486    visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
487  }
488  void visitSub(User &I);
489  void visitMul(User &I) {
490    visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
491  }
492  void visitDiv(User &I) {
493    const Type *Ty = I.getType();
494    visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
495  }
496  void visitRem(User &I) {
497    const Type *Ty = I.getType();
498    visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
499  }
500  void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
501  void visitOr (User &I) { visitBinary(I, ISD::OR,  0, 0); }
502  void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
503  void visitShl(User &I) { visitShift(I, ISD::SHL); }
504  void visitShr(User &I) {
505    visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
506  }
507
508  void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
509  void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
510  void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
511  void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
512  void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
513  void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
514  void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
515
516  void visitGetElementPtr(User &I);
517  void visitCast(User &I);
518  void visitSelect(User &I);
519  //
520
521  void visitMalloc(MallocInst &I);
522  void visitFree(FreeInst &I);
523  void visitAlloca(AllocaInst &I);
524  void visitLoad(LoadInst &I);
525  void visitStore(StoreInst &I);
526  void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
527  void visitCall(CallInst &I);
528  void visitInlineAsm(CallInst &I);
529  const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
530
531  void visitVAStart(CallInst &I);
532  void visitVAArg(VAArgInst &I);
533  void visitVAEnd(CallInst &I);
534  void visitVACopy(CallInst &I);
535  void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
536
537  void visitMemIntrinsic(CallInst &I, unsigned Op);
538
539  void visitUserOp1(Instruction &I) {
540    assert(0 && "UserOp1 should not exist at instruction selection time!");
541    abort();
542  }
543  void visitUserOp2(Instruction &I) {
544    assert(0 && "UserOp2 should not exist at instruction selection time!");
545    abort();
546  }
547};
548} // end namespace llvm
549
550void SelectionDAGLowering::visitRet(ReturnInst &I) {
551  if (I.getNumOperands() == 0) {
552    DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
553    return;
554  }
555  std::vector<SDOperand> NewValues;
556  NewValues.push_back(getRoot());
557  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
558    SDOperand RetOp = getValue(I.getOperand(i));
559
560    // If this is an integer return value, we need to promote it ourselves to
561    // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
562    // than sign/zero.
563    if (MVT::isInteger(RetOp.getValueType()) &&
564        RetOp.getValueType() < MVT::i64) {
565      MVT::ValueType TmpVT;
566      if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
567        TmpVT = TLI.getTypeToTransformTo(MVT::i32);
568      else
569        TmpVT = MVT::i32;
570
571      if (I.getOperand(i)->getType()->isSigned())
572        RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
573      else
574        RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
575    }
576    NewValues.push_back(RetOp);
577  }
578  DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
579}
580
581void SelectionDAGLowering::visitBr(BranchInst &I) {
582  // Update machine-CFG edges.
583  MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
584
585  // Figure out which block is immediately after the current one.
586  MachineBasicBlock *NextBlock = 0;
587  MachineFunction::iterator BBI = CurMBB;
588  if (++BBI != CurMBB->getParent()->end())
589    NextBlock = BBI;
590
591  if (I.isUnconditional()) {
592    // If this is not a fall-through branch, emit the branch.
593    if (Succ0MBB != NextBlock)
594      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
595                              DAG.getBasicBlock(Succ0MBB)));
596  } else {
597    MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
598
599    SDOperand Cond = getValue(I.getCondition());
600    if (Succ1MBB == NextBlock) {
601      // If the condition is false, fall through.  This means we should branch
602      // if the condition is true to Succ #0.
603      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
604                              Cond, DAG.getBasicBlock(Succ0MBB)));
605    } else if (Succ0MBB == NextBlock) {
606      // If the condition is true, fall through.  This means we should branch if
607      // the condition is false to Succ #1.  Invert the condition first.
608      SDOperand True = DAG.getConstant(1, Cond.getValueType());
609      Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
610      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
611                              Cond, DAG.getBasicBlock(Succ1MBB)));
612    } else {
613      std::vector<SDOperand> Ops;
614      Ops.push_back(getRoot());
615      // If the false case is the current basic block, then this is a self
616      // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
617      // adds an extra instruction in the loop.  Instead, invert the
618      // condition and emit "Loop: ... br!cond Loop; br Out.
619      if (CurMBB == Succ1MBB) {
620        std::swap(Succ0MBB, Succ1MBB);
621        SDOperand True = DAG.getConstant(1, Cond.getValueType());
622        Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
623      }
624      Ops.push_back(Cond);
625      Ops.push_back(DAG.getBasicBlock(Succ0MBB));
626      Ops.push_back(DAG.getBasicBlock(Succ1MBB));
627      DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
628    }
629  }
630}
631
632void SelectionDAGLowering::visitSub(User &I) {
633  // -0.0 - X --> fneg
634  if (I.getType()->isFloatingPoint()) {
635    if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
636      if (CFP->isExactlyValue(-0.0)) {
637        SDOperand Op2 = getValue(I.getOperand(1));
638        setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
639        return;
640      }
641  }
642  visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
643}
644
645void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
646                                       unsigned VecOp) {
647  const Type *Ty = I.getType();
648  SDOperand Op1 = getValue(I.getOperand(0));
649  SDOperand Op2 = getValue(I.getOperand(1));
650
651  if (Ty->isIntegral()) {
652    setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
653  } else if (Ty->isFloatingPoint()) {
654    setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
655  } else {
656    const PackedType *PTy = cast<PackedType>(Ty);
657    unsigned NumElements = PTy->getNumElements();
658    MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
659    MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
660
661    // Immediately scalarize packed types containing only one element, so that
662    // the Legalize pass does not have to deal with them.  Similarly, if the
663    // abstract vector is going to turn into one that the target natively
664    // supports, generate that type now so that Legalize doesn't have to deal
665    // with that either.  These steps ensure that Legalize only has to handle
666    // vector types in its Expand case.
667    unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
668    if (NumElements == 1) {
669      setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
670    } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
671      setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
672    } else {
673      SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
674      SDOperand Typ = DAG.getValueType(PVT);
675      setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
676    }
677  }
678}
679
680void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
681  SDOperand Op1 = getValue(I.getOperand(0));
682  SDOperand Op2 = getValue(I.getOperand(1));
683
684  Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
685
686  setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
687}
688
689void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
690                                      ISD::CondCode UnsignedOpcode) {
691  SDOperand Op1 = getValue(I.getOperand(0));
692  SDOperand Op2 = getValue(I.getOperand(1));
693  ISD::CondCode Opcode = SignedOpcode;
694  if (I.getOperand(0)->getType()->isUnsigned())
695    Opcode = UnsignedOpcode;
696  setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
697}
698
699void SelectionDAGLowering::visitSelect(User &I) {
700  SDOperand Cond     = getValue(I.getOperand(0));
701  SDOperand TrueVal  = getValue(I.getOperand(1));
702  SDOperand FalseVal = getValue(I.getOperand(2));
703  setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
704                           TrueVal, FalseVal));
705}
706
707void SelectionDAGLowering::visitCast(User &I) {
708  SDOperand N = getValue(I.getOperand(0));
709  MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
710  MVT::ValueType DestTy = TLI.getValueType(I.getType());
711
712  if (N.getValueType() == DestTy) {
713    setValue(&I, N);  // noop cast.
714  } else if (DestTy == MVT::i1) {
715    // Cast to bool is a comparison against zero, not truncation to zero.
716    SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
717                                       DAG.getConstantFP(0.0, N.getValueType());
718    setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
719  } else if (isInteger(SrcTy)) {
720    if (isInteger(DestTy)) {        // Int -> Int cast
721      if (DestTy < SrcTy)   // Truncating cast?
722        setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
723      else if (I.getOperand(0)->getType()->isSigned())
724        setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
725      else
726        setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
727    } else {                        // Int -> FP cast
728      if (I.getOperand(0)->getType()->isSigned())
729        setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
730      else
731        setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
732    }
733  } else {
734    assert(isFloatingPoint(SrcTy) && "Unknown value type!");
735    if (isFloatingPoint(DestTy)) {  // FP -> FP cast
736      if (DestTy < SrcTy)   // Rounding cast?
737        setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
738      else
739        setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
740    } else {                        // FP -> Int cast.
741      if (I.getType()->isSigned())
742        setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
743      else
744        setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
745    }
746  }
747}
748
749void SelectionDAGLowering::visitGetElementPtr(User &I) {
750  SDOperand N = getValue(I.getOperand(0));
751  const Type *Ty = I.getOperand(0)->getType();
752  const Type *UIntPtrTy = TD.getIntPtrType();
753
754  for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
755       OI != E; ++OI) {
756    Value *Idx = *OI;
757    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
758      unsigned Field = cast<ConstantUInt>(Idx)->getValue();
759      if (Field) {
760        // N = N + Offset
761        uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
762        N = DAG.getNode(ISD::ADD, N.getValueType(), N,
763                        getIntPtrConstant(Offset));
764      }
765      Ty = StTy->getElementType(Field);
766    } else {
767      Ty = cast<SequentialType>(Ty)->getElementType();
768
769      // If this is a constant subscript, handle it quickly.
770      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
771        if (CI->getRawValue() == 0) continue;
772
773        uint64_t Offs;
774        if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
775          Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
776        else
777          Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
778        N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
779        continue;
780      }
781
782      // N = N + Idx * ElementSize;
783      uint64_t ElementSize = TD.getTypeSize(Ty);
784      SDOperand IdxN = getValue(Idx);
785
786      // If the index is smaller or larger than intptr_t, truncate or extend
787      // it.
788      if (IdxN.getValueType() < N.getValueType()) {
789        if (Idx->getType()->isSigned())
790          IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
791        else
792          IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
793      } else if (IdxN.getValueType() > N.getValueType())
794        IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
795
796      // If this is a multiply by a power of two, turn it into a shl
797      // immediately.  This is a very common case.
798      if (isPowerOf2_64(ElementSize)) {
799        unsigned Amt = Log2_64(ElementSize);
800        IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
801                           DAG.getConstant(Amt, TLI.getShiftAmountTy()));
802        N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
803        continue;
804      }
805
806      SDOperand Scale = getIntPtrConstant(ElementSize);
807      IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
808      N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
809    }
810  }
811  setValue(&I, N);
812}
813
814void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
815  // If this is a fixed sized alloca in the entry block of the function,
816  // allocate it statically on the stack.
817  if (FuncInfo.StaticAllocaMap.count(&I))
818    return;   // getValue will auto-populate this.
819
820  const Type *Ty = I.getAllocatedType();
821  uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
822  unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
823                            I.getAlignment());
824
825  SDOperand AllocSize = getValue(I.getArraySize());
826  MVT::ValueType IntPtr = TLI.getPointerTy();
827  if (IntPtr < AllocSize.getValueType())
828    AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
829  else if (IntPtr > AllocSize.getValueType())
830    AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
831
832  AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
833                          getIntPtrConstant(TySize));
834
835  // Handle alignment.  If the requested alignment is less than or equal to the
836  // stack alignment, ignore it and round the size of the allocation up to the
837  // stack alignment size.  If the size is greater than the stack alignment, we
838  // note this in the DYNAMIC_STACKALLOC node.
839  unsigned StackAlign =
840    TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
841  if (Align <= StackAlign) {
842    Align = 0;
843    // Add SA-1 to the size.
844    AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
845                            getIntPtrConstant(StackAlign-1));
846    // Mask out the low bits for alignment purposes.
847    AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
848                            getIntPtrConstant(~(uint64_t)(StackAlign-1)));
849  }
850
851  std::vector<MVT::ValueType> VTs;
852  VTs.push_back(AllocSize.getValueType());
853  VTs.push_back(MVT::Other);
854  std::vector<SDOperand> Ops;
855  Ops.push_back(getRoot());
856  Ops.push_back(AllocSize);
857  Ops.push_back(getIntPtrConstant(Align));
858  SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
859  DAG.setRoot(setValue(&I, DSA).getValue(1));
860
861  // Inform the Frame Information that we have just allocated a variable-sized
862  // object.
863  CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
864}
865
866/// getStringValue - Turn an LLVM constant pointer that eventually points to a
867/// global into a string value.  Return an empty string if we can't do it.
868///
869static std::string getStringValue(GlobalVariable *GV, unsigned Offset = 0) {
870  if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
871    ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
872    if (Init->isString()) {
873      std::string Result = Init->getAsString();
874      if (Offset < Result.size()) {
875        // If we are pointing INTO The string, erase the beginning...
876        Result.erase(Result.begin(), Result.begin()+Offset);
877        return Result;
878      }
879    }
880  }
881  return "";
882}
883
884void SelectionDAGLowering::visitLoad(LoadInst &I) {
885  SDOperand Ptr = getValue(I.getOperand(0));
886
887  SDOperand Root;
888  if (I.isVolatile())
889    Root = getRoot();
890  else {
891    // Do not serialize non-volatile loads against each other.
892    Root = DAG.getRoot();
893  }
894
895  const Type *Ty = I.getType();
896  SDOperand L;
897
898  if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
899    unsigned NumElements = PTy->getNumElements();
900    MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
901    MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
902
903    // Immediately scalarize packed types containing only one element, so that
904    // the Legalize pass does not have to deal with them.
905    if (NumElements == 1) {
906      L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
907    } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
908      L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
909    } else {
910      L = DAG.getVecLoad(NumElements, PVT, Root, Ptr,
911                         DAG.getSrcValue(I.getOperand(0)));
912    }
913  } else {
914    L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr,
915                    DAG.getSrcValue(I.getOperand(0)));
916  }
917  setValue(&I, L);
918
919  if (I.isVolatile())
920    DAG.setRoot(L.getValue(1));
921  else
922    PendingLoads.push_back(L.getValue(1));
923}
924
925
926void SelectionDAGLowering::visitStore(StoreInst &I) {
927  Value *SrcV = I.getOperand(0);
928  SDOperand Src = getValue(SrcV);
929  SDOperand Ptr = getValue(I.getOperand(1));
930  DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
931                          DAG.getSrcValue(I.getOperand(1))));
932}
933
934/// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
935/// we want to emit this as a call to a named external function, return the name
936/// otherwise lower it and return null.
937const char *
938SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
939  switch (Intrinsic) {
940  case Intrinsic::vastart:  visitVAStart(I); return 0;
941  case Intrinsic::vaend:    visitVAEnd(I); return 0;
942  case Intrinsic::vacopy:   visitVACopy(I); return 0;
943  case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
944  case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
945  case Intrinsic::setjmp:
946    return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
947    break;
948  case Intrinsic::longjmp:
949    return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
950    break;
951  case Intrinsic::memcpy:  visitMemIntrinsic(I, ISD::MEMCPY); return 0;
952  case Intrinsic::memset:  visitMemIntrinsic(I, ISD::MEMSET); return 0;
953  case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
954
955  case Intrinsic::readport:
956  case Intrinsic::readio: {
957    std::vector<MVT::ValueType> VTs;
958    VTs.push_back(TLI.getValueType(I.getType()));
959    VTs.push_back(MVT::Other);
960    std::vector<SDOperand> Ops;
961    Ops.push_back(getRoot());
962    Ops.push_back(getValue(I.getOperand(1)));
963    SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
964                                ISD::READPORT : ISD::READIO, VTs, Ops);
965
966    setValue(&I, Tmp);
967    DAG.setRoot(Tmp.getValue(1));
968    return 0;
969  }
970  case Intrinsic::writeport:
971  case Intrinsic::writeio:
972    DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
973                            ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
974                            getRoot(), getValue(I.getOperand(1)),
975                            getValue(I.getOperand(2))));
976    return 0;
977
978  case Intrinsic::dbg_stoppoint: {
979    if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
980      return "llvm_debugger_stop";
981
982    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
983    if (DebugInfo &&  DebugInfo->Verify(I.getOperand(4))) {
984      std::vector<SDOperand> Ops;
985
986      // Input Chain
987      Ops.push_back(getRoot());
988
989      // line number
990      Ops.push_back(getValue(I.getOperand(2)));
991
992      // column
993      Ops.push_back(getValue(I.getOperand(3)));
994
995      DebugInfoDesc *DD = DebugInfo->getDescFor(I.getOperand(4));
996      assert(DD && "Not a debug information descriptor");
997      CompileUnitDesc *CompileUnit = dyn_cast<CompileUnitDesc>(DD);
998      assert(CompileUnit && "Not a compile unit");
999      Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1000      Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1001
1002      if (Ops.size() == 5)  // Found filename/workingdir.
1003        DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1004    }
1005
1006    setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1007    return 0;
1008  }
1009  case Intrinsic::dbg_region_start:
1010    if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1011      return "llvm_dbg_region_start";
1012    if (I.getType() != Type::VoidTy)
1013      setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1014    return 0;
1015  case Intrinsic::dbg_region_end:
1016    if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1017      return "llvm_dbg_region_end";
1018    if (I.getType() != Type::VoidTy)
1019      setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1020    return 0;
1021  case Intrinsic::dbg_func_start:
1022    if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
1023      return "llvm_dbg_subprogram";
1024    if (I.getType() != Type::VoidTy)
1025      setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1026    return 0;
1027  case Intrinsic::dbg_declare:
1028    if (I.getType() != Type::VoidTy)
1029      setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
1030    return 0;
1031
1032  case Intrinsic::isunordered_f32:
1033  case Intrinsic::isunordered_f64:
1034    setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1035                              getValue(I.getOperand(2)), ISD::SETUO));
1036    return 0;
1037
1038  case Intrinsic::sqrt_f32:
1039  case Intrinsic::sqrt_f64:
1040    setValue(&I, DAG.getNode(ISD::FSQRT,
1041                             getValue(I.getOperand(1)).getValueType(),
1042                             getValue(I.getOperand(1))));
1043    return 0;
1044  case Intrinsic::pcmarker: {
1045    SDOperand Tmp = getValue(I.getOperand(1));
1046    DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1047    return 0;
1048  }
1049  case Intrinsic::readcyclecounter: {
1050    std::vector<MVT::ValueType> VTs;
1051    VTs.push_back(MVT::i64);
1052    VTs.push_back(MVT::Other);
1053    std::vector<SDOperand> Ops;
1054    Ops.push_back(getRoot());
1055    SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1056    setValue(&I, Tmp);
1057    DAG.setRoot(Tmp.getValue(1));
1058    return 0;
1059  }
1060  case Intrinsic::bswap_i16:
1061  case Intrinsic::bswap_i32:
1062  case Intrinsic::bswap_i64:
1063    setValue(&I, DAG.getNode(ISD::BSWAP,
1064                             getValue(I.getOperand(1)).getValueType(),
1065                             getValue(I.getOperand(1))));
1066    return 0;
1067  case Intrinsic::cttz_i8:
1068  case Intrinsic::cttz_i16:
1069  case Intrinsic::cttz_i32:
1070  case Intrinsic::cttz_i64:
1071    setValue(&I, DAG.getNode(ISD::CTTZ,
1072                             getValue(I.getOperand(1)).getValueType(),
1073                             getValue(I.getOperand(1))));
1074    return 0;
1075  case Intrinsic::ctlz_i8:
1076  case Intrinsic::ctlz_i16:
1077  case Intrinsic::ctlz_i32:
1078  case Intrinsic::ctlz_i64:
1079    setValue(&I, DAG.getNode(ISD::CTLZ,
1080                             getValue(I.getOperand(1)).getValueType(),
1081                             getValue(I.getOperand(1))));
1082    return 0;
1083  case Intrinsic::ctpop_i8:
1084  case Intrinsic::ctpop_i16:
1085  case Intrinsic::ctpop_i32:
1086  case Intrinsic::ctpop_i64:
1087    setValue(&I, DAG.getNode(ISD::CTPOP,
1088                             getValue(I.getOperand(1)).getValueType(),
1089                             getValue(I.getOperand(1))));
1090    return 0;
1091  case Intrinsic::stacksave: {
1092    std::vector<MVT::ValueType> VTs;
1093    VTs.push_back(TLI.getPointerTy());
1094    VTs.push_back(MVT::Other);
1095    std::vector<SDOperand> Ops;
1096    Ops.push_back(getRoot());
1097    SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1098    setValue(&I, Tmp);
1099    DAG.setRoot(Tmp.getValue(1));
1100    return 0;
1101  }
1102  case Intrinsic::stackrestore: {
1103    SDOperand Tmp = getValue(I.getOperand(1));
1104    DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1105    return 0;
1106  }
1107  case Intrinsic::prefetch:
1108    // FIXME: Currently discarding prefetches.
1109    return 0;
1110  default:
1111    std::cerr << I;
1112    assert(0 && "This intrinsic is not implemented yet!");
1113    return 0;
1114  }
1115}
1116
1117
1118void SelectionDAGLowering::visitCall(CallInst &I) {
1119  const char *RenameFn = 0;
1120  if (Function *F = I.getCalledFunction()) {
1121    if (F->isExternal())
1122      if (unsigned IID = F->getIntrinsicID()) {
1123        RenameFn = visitIntrinsicCall(I, IID);
1124        if (!RenameFn)
1125          return;
1126      } else {    // Not an LLVM intrinsic.
1127        const std::string &Name = F->getName();
1128        if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1129          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1130              I.getOperand(1)->getType()->isFloatingPoint() &&
1131              I.getType() == I.getOperand(1)->getType()) {
1132            SDOperand Tmp = getValue(I.getOperand(1));
1133            setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1134            return;
1135          }
1136        } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1137          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1138              I.getOperand(1)->getType()->isFloatingPoint() &&
1139              I.getType() == I.getOperand(1)->getType()) {
1140            SDOperand Tmp = getValue(I.getOperand(1));
1141            setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1142            return;
1143          }
1144        } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1145          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1146              I.getOperand(1)->getType()->isFloatingPoint() &&
1147              I.getType() == I.getOperand(1)->getType()) {
1148            SDOperand Tmp = getValue(I.getOperand(1));
1149            setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1150            return;
1151          }
1152        }
1153      }
1154  } else if (isa<InlineAsm>(I.getOperand(0))) {
1155    visitInlineAsm(I);
1156    return;
1157  }
1158
1159  SDOperand Callee;
1160  if (!RenameFn)
1161    Callee = getValue(I.getOperand(0));
1162  else
1163    Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1164  std::vector<std::pair<SDOperand, const Type*> > Args;
1165  Args.reserve(I.getNumOperands());
1166  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1167    Value *Arg = I.getOperand(i);
1168    SDOperand ArgNode = getValue(Arg);
1169    Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1170  }
1171
1172  const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1173  const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1174
1175  std::pair<SDOperand,SDOperand> Result =
1176    TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1177                    I.isTailCall(), Callee, Args, DAG);
1178  if (I.getType() != Type::VoidTy)
1179    setValue(&I, Result.first);
1180  DAG.setRoot(Result.second);
1181}
1182
1183SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1184                                        SDOperand &Chain, SDOperand &Flag)const{
1185  SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1186  Chain = Val.getValue(1);
1187  Flag  = Val.getValue(2);
1188
1189  // If the result was expanded, copy from the top part.
1190  if (Regs.size() > 1) {
1191    assert(Regs.size() == 2 &&
1192           "Cannot expand to more than 2 elts yet!");
1193    SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1194    Chain = Val.getValue(1);
1195    Flag  = Val.getValue(2);
1196    if (DAG.getTargetLoweringInfo().isLittleEndian())
1197      return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1198    else
1199      return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
1200  }
1201
1202  // Otherwise, if the return value was promoted, truncate it to the
1203  // appropriate type.
1204  if (RegVT == ValueVT)
1205    return Val;
1206
1207  if (MVT::isInteger(RegVT))
1208    return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1209  else
1210    return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1211}
1212
1213/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1214/// specified value into the registers specified by this object.  This uses
1215/// Chain/Flag as the input and updates them for the output Chain/Flag.
1216void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1217                                 SDOperand &Chain, SDOperand &Flag) const {
1218  if (Regs.size() == 1) {
1219    // If there is a single register and the types differ, this must be
1220    // a promotion.
1221    if (RegVT != ValueVT) {
1222      if (MVT::isInteger(RegVT))
1223        Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1224      else
1225        Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1226    }
1227    Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1228    Flag = Chain.getValue(1);
1229  } else {
1230    std::vector<unsigned> R(Regs);
1231    if (!DAG.getTargetLoweringInfo().isLittleEndian())
1232      std::reverse(R.begin(), R.end());
1233
1234    for (unsigned i = 0, e = R.size(); i != e; ++i) {
1235      SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1236                                   DAG.getConstant(i, MVT::i32));
1237      Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
1238      Flag = Chain.getValue(1);
1239    }
1240  }
1241}
1242
1243/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1244/// operand list.  This adds the code marker and includes the number of
1245/// values added into it.
1246void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1247                                        std::vector<SDOperand> &Ops) const {
1248  Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1249  for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1250    Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1251}
1252
1253/// isAllocatableRegister - If the specified register is safe to allocate,
1254/// i.e. it isn't a stack pointer or some other special register, return the
1255/// register class for the register.  Otherwise, return null.
1256static const TargetRegisterClass *
1257isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1258                      const TargetLowering &TLI, const MRegisterInfo *MRI) {
1259  for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1260       E = MRI->regclass_end(); RCI != E; ++RCI) {
1261    const TargetRegisterClass *RC = *RCI;
1262    // If none of the the value types for this register class are valid, we
1263    // can't use it.  For example, 64-bit reg classes on 32-bit targets.
1264    bool isLegal = false;
1265    for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1266         I != E; ++I) {
1267      if (TLI.isTypeLegal(*I)) {
1268        isLegal = true;
1269        break;
1270      }
1271    }
1272
1273    if (!isLegal) continue;
1274
1275    // NOTE: This isn't ideal.  In particular, this might allocate the
1276    // frame pointer in functions that need it (due to them not being taken
1277    // out of allocation, because a variable sized allocation hasn't been seen
1278    // yet).  This is a slight code pessimization, but should still work.
1279    for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1280         E = RC->allocation_order_end(MF); I != E; ++I)
1281      if (*I == Reg)
1282        return RC;
1283  }
1284  return 0;
1285}
1286
1287RegsForValue SelectionDAGLowering::
1288GetRegistersForValue(const std::string &ConstrCode,
1289                     MVT::ValueType VT, bool isOutReg, bool isInReg,
1290                     std::set<unsigned> &OutputRegs,
1291                     std::set<unsigned> &InputRegs) {
1292  std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1293    TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1294  std::vector<unsigned> Regs;
1295
1296  unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1297  MVT::ValueType RegVT;
1298  MVT::ValueType ValueVT = VT;
1299
1300  if (PhysReg.first) {
1301    if (VT == MVT::Other)
1302      ValueVT = *PhysReg.second->vt_begin();
1303    RegVT = VT;
1304
1305    // This is a explicit reference to a physical register.
1306    Regs.push_back(PhysReg.first);
1307
1308    // If this is an expanded reference, add the rest of the regs to Regs.
1309    if (NumRegs != 1) {
1310      RegVT = *PhysReg.second->vt_begin();
1311      TargetRegisterClass::iterator I = PhysReg.second->begin();
1312      TargetRegisterClass::iterator E = PhysReg.second->end();
1313      for (; *I != PhysReg.first; ++I)
1314        assert(I != E && "Didn't find reg!");
1315
1316      // Already added the first reg.
1317      --NumRegs; ++I;
1318      for (; NumRegs; --NumRegs, ++I) {
1319        assert(I != E && "Ran out of registers to allocate!");
1320        Regs.push_back(*I);
1321      }
1322    }
1323    return RegsForValue(Regs, RegVT, ValueVT);
1324  }
1325
1326  // This is a reference to a register class.  Allocate NumRegs consecutive,
1327  // available, registers from the class.
1328  std::vector<unsigned> RegClassRegs =
1329    TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1330
1331  const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1332  MachineFunction &MF = *CurMBB->getParent();
1333  unsigned NumAllocated = 0;
1334  for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1335    unsigned Reg = RegClassRegs[i];
1336    // See if this register is available.
1337    if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
1338        (isInReg  && InputRegs.count(Reg))) {    // Already used.
1339      // Make sure we find consecutive registers.
1340      NumAllocated = 0;
1341      continue;
1342    }
1343
1344    // Check to see if this register is allocatable (i.e. don't give out the
1345    // stack pointer).
1346    const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1347    if (!RC) {
1348      // Make sure we find consecutive registers.
1349      NumAllocated = 0;
1350      continue;
1351    }
1352
1353    // Okay, this register is good, we can use it.
1354    ++NumAllocated;
1355
1356    // If we allocated enough consecutive
1357    if (NumAllocated == NumRegs) {
1358      unsigned RegStart = (i-NumAllocated)+1;
1359      unsigned RegEnd   = i+1;
1360      // Mark all of the allocated registers used.
1361      for (unsigned i = RegStart; i != RegEnd; ++i) {
1362        unsigned Reg = RegClassRegs[i];
1363        Regs.push_back(Reg);
1364        if (isOutReg) OutputRegs.insert(Reg);    // Mark reg used.
1365        if (isInReg)  InputRegs.insert(Reg);     // Mark reg used.
1366      }
1367
1368      return RegsForValue(Regs, *RC->vt_begin(), VT);
1369    }
1370  }
1371
1372  // Otherwise, we couldn't allocate enough registers for this.
1373  return RegsForValue();
1374}
1375
1376
1377/// visitInlineAsm - Handle a call to an InlineAsm object.
1378///
1379void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1380  InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1381
1382  SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1383                                                 MVT::Other);
1384
1385  // Note, we treat inline asms both with and without side-effects as the same.
1386  // If an inline asm doesn't have side effects and doesn't access memory, we
1387  // could not choose to not chain it.
1388  bool hasSideEffects = IA->hasSideEffects();
1389
1390  std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1391  std::vector<MVT::ValueType> ConstraintVTs;
1392
1393  /// AsmNodeOperands - A list of pairs.  The first element is a register, the
1394  /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1395  /// if it is a def of that register.
1396  std::vector<SDOperand> AsmNodeOperands;
1397  AsmNodeOperands.push_back(SDOperand());  // reserve space for input chain
1398  AsmNodeOperands.push_back(AsmStr);
1399
1400  SDOperand Chain = getRoot();
1401  SDOperand Flag;
1402
1403  // We fully assign registers here at isel time.  This is not optimal, but
1404  // should work.  For register classes that correspond to LLVM classes, we
1405  // could let the LLVM RA do its thing, but we currently don't.  Do a prepass
1406  // over the constraints, collecting fixed registers that we know we can't use.
1407  std::set<unsigned> OutputRegs, InputRegs;
1408  unsigned OpNum = 1;
1409  for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1410    assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1411    std::string &ConstraintCode = Constraints[i].Codes[0];
1412
1413    MVT::ValueType OpVT;
1414
1415    // Compute the value type for each operand and add it to ConstraintVTs.
1416    switch (Constraints[i].Type) {
1417    case InlineAsm::isOutput:
1418      if (!Constraints[i].isIndirectOutput) {
1419        assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1420        OpVT = TLI.getValueType(I.getType());
1421      } else {
1422        Value *CallOperand = I.getOperand(OpNum);
1423        const Type *OpTy = CallOperand->getType();
1424        OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1425        OpNum++;  // Consumes a call operand.
1426      }
1427      break;
1428    case InlineAsm::isInput:
1429      OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1430      OpNum++;  // Consumes a call operand.
1431      break;
1432    case InlineAsm::isClobber:
1433      OpVT = MVT::Other;
1434      break;
1435    }
1436
1437    ConstraintVTs.push_back(OpVT);
1438
1439    if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1440      continue;  // Not assigned a fixed reg.
1441
1442    // Build a list of regs that this operand uses.  This always has a single
1443    // element for promoted/expanded operands.
1444    RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1445                                             false, false,
1446                                             OutputRegs, InputRegs);
1447
1448    switch (Constraints[i].Type) {
1449    case InlineAsm::isOutput:
1450      // We can't assign any other output to this register.
1451      OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1452      // If this is an early-clobber output, it cannot be assigned to the same
1453      // value as the input reg.
1454      if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1455        InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1456      break;
1457    case InlineAsm::isInput:
1458      // We can't assign any other input to this register.
1459      InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1460      break;
1461    case InlineAsm::isClobber:
1462      // Clobbered regs cannot be used as inputs or outputs.
1463      InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1464      OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1465      break;
1466    }
1467  }
1468
1469  // Loop over all of the inputs, copying the operand values into the
1470  // appropriate registers and processing the output regs.
1471  RegsForValue RetValRegs;
1472  std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
1473  OpNum = 1;
1474
1475  for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1476    assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1477    std::string &ConstraintCode = Constraints[i].Codes[0];
1478
1479    switch (Constraints[i].Type) {
1480    case InlineAsm::isOutput: {
1481      // If this is an early-clobber output, or if there is an input
1482      // constraint that matches this, we need to reserve the input register
1483      // so no other inputs allocate to it.
1484      bool UsesInputRegister = false;
1485      if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1486        UsesInputRegister = true;
1487
1488      // Copy the output from the appropriate register.  Find a register that
1489      // we can use.
1490      RegsForValue Regs =
1491        GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1492                             true, UsesInputRegister,
1493                             OutputRegs, InputRegs);
1494      assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
1495
1496      if (!Constraints[i].isIndirectOutput) {
1497        assert(RetValRegs.Regs.empty() &&
1498               "Cannot have multiple output constraints yet!");
1499        assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1500        RetValRegs = Regs;
1501      } else {
1502        Value *CallOperand = I.getOperand(OpNum);
1503        IndirectStoresToEmit.push_back(std::make_pair(Regs, CallOperand));
1504        OpNum++;  // Consumes a call operand.
1505      }
1506
1507      // Add information to the INLINEASM node to know that this register is
1508      // set.
1509      Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
1510      break;
1511    }
1512    case InlineAsm::isInput: {
1513      Value *CallOperand = I.getOperand(OpNum);
1514      OpNum++;  // Consumes a call operand.
1515
1516      SDOperand InOperandVal = getValue(CallOperand);
1517
1518      if (isdigit(ConstraintCode[0])) {    // Matching constraint?
1519        // If this is required to match an output register we have already set,
1520        // just use its register.
1521        unsigned OperandNo = atoi(ConstraintCode.c_str());
1522
1523        // Scan until we find the definition we already emitted of this operand.
1524        // When we find it, create a RegsForValue operand.
1525        unsigned CurOp = 2;  // The first operand.
1526        for (; OperandNo; --OperandNo) {
1527          // Advance to the next operand.
1528          unsigned NumOps =
1529            cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1530          assert((NumOps & 7) == 2 /*REGDEF*/ &&
1531                 "Skipped past definitions?");
1532          CurOp += (NumOps>>3)+1;
1533        }
1534
1535        unsigned NumOps =
1536          cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1537        assert((NumOps & 7) == 2 /*REGDEF*/ &&
1538               "Skipped past definitions?");
1539
1540        // Add NumOps>>3 registers to MatchedRegs.
1541        RegsForValue MatchedRegs;
1542        MatchedRegs.ValueVT = InOperandVal.getValueType();
1543        MatchedRegs.RegVT   = AsmNodeOperands[CurOp+1].getValueType();
1544        for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1545          unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1546          MatchedRegs.Regs.push_back(Reg);
1547        }
1548
1549        // Use the produced MatchedRegs object to
1550        MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1551        MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
1552        break;
1553      }
1554
1555      TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1556      if (ConstraintCode.size() == 1)   // not a physreg name.
1557        CTy = TLI.getConstraintType(ConstraintCode[0]);
1558
1559      if (CTy == TargetLowering::C_Other) {
1560        if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1561          assert(0 && "MATCH FAIL!");
1562
1563        // Add information to the INLINEASM node to know about this input.
1564        unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1565        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1566        AsmNodeOperands.push_back(InOperandVal);
1567        break;
1568      } else if (CTy == TargetLowering::C_Memory) {
1569        // Memory input.
1570
1571        // Check that the operand isn't a float.
1572        if (!MVT::isInteger(InOperandVal.getValueType()))
1573          assert(0 && "MATCH FAIL!");
1574
1575        // Extend/truncate to the right pointer type if needed.
1576        MVT::ValueType PtrType = TLI.getPointerTy();
1577        if (InOperandVal.getValueType() < PtrType)
1578          InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1579        else if (InOperandVal.getValueType() > PtrType)
1580          InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1581
1582        // Add information to the INLINEASM node to know about this input.
1583        unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1584        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1585        AsmNodeOperands.push_back(InOperandVal);
1586        break;
1587      }
1588
1589      assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1590
1591      // Copy the input into the appropriate registers.
1592      RegsForValue InRegs =
1593        GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1594                             false, true, OutputRegs, InputRegs);
1595      // FIXME: should be match fail.
1596      assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
1597
1598      InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1599
1600      InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
1601      break;
1602    }
1603    case InlineAsm::isClobber: {
1604      RegsForValue ClobberedRegs =
1605        GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
1606                             OutputRegs, InputRegs);
1607      // Add the clobbered value to the operand list, so that the register
1608      // allocator is aware that the physreg got clobbered.
1609      if (!ClobberedRegs.Regs.empty())
1610        ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
1611      break;
1612    }
1613    }
1614  }
1615
1616  // Finish up input operands.
1617  AsmNodeOperands[0] = Chain;
1618  if (Flag.Val) AsmNodeOperands.push_back(Flag);
1619
1620  std::vector<MVT::ValueType> VTs;
1621  VTs.push_back(MVT::Other);
1622  VTs.push_back(MVT::Flag);
1623  Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
1624  Flag = Chain.getValue(1);
1625
1626  // If this asm returns a register value, copy the result from that register
1627  // and set it as the value of the call.
1628  if (!RetValRegs.Regs.empty())
1629    setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
1630
1631  std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
1632
1633  // Process indirect outputs, first output all of the flagged copies out of
1634  // physregs.
1635  for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
1636    RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
1637    Value *Ptr = IndirectStoresToEmit[i].second;
1638    SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
1639    StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
1640  }
1641
1642  // Emit the non-flagged stores from the physregs.
1643  std::vector<SDOperand> OutChains;
1644  for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
1645    OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
1646                                    StoresToEmit[i].first,
1647                                    getValue(StoresToEmit[i].second),
1648                                    DAG.getSrcValue(StoresToEmit[i].second)));
1649  if (!OutChains.empty())
1650    Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
1651  DAG.setRoot(Chain);
1652}
1653
1654
1655void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1656  SDOperand Src = getValue(I.getOperand(0));
1657
1658  MVT::ValueType IntPtr = TLI.getPointerTy();
1659
1660  if (IntPtr < Src.getValueType())
1661    Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1662  else if (IntPtr > Src.getValueType())
1663    Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
1664
1665  // Scale the source by the type size.
1666  uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1667  Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1668                    Src, getIntPtrConstant(ElementSize));
1669
1670  std::vector<std::pair<SDOperand, const Type*> > Args;
1671  Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
1672
1673  std::pair<SDOperand,SDOperand> Result =
1674    TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
1675                    DAG.getExternalSymbol("malloc", IntPtr),
1676                    Args, DAG);
1677  setValue(&I, Result.first);  // Pointers always fit in registers
1678  DAG.setRoot(Result.second);
1679}
1680
1681void SelectionDAGLowering::visitFree(FreeInst &I) {
1682  std::vector<std::pair<SDOperand, const Type*> > Args;
1683  Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1684                                TLI.getTargetData().getIntPtrType()));
1685  MVT::ValueType IntPtr = TLI.getPointerTy();
1686  std::pair<SDOperand,SDOperand> Result =
1687    TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
1688                    DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1689  DAG.setRoot(Result.second);
1690}
1691
1692// InsertAtEndOfBasicBlock - This method should be implemented by targets that
1693// mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
1694// instructions are special in various ways, which require special support to
1695// insert.  The specified MachineInstr is created but not inserted into any
1696// basic blocks, and the scheduler passes ownership of it to this method.
1697MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1698                                                       MachineBasicBlock *MBB) {
1699  std::cerr << "If a target marks an instruction with "
1700               "'usesCustomDAGSchedInserter', it must implement "
1701               "TargetLowering::InsertAtEndOfBasicBlock!\n";
1702  abort();
1703  return 0;
1704}
1705
1706void SelectionDAGLowering::visitVAStart(CallInst &I) {
1707  DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
1708                          getValue(I.getOperand(1)),
1709                          DAG.getSrcValue(I.getOperand(1))));
1710}
1711
1712void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1713  SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
1714                             getValue(I.getOperand(0)),
1715                             DAG.getSrcValue(I.getOperand(0)));
1716  setValue(&I, V);
1717  DAG.setRoot(V.getValue(1));
1718}
1719
1720void SelectionDAGLowering::visitVAEnd(CallInst &I) {
1721  DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
1722                          getValue(I.getOperand(1)),
1723                          DAG.getSrcValue(I.getOperand(1))));
1724}
1725
1726void SelectionDAGLowering::visitVACopy(CallInst &I) {
1727  DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
1728                          getValue(I.getOperand(1)),
1729                          getValue(I.getOperand(2)),
1730                          DAG.getSrcValue(I.getOperand(1)),
1731                          DAG.getSrcValue(I.getOperand(2))));
1732}
1733
1734// It is always conservatively correct for llvm.returnaddress and
1735// llvm.frameaddress to return 0.
1736std::pair<SDOperand, SDOperand>
1737TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1738                                        unsigned Depth, SelectionDAG &DAG) {
1739  return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
1740}
1741
1742SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1743  assert(0 && "LowerOperation not implemented for this target!");
1744  abort();
1745  return SDOperand();
1746}
1747
1748SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
1749                                                 SelectionDAG &DAG) {
1750  assert(0 && "CustomPromoteOperation not implemented for this target!");
1751  abort();
1752  return SDOperand();
1753}
1754
1755void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1756  unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1757  std::pair<SDOperand,SDOperand> Result =
1758    TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
1759  setValue(&I, Result.first);
1760  DAG.setRoot(Result.second);
1761}
1762
1763/// getMemsetValue - Vectorized representation of the memset value
1764/// operand.
1765static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
1766                                SelectionDAG &DAG) {
1767  MVT::ValueType CurVT = VT;
1768  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
1769    uint64_t Val   = C->getValue() & 255;
1770    unsigned Shift = 8;
1771    while (CurVT != MVT::i8) {
1772      Val = (Val << Shift) | Val;
1773      Shift <<= 1;
1774      CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
1775    }
1776    return DAG.getConstant(Val, VT);
1777  } else {
1778    Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
1779    unsigned Shift = 8;
1780    while (CurVT != MVT::i8) {
1781      Value =
1782        DAG.getNode(ISD::OR, VT,
1783                    DAG.getNode(ISD::SHL, VT, Value,
1784                                DAG.getConstant(Shift, MVT::i8)), Value);
1785      Shift <<= 1;
1786      CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
1787    }
1788
1789    return Value;
1790  }
1791}
1792
1793/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
1794/// used when a memcpy is turned into a memset when the source is a constant
1795/// string ptr.
1796static SDOperand getMemsetStringVal(MVT::ValueType VT,
1797                                    SelectionDAG &DAG, TargetLowering &TLI,
1798                                    std::string &Str, unsigned Offset) {
1799  MVT::ValueType CurVT = VT;
1800  uint64_t Val = 0;
1801  unsigned MSB = getSizeInBits(VT) / 8;
1802  if (TLI.isLittleEndian())
1803    Offset = Offset + MSB - 1;
1804  for (unsigned i = 0; i != MSB; ++i) {
1805    Val = (Val << 8) | Str[Offset];
1806    Offset += TLI.isLittleEndian() ? -1 : 1;
1807  }
1808  return DAG.getConstant(Val, VT);
1809}
1810
1811/// getMemBasePlusOffset - Returns base and offset node for the
1812static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
1813                                      SelectionDAG &DAG, TargetLowering &TLI) {
1814  MVT::ValueType VT = Base.getValueType();
1815  return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
1816}
1817
1818/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
1819/// to replace the memset / memcpy is below the threshold. It also returns the
1820/// types of the sequence of  memory ops to perform memset / memcpy.
1821static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
1822                                     unsigned Limit, uint64_t Size,
1823                                     unsigned Align, TargetLowering &TLI) {
1824  MVT::ValueType VT;
1825
1826  if (TLI.allowsUnalignedMemoryAccesses()) {
1827    VT = MVT::i64;
1828  } else {
1829    switch (Align & 7) {
1830    case 0:
1831      VT = MVT::i64;
1832      break;
1833    case 4:
1834      VT = MVT::i32;
1835      break;
1836    case 2:
1837      VT = MVT::i16;
1838      break;
1839    default:
1840      VT = MVT::i8;
1841      break;
1842    }
1843  }
1844
1845  MVT::ValueType LVT = MVT::i64;
1846  while (!TLI.isTypeLegal(LVT))
1847    LVT = (MVT::ValueType)((unsigned)LVT - 1);
1848  assert(MVT::isInteger(LVT));
1849
1850  if (VT > LVT)
1851    VT = LVT;
1852
1853  unsigned NumMemOps = 0;
1854  while (Size != 0) {
1855    unsigned VTSize = getSizeInBits(VT) / 8;
1856    while (VTSize > Size) {
1857      VT = (MVT::ValueType)((unsigned)VT - 1);
1858      VTSize >>= 1;
1859    }
1860    assert(MVT::isInteger(VT));
1861
1862    if (++NumMemOps > Limit)
1863      return false;
1864    MemOps.push_back(VT);
1865    Size -= VTSize;
1866  }
1867
1868  return true;
1869}
1870
1871void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1872  SDOperand Op1 = getValue(I.getOperand(1));
1873  SDOperand Op2 = getValue(I.getOperand(2));
1874  SDOperand Op3 = getValue(I.getOperand(3));
1875  SDOperand Op4 = getValue(I.getOperand(4));
1876  unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
1877  if (Align == 0) Align = 1;
1878
1879  if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
1880    std::vector<MVT::ValueType> MemOps;
1881
1882    // Expand memset / memcpy to a series of load / store ops
1883    // if the size operand falls below a certain threshold.
1884    std::vector<SDOperand> OutChains;
1885    switch (Op) {
1886    default: break;  // Do nothing for now.
1887    case ISD::MEMSET: {
1888      if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
1889                                   Size->getValue(), Align, TLI)) {
1890        unsigned NumMemOps = MemOps.size();
1891        unsigned Offset = 0;
1892        for (unsigned i = 0; i < NumMemOps; i++) {
1893          MVT::ValueType VT = MemOps[i];
1894          unsigned VTSize = getSizeInBits(VT) / 8;
1895          SDOperand Value = getMemsetValue(Op2, VT, DAG);
1896          SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
1897                                        Value,
1898                                    getMemBasePlusOffset(Op1, Offset, DAG, TLI),
1899                                      DAG.getSrcValue(I.getOperand(1), Offset));
1900          OutChains.push_back(Store);
1901          Offset += VTSize;
1902        }
1903      }
1904      break;
1905    }
1906    case ISD::MEMCPY: {
1907      if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
1908                                   Size->getValue(), Align, TLI)) {
1909        unsigned NumMemOps = MemOps.size();
1910        unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
1911        GlobalAddressSDNode *G = NULL;
1912        std::string Str;
1913        bool CopyFromStr = false;
1914
1915        if (Op2.getOpcode() == ISD::GlobalAddress)
1916          G = cast<GlobalAddressSDNode>(Op2);
1917        else if (Op2.getOpcode() == ISD::ADD &&
1918                 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
1919                 Op2.getOperand(1).getOpcode() == ISD::Constant) {
1920          G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
1921          SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
1922        }
1923        if (G) {
1924          GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
1925          if (GV) {
1926            Str = getStringValue(GV);
1927            if (!Str.empty()) {
1928              CopyFromStr = true;
1929              SrcOff += SrcDelta;
1930            }
1931          }
1932        }
1933
1934        for (unsigned i = 0; i < NumMemOps; i++) {
1935          MVT::ValueType VT = MemOps[i];
1936          unsigned VTSize = getSizeInBits(VT) / 8;
1937          SDOperand Value, Chain, Store;
1938
1939          if (CopyFromStr) {
1940            Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
1941            Chain = getRoot();
1942            Store =
1943              DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1944                          getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1945                          DAG.getSrcValue(I.getOperand(1), DstOff));
1946          } else {
1947            Value = DAG.getLoad(VT, getRoot(),
1948                        getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
1949                        DAG.getSrcValue(I.getOperand(2), SrcOff));
1950            Chain = Value.getValue(1);
1951            Store =
1952              DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
1953                          getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
1954                          DAG.getSrcValue(I.getOperand(1), DstOff));
1955          }
1956          OutChains.push_back(Store);
1957          SrcOff += VTSize;
1958          DstOff += VTSize;
1959        }
1960      }
1961      break;
1962    }
1963    }
1964
1965    if (!OutChains.empty()) {
1966      DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
1967      return;
1968    }
1969  }
1970
1971  std::vector<SDOperand> Ops;
1972  Ops.push_back(getRoot());
1973  Ops.push_back(Op1);
1974  Ops.push_back(Op2);
1975  Ops.push_back(Op3);
1976  Ops.push_back(Op4);
1977  DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1978}
1979
1980//===----------------------------------------------------------------------===//
1981// SelectionDAGISel code
1982//===----------------------------------------------------------------------===//
1983
1984unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1985  return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1986}
1987
1988void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1989  // FIXME: we only modify the CFG to split critical edges.  This
1990  // updates dom and loop info.
1991}
1992
1993
1994/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1995/// casting to the type of GEPI.
1996static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1997                                   Value *Ptr, Value *PtrOffset) {
1998  if (V) return V;   // Already computed.
1999
2000  BasicBlock::iterator InsertPt;
2001  if (BB == GEPI->getParent()) {
2002    // If insert into the GEP's block, insert right after the GEP.
2003    InsertPt = GEPI;
2004    ++InsertPt;
2005  } else {
2006    // Otherwise, insert at the top of BB, after any PHI nodes
2007    InsertPt = BB->begin();
2008    while (isa<PHINode>(InsertPt)) ++InsertPt;
2009  }
2010
2011  // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2012  // BB so that there is only one value live across basic blocks (the cast
2013  // operand).
2014  if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2015    if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2016      Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2017
2018  // Add the offset, cast it to the right type.
2019  Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2020  Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2021  return V = Ptr;
2022}
2023
2024
2025/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2026/// selection, we want to be a bit careful about some things.  In particular, if
2027/// we have a GEP instruction that is used in a different block than it is
2028/// defined, the addressing expression of the GEP cannot be folded into loads or
2029/// stores that use it.  In this case, decompose the GEP and move constant
2030/// indices into blocks that use it.
2031static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2032                                  const TargetData &TD) {
2033  // If this GEP is only used inside the block it is defined in, there is no
2034  // need to rewrite it.
2035  bool isUsedOutsideDefBB = false;
2036  BasicBlock *DefBB = GEPI->getParent();
2037  for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2038       UI != E; ++UI) {
2039    if (cast<Instruction>(*UI)->getParent() != DefBB) {
2040      isUsedOutsideDefBB = true;
2041      break;
2042    }
2043  }
2044  if (!isUsedOutsideDefBB) return;
2045
2046  // If this GEP has no non-zero constant indices, there is nothing we can do,
2047  // ignore it.
2048  bool hasConstantIndex = false;
2049  for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2050       E = GEPI->op_end(); OI != E; ++OI) {
2051    if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2052      if (CI->getRawValue()) {
2053        hasConstantIndex = true;
2054        break;
2055      }
2056  }
2057  // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2058  if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
2059
2060  // Otherwise, decompose the GEP instruction into multiplies and adds.  Sum the
2061  // constant offset (which we now know is non-zero) and deal with it later.
2062  uint64_t ConstantOffset = 0;
2063  const Type *UIntPtrTy = TD.getIntPtrType();
2064  Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2065  const Type *Ty = GEPI->getOperand(0)->getType();
2066
2067  for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2068       E = GEPI->op_end(); OI != E; ++OI) {
2069    Value *Idx = *OI;
2070    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2071      unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2072      if (Field)
2073        ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2074      Ty = StTy->getElementType(Field);
2075    } else {
2076      Ty = cast<SequentialType>(Ty)->getElementType();
2077
2078      // Handle constant subscripts.
2079      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2080        if (CI->getRawValue() == 0) continue;
2081
2082        if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2083          ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2084        else
2085          ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2086        continue;
2087      }
2088
2089      // Ptr = Ptr + Idx * ElementSize;
2090
2091      // Cast Idx to UIntPtrTy if needed.
2092      Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2093
2094      uint64_t ElementSize = TD.getTypeSize(Ty);
2095      // Mask off bits that should not be set.
2096      ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2097      Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2098
2099      // Multiply by the element size and add to the base.
2100      Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2101      Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2102    }
2103  }
2104
2105  // Make sure that the offset fits in uintptr_t.
2106  ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2107  Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2108
2109  // Okay, we have now emitted all of the variable index parts to the BB that
2110  // the GEP is defined in.  Loop over all of the using instructions, inserting
2111  // an "add Ptr, ConstantOffset" into each block that uses it and update the
2112  // instruction to use the newly computed value, making GEPI dead.  When the
2113  // user is a load or store instruction address, we emit the add into the user
2114  // block, otherwise we use a canonical version right next to the gep (these
2115  // won't be foldable as addresses, so we might as well share the computation).
2116
2117  std::map<BasicBlock*,Value*> InsertedExprs;
2118  while (!GEPI->use_empty()) {
2119    Instruction *User = cast<Instruction>(GEPI->use_back());
2120
2121    // If this use is not foldable into the addressing mode, use a version
2122    // emitted in the GEP block.
2123    Value *NewVal;
2124    if (!isa<LoadInst>(User) &&
2125        (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2126      NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2127                                    Ptr, PtrOffset);
2128    } else {
2129      // Otherwise, insert the code in the User's block so it can be folded into
2130      // any users in that block.
2131      NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
2132                                    User->getParent(), GEPI,
2133                                    Ptr, PtrOffset);
2134    }
2135    User->replaceUsesOfWith(GEPI, NewVal);
2136  }
2137
2138  // Finally, the GEP is dead, remove it.
2139  GEPI->eraseFromParent();
2140}
2141
2142bool SelectionDAGISel::runOnFunction(Function &Fn) {
2143  MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2144  RegMap = MF.getSSARegMap();
2145  DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2146
2147  // First, split all critical edges for PHI nodes with incoming values that are
2148  // constants, this way the load of the constant into a vreg will not be placed
2149  // into MBBs that are used some other way.
2150  //
2151  // In this pass we also look for GEP instructions that are used across basic
2152  // blocks and rewrites them to improve basic-block-at-a-time selection.
2153  //
2154  for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2155    PHINode *PN;
2156    BasicBlock::iterator BBI;
2157    for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
2158      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2159        if (isa<Constant>(PN->getIncomingValue(i)))
2160          SplitCriticalEdge(PN->getIncomingBlock(i), BB);
2161
2162    for (BasicBlock::iterator E = BB->end(); BBI != E; )
2163      if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2164        OptimizeGEPExpression(GEPI, TLI.getTargetData());
2165  }
2166
2167  FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2168
2169  for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2170    SelectBasicBlock(I, MF, FuncInfo);
2171
2172  return true;
2173}
2174
2175
2176SDOperand SelectionDAGISel::
2177CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
2178  SDOperand Op = SDL.getValue(V);
2179  assert((Op.getOpcode() != ISD::CopyFromReg ||
2180          cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
2181         "Copy from a reg to the same reg!");
2182
2183  // If this type is not legal, we must make sure to not create an invalid
2184  // register use.
2185  MVT::ValueType SrcVT = Op.getValueType();
2186  MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2187  SelectionDAG &DAG = SDL.DAG;
2188  if (SrcVT == DestVT) {
2189    return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2190  } else if (SrcVT < DestVT) {
2191    // The src value is promoted to the register.
2192    if (MVT::isFloatingPoint(SrcVT))
2193      Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2194    else
2195      Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
2196    return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2197  } else  {
2198    // The src value is expanded into multiple registers.
2199    SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2200                               Op, DAG.getConstant(0, MVT::i32));
2201    SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2202                               Op, DAG.getConstant(1, MVT::i32));
2203    Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2204    return DAG.getCopyToReg(Op, Reg+1, Hi);
2205  }
2206}
2207
2208void SelectionDAGISel::
2209LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2210               std::vector<SDOperand> &UnorderedChains) {
2211  // If this is the entry block, emit arguments.
2212  Function &F = *BB->getParent();
2213  FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
2214  SDOperand OldRoot = SDL.DAG.getRoot();
2215  std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
2216
2217  unsigned a = 0;
2218  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2219       AI != E; ++AI, ++a)
2220    if (!AI->use_empty()) {
2221      SDL.setValue(AI, Args[a]);
2222
2223      // If this argument is live outside of the entry block, insert a copy from
2224      // whereever we got it to the vreg that other BB's will reference it as.
2225      if (FuncInfo.ValueMap.count(AI)) {
2226        SDOperand Copy =
2227          CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2228        UnorderedChains.push_back(Copy);
2229      }
2230    }
2231
2232  // Next, if the function has live ins that need to be copied into vregs,
2233  // emit the copies now, into the top of the block.
2234  MachineFunction &MF = SDL.DAG.getMachineFunction();
2235  if (MF.livein_begin() != MF.livein_end()) {
2236    SSARegMap *RegMap = MF.getSSARegMap();
2237    const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2238    for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2239         E = MF.livein_end(); LI != E; ++LI)
2240      if (LI->second)
2241        MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2242                         LI->first, RegMap->getRegClass(LI->second));
2243  }
2244
2245  // Finally, if the target has anything special to do, allow it to do so.
2246  EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
2247}
2248
2249
2250void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2251       std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2252                                    FunctionLoweringInfo &FuncInfo) {
2253  SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
2254
2255  std::vector<SDOperand> UnorderedChains;
2256
2257  // Lower any arguments needed in this block if this is the entry block.
2258  if (LLVMBB == &LLVMBB->getParent()->front())
2259    LowerArguments(LLVMBB, SDL, UnorderedChains);
2260
2261  BB = FuncInfo.MBBMap[LLVMBB];
2262  SDL.setCurrentBasicBlock(BB);
2263
2264  // Lower all of the non-terminator instructions.
2265  for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2266       I != E; ++I)
2267    SDL.visit(*I);
2268
2269  // Ensure that all instructions which are used outside of their defining
2270  // blocks are available as virtual registers.
2271  for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
2272    if (!I->use_empty() && !isa<PHINode>(I)) {
2273      std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
2274      if (VMI != FuncInfo.ValueMap.end())
2275        UnorderedChains.push_back(
2276                           CopyValueToVirtualRegister(SDL, I, VMI->second));
2277    }
2278
2279  // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
2280  // ensure constants are generated when needed.  Remember the virtual registers
2281  // that need to be added to the Machine PHI nodes as input.  We cannot just
2282  // directly add them, because expansion might result in multiple MBB's for one
2283  // BB.  As such, the start of the BB might correspond to a different MBB than
2284  // the end.
2285  //
2286
2287  // Emit constants only once even if used by multiple PHI nodes.
2288  std::map<Constant*, unsigned> ConstantsOut;
2289
2290  // Check successor nodes PHI nodes that expect a constant to be available from
2291  // this block.
2292  TerminatorInst *TI = LLVMBB->getTerminator();
2293  for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2294    BasicBlock *SuccBB = TI->getSuccessor(succ);
2295    MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2296    PHINode *PN;
2297
2298    // At this point we know that there is a 1-1 correspondence between LLVM PHI
2299    // nodes and Machine PHI nodes, but the incoming operands have not been
2300    // emitted yet.
2301    for (BasicBlock::iterator I = SuccBB->begin();
2302         (PN = dyn_cast<PHINode>(I)); ++I)
2303      if (!PN->use_empty()) {
2304        unsigned Reg;
2305        Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2306        if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2307          unsigned &RegOut = ConstantsOut[C];
2308          if (RegOut == 0) {
2309            RegOut = FuncInfo.CreateRegForValue(C);
2310            UnorderedChains.push_back(
2311                             CopyValueToVirtualRegister(SDL, C, RegOut));
2312          }
2313          Reg = RegOut;
2314        } else {
2315          Reg = FuncInfo.ValueMap[PHIOp];
2316          if (Reg == 0) {
2317            assert(isa<AllocaInst>(PHIOp) &&
2318                   FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2319                   "Didn't codegen value into a register!??");
2320            Reg = FuncInfo.CreateRegForValue(PHIOp);
2321            UnorderedChains.push_back(
2322                             CopyValueToVirtualRegister(SDL, PHIOp, Reg));
2323          }
2324        }
2325
2326        // Remember that this register needs to added to the machine PHI node as
2327        // the input for this MBB.
2328        unsigned NumElements =
2329          TLI.getNumElements(TLI.getValueType(PN->getType()));
2330        for (unsigned i = 0, e = NumElements; i != e; ++i)
2331          PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
2332      }
2333  }
2334  ConstantsOut.clear();
2335
2336  // Turn all of the unordered chains into one factored node.
2337  if (!UnorderedChains.empty()) {
2338    SDOperand Root = SDL.getRoot();
2339    if (Root.getOpcode() != ISD::EntryToken) {
2340      unsigned i = 0, e = UnorderedChains.size();
2341      for (; i != e; ++i) {
2342        assert(UnorderedChains[i].Val->getNumOperands() > 1);
2343        if (UnorderedChains[i].Val->getOperand(0) == Root)
2344          break;  // Don't add the root if we already indirectly depend on it.
2345      }
2346
2347      if (i == e)
2348        UnorderedChains.push_back(Root);
2349    }
2350    DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2351  }
2352
2353  // Lower the terminator after the copies are emitted.
2354  SDL.visit(*LLVMBB->getTerminator());
2355
2356  // Make sure the root of the DAG is up-to-date.
2357  DAG.setRoot(SDL.getRoot());
2358}
2359
2360void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2361                                        FunctionLoweringInfo &FuncInfo) {
2362  SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2363  CurDAG = &DAG;
2364  std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2365
2366  // First step, lower LLVM code to some DAG.  This DAG may use operations and
2367  // types that are not supported by the target.
2368  BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2369
2370  // Run the DAG combiner in pre-legalize mode.
2371  DAG.Combine(false);
2372
2373  DEBUG(std::cerr << "Lowered selection DAG:\n");
2374  DEBUG(DAG.dump());
2375
2376  // Second step, hack on the DAG until it only uses operations and types that
2377  // the target supports.
2378  DAG.Legalize();
2379
2380  DEBUG(std::cerr << "Legalized selection DAG:\n");
2381  DEBUG(DAG.dump());
2382
2383  // Run the DAG combiner in post-legalize mode.
2384  DAG.Combine(true);
2385
2386  if (ViewISelDAGs) DAG.viewGraph();
2387
2388  // Third, instruction select all of the operations to machine code, adding the
2389  // code to the MachineBasicBlock.
2390  InstructionSelectBasicBlock(DAG);
2391
2392  DEBUG(std::cerr << "Selected machine code:\n");
2393  DEBUG(BB->dump());
2394
2395  // Next, now that we know what the last MBB the LLVM BB expanded is, update
2396  // PHI nodes in successors.
2397  for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2398    MachineInstr *PHI = PHINodesToUpdate[i].first;
2399    assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2400           "This is not a machine PHI node that we are updating!");
2401    PHI->addRegOperand(PHINodesToUpdate[i].second);
2402    PHI->addMachineBasicBlockOperand(BB);
2403  }
2404
2405  // Finally, add the CFG edges from the last selected MBB to the successor
2406  // MBBs.
2407  TerminatorInst *TI = LLVMBB->getTerminator();
2408  for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
2409    MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
2410    BB->addSuccessor(Succ0MBB);
2411  }
2412}
2413
2414//===----------------------------------------------------------------------===//
2415/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2416/// target node in the graph.
2417void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2418  if (ViewSchedDAGs) DAG.viewGraph();
2419  ScheduleDAG *SL = NULL;
2420
2421  switch (ISHeuristic) {
2422  default: assert(0 && "Unrecognized scheduling heuristic");
2423  case defaultScheduling:
2424    if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2425      SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2426    else /* TargetLowering::SchedulingForRegPressure */
2427      SL = createBURRListDAGScheduler(DAG, BB);
2428    break;
2429  case noScheduling:
2430  case simpleScheduling:
2431  case simpleNoItinScheduling:
2432    SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
2433    break;
2434  case listSchedulingBURR:
2435    SL = createBURRListDAGScheduler(DAG, BB);
2436  }
2437  BB = SL->Run();
2438  delete SL;
2439}
2440