SelectionDAGISel.cpp revision 05f9466cf0f4f47803af7283f7708cb25f4da889
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/IntrinsicInst.h"
26#include "llvm/CodeGen/IntrinsicLowering.h"
27#include "llvm/CodeGen/MachineDebugInfo.h"
28#include "llvm/CodeGen/MachineFunction.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineJumpTableInfo.h"
31#include "llvm/CodeGen/MachineInstrBuilder.h"
32#include "llvm/CodeGen/SelectionDAG.h"
33#include "llvm/CodeGen/SSARegMap.h"
34#include "llvm/Target/MRegisterInfo.h"
35#include "llvm/Target/TargetData.h"
36#include "llvm/Target/TargetFrameInfo.h"
37#include "llvm/Target/TargetInstrInfo.h"
38#include "llvm/Target/TargetLowering.h"
39#include "llvm/Target/TargetMachine.h"
40#include "llvm/Transforms/Utils/BasicBlockUtils.h"
41#include "llvm/Support/CommandLine.h"
42#include "llvm/Support/MathExtras.h"
43#include "llvm/Support/Debug.h"
44#include <map>
45#include <set>
46#include <iostream>
47#include <algorithm>
48using namespace llvm;
49
50#ifndef NDEBUG
51static cl::opt<bool>
52ViewISelDAGs("view-isel-dags", cl::Hidden,
53          cl::desc("Pop up a window to show isel dags as they are selected"));
54static cl::opt<bool>
55ViewSchedDAGs("view-sched-dags", cl::Hidden,
56          cl::desc("Pop up a window to show sched dags as they are processed"));
57#else
58static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
59#endif
60
61// Scheduling heuristics
62enum SchedHeuristics {
63  defaultScheduling,      // Let the target specify its preference.
64  noScheduling,           // No scheduling, emit breadth first sequence.
65  simpleScheduling,       // Two pass, min. critical path, max. utilization.
66  simpleNoItinScheduling, // Same as above exact using generic latency.
67  listSchedulingBURR,     // Bottom up reg reduction list scheduling.
68  listSchedulingTD        // Top-down list scheduler.
69};
70
71namespace {
72  cl::opt<SchedHeuristics>
73  ISHeuristic(
74    "sched",
75    cl::desc("Choose scheduling style"),
76    cl::init(defaultScheduling),
77    cl::values(
78      clEnumValN(defaultScheduling, "default",
79                 "Target preferred scheduling style"),
80      clEnumValN(noScheduling, "none",
81                 "No scheduling: breadth first sequencing"),
82      clEnumValN(simpleScheduling, "simple",
83                 "Simple two pass scheduling: minimize critical path "
84                 "and maximize processor utilization"),
85      clEnumValN(simpleNoItinScheduling, "simple-noitin",
86                 "Simple two pass scheduling: Same as simple "
87                 "except using generic latency"),
88      clEnumValN(listSchedulingBURR, "list-burr",
89                 "Bottom up register reduction list scheduling"),
90      clEnumValN(listSchedulingTD, "list-td",
91                 "Top-down list scheduler"),
92      clEnumValEnd));
93} // namespace
94
95namespace {
96  /// RegsForValue - This struct represents the physical registers that a
97  /// particular value is assigned and the type information about the value.
98  /// This is needed because values can be promoted into larger registers and
99  /// expanded into multiple smaller registers than the value.
100  struct RegsForValue {
101    /// Regs - This list hold the register (for legal and promoted values)
102    /// or register set (for expanded values) that the value should be assigned
103    /// to.
104    std::vector<unsigned> Regs;
105
106    /// RegVT - The value type of each register.
107    ///
108    MVT::ValueType RegVT;
109
110    /// ValueVT - The value type of the LLVM value, which may be promoted from
111    /// RegVT or made from merging the two expanded parts.
112    MVT::ValueType ValueVT;
113
114    RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
115
116    RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
117      : RegVT(regvt), ValueVT(valuevt) {
118        Regs.push_back(Reg);
119    }
120    RegsForValue(const std::vector<unsigned> &regs,
121                 MVT::ValueType regvt, MVT::ValueType valuevt)
122      : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
123    }
124
125    /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
126    /// this value and returns the result as a ValueVT value.  This uses
127    /// Chain/Flag as the input and updates them for the output Chain/Flag.
128    SDOperand getCopyFromRegs(SelectionDAG &DAG,
129                              SDOperand &Chain, SDOperand &Flag) const;
130
131    /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
132    /// specified value into the registers specified by this object.  This uses
133    /// Chain/Flag as the input and updates them for the output Chain/Flag.
134    void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
135                       SDOperand &Chain, SDOperand &Flag) const;
136
137    /// AddInlineAsmOperands - Add this value to the specified inlineasm node
138    /// operand list.  This adds the code marker and includes the number of
139    /// values added into it.
140    void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
141                              std::vector<SDOperand> &Ops) const;
142  };
143}
144
145namespace llvm {
146  //===--------------------------------------------------------------------===//
147  /// FunctionLoweringInfo - This contains information that is global to a
148  /// function that is used when lowering a region of the function.
149  class FunctionLoweringInfo {
150  public:
151    TargetLowering &TLI;
152    Function &Fn;
153    MachineFunction &MF;
154    SSARegMap *RegMap;
155
156    FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
157
158    /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
159    std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
160
161    /// ValueMap - Since we emit code for the function a basic block at a time,
162    /// we must remember which virtual registers hold the values for
163    /// cross-basic-block values.
164    std::map<const Value*, unsigned> ValueMap;
165
166    /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
167    /// the entry block.  This allows the allocas to be efficiently referenced
168    /// anywhere in the function.
169    std::map<const AllocaInst*, int> StaticAllocaMap;
170
171    unsigned MakeReg(MVT::ValueType VT) {
172      return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
173    }
174
175    unsigned CreateRegForValue(const Value *V);
176
177    unsigned InitializeRegForValue(const Value *V) {
178      unsigned &R = ValueMap[V];
179      assert(R == 0 && "Already initialized this value register!");
180      return R = CreateRegForValue(V);
181    }
182  };
183}
184
185/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
186/// PHI nodes or outside of the basic block that defines it, or used by a
187/// switch instruction, which may expand to multiple basic blocks.
188static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
189  if (isa<PHINode>(I)) return true;
190  BasicBlock *BB = I->getParent();
191  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
192    if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
193        isa<SwitchInst>(*UI))
194      return true;
195  return false;
196}
197
198/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
199/// entry block, return true.  This includes arguments used by switches, since
200/// the switch may expand into multiple basic blocks.
201static bool isOnlyUsedInEntryBlock(Argument *A) {
202  BasicBlock *Entry = A->getParent()->begin();
203  for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
204    if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
205      return false;  // Use not in entry block.
206  return true;
207}
208
209FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
210                                           Function &fn, MachineFunction &mf)
211    : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
212
213  // Create a vreg for each argument register that is not dead and is used
214  // outside of the entry block for the function.
215  for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
216       AI != E; ++AI)
217    if (!isOnlyUsedInEntryBlock(AI))
218      InitializeRegForValue(AI);
219
220  // Initialize the mapping of values to registers.  This is only set up for
221  // instruction values that are used outside of the block that defines
222  // them.
223  Function::iterator BB = Fn.begin(), EB = Fn.end();
224  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
225    if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
226      if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
227        const Type *Ty = AI->getAllocatedType();
228        uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
229        unsigned Align =
230          std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
231                   AI->getAlignment());
232
233        // If the alignment of the value is smaller than the size of the value,
234        // and if the size of the value is particularly small (<= 8 bytes),
235        // round up to the size of the value for potentially better performance.
236        //
237        // FIXME: This could be made better with a preferred alignment hook in
238        // TargetData.  It serves primarily to 8-byte align doubles for X86.
239        if (Align < TySize && TySize <= 8) Align = TySize;
240        TySize *= CUI->getValue();   // Get total allocated size.
241        if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
242        StaticAllocaMap[AI] =
243          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
244      }
245
246  for (; BB != EB; ++BB)
247    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
248      if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
249        if (!isa<AllocaInst>(I) ||
250            !StaticAllocaMap.count(cast<AllocaInst>(I)))
251          InitializeRegForValue(I);
252
253  // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
254  // also creates the initial PHI MachineInstrs, though none of the input
255  // operands are populated.
256  for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
257    MachineBasicBlock *MBB = new MachineBasicBlock(BB);
258    MBBMap[BB] = MBB;
259    MF.getBasicBlockList().push_back(MBB);
260
261    // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
262    // appropriate.
263    PHINode *PN;
264    for (BasicBlock::iterator I = BB->begin();
265         (PN = dyn_cast<PHINode>(I)); ++I)
266      if (!PN->use_empty()) {
267        MVT::ValueType VT = TLI.getValueType(PN->getType());
268        unsigned NumElements;
269        if (VT != MVT::Vector)
270          NumElements = TLI.getNumElements(VT);
271        else {
272          MVT::ValueType VT1,VT2;
273          NumElements =
274            TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
275                                       VT1, VT2);
276        }
277        unsigned PHIReg = ValueMap[PN];
278        assert(PHIReg &&"PHI node does not have an assigned virtual register!");
279        for (unsigned i = 0; i != NumElements; ++i)
280          BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
281      }
282  }
283}
284
285/// CreateRegForValue - Allocate the appropriate number of virtual registers of
286/// the correctly promoted or expanded types.  Assign these registers
287/// consecutive vreg numbers and return the first assigned number.
288unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
289  MVT::ValueType VT = TLI.getValueType(V->getType());
290
291  // The number of multiples of registers that we need, to, e.g., split up
292  // a <2 x int64> -> 4 x i32 registers.
293  unsigned NumVectorRegs = 1;
294
295  // If this is a packed type, figure out what type it will decompose into
296  // and how many of the elements it will use.
297  if (VT == MVT::Vector) {
298    const PackedType *PTy = cast<PackedType>(V->getType());
299    unsigned NumElts = PTy->getNumElements();
300    MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
301
302    // Divide the input until we get to a supported size.  This will always
303    // end with a scalar if the target doesn't support vectors.
304    while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
305      NumElts >>= 1;
306      NumVectorRegs <<= 1;
307    }
308    if (NumElts == 1)
309      VT = EltTy;
310    else
311      VT = getVectorType(EltTy, NumElts);
312  }
313
314  // The common case is that we will only create one register for this
315  // value.  If we have that case, create and return the virtual register.
316  unsigned NV = TLI.getNumElements(VT);
317  if (NV == 1) {
318    // If we are promoting this value, pick the next largest supported type.
319    MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
320    unsigned Reg = MakeReg(PromotedType);
321    // If this is a vector of supported or promoted types (e.g. 4 x i16),
322    // create all of the registers.
323    for (unsigned i = 1; i != NumVectorRegs; ++i)
324      MakeReg(PromotedType);
325    return Reg;
326  }
327
328  // If this value is represented with multiple target registers, make sure
329  // to create enough consecutive registers of the right (smaller) type.
330  unsigned NT = VT-1;  // Find the type to use.
331  while (TLI.getNumElements((MVT::ValueType)NT) != 1)
332    --NT;
333
334  unsigned R = MakeReg((MVT::ValueType)NT);
335  for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
336    MakeReg((MVT::ValueType)NT);
337  return R;
338}
339
340//===----------------------------------------------------------------------===//
341/// SelectionDAGLowering - This is the common target-independent lowering
342/// implementation that is parameterized by a TargetLowering object.
343/// Also, targets can overload any lowering method.
344///
345namespace llvm {
346class SelectionDAGLowering {
347  MachineBasicBlock *CurMBB;
348
349  std::map<const Value*, SDOperand> NodeMap;
350
351  /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
352  /// them up and then emit token factor nodes when possible.  This allows us to
353  /// get simple disambiguation between loads without worrying about alias
354  /// analysis.
355  std::vector<SDOperand> PendingLoads;
356
357  /// Case - A pair of values to record the Value for a switch case, and the
358  /// case's target basic block.
359  typedef std::pair<Constant*, MachineBasicBlock*> Case;
360  typedef std::vector<Case>::iterator              CaseItr;
361  typedef std::pair<CaseItr, CaseItr>              CaseRange;
362
363  /// CaseRec - A struct with ctor used in lowering switches to a binary tree
364  /// of conditional branches.
365  struct CaseRec {
366    CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
367    CaseBB(bb), LT(lt), GE(ge), Range(r) {}
368
369    /// CaseBB - The MBB in which to emit the compare and branch
370    MachineBasicBlock *CaseBB;
371    /// LT, GE - If nonzero, we know the current case value must be less-than or
372    /// greater-than-or-equal-to these Constants.
373    Constant *LT;
374    Constant *GE;
375    /// Range - A pair of iterators representing the range of case values to be
376    /// processed at this point in the binary search tree.
377    CaseRange Range;
378  };
379
380  /// The comparison function for sorting Case values.
381  struct CaseCmp {
382    bool operator () (const Case& C1, const Case& C2) {
383      if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
384        return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
385
386      const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
387      return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
388    }
389  };
390
391public:
392  // TLI - This is information that describes the available target features we
393  // need for lowering.  This indicates when operations are unavailable,
394  // implemented with a libcall, etc.
395  TargetLowering &TLI;
396  SelectionDAG &DAG;
397  const TargetData &TD;
398
399  /// SwitchCases - Vector of CaseBlock structures used to communicate
400  /// SwitchInst code generation information.
401  std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
402  SelectionDAGISel::JumpTable JT;
403
404  /// FuncInfo - Information about the function as a whole.
405  ///
406  FunctionLoweringInfo &FuncInfo;
407
408  SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
409                       FunctionLoweringInfo &funcinfo)
410    : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
411      JT(0,0,0), FuncInfo(funcinfo) {
412  }
413
414  /// getRoot - Return the current virtual root of the Selection DAG.
415  ///
416  SDOperand getRoot() {
417    if (PendingLoads.empty())
418      return DAG.getRoot();
419
420    if (PendingLoads.size() == 1) {
421      SDOperand Root = PendingLoads[0];
422      DAG.setRoot(Root);
423      PendingLoads.clear();
424      return Root;
425    }
426
427    // Otherwise, we have to make a token factor node.
428    SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
429    PendingLoads.clear();
430    DAG.setRoot(Root);
431    return Root;
432  }
433
434  void visit(Instruction &I) { visit(I.getOpcode(), I); }
435
436  void visit(unsigned Opcode, User &I) {
437    switch (Opcode) {
438    default: assert(0 && "Unknown instruction type encountered!");
439             abort();
440      // Build the switch statement using the Instruction.def file.
441#define HANDLE_INST(NUM, OPCODE, CLASS) \
442    case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
443#include "llvm/Instruction.def"
444    }
445  }
446
447  void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
448
449  SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
450                        SDOperand SrcValue, SDOperand Root,
451                        bool isVolatile);
452
453  SDOperand getIntPtrConstant(uint64_t Val) {
454    return DAG.getConstant(Val, TLI.getPointerTy());
455  }
456
457  SDOperand getValue(const Value *V);
458
459  const SDOperand &setValue(const Value *V, SDOperand NewN) {
460    SDOperand &N = NodeMap[V];
461    assert(N.Val == 0 && "Already set a value for this node!");
462    return N = NewN;
463  }
464
465  RegsForValue GetRegistersForValue(const std::string &ConstrCode,
466                                    MVT::ValueType VT,
467                                    bool OutReg, bool InReg,
468                                    std::set<unsigned> &OutputRegs,
469                                    std::set<unsigned> &InputRegs);
470
471  // Terminator instructions.
472  void visitRet(ReturnInst &I);
473  void visitBr(BranchInst &I);
474  void visitSwitch(SwitchInst &I);
475  void visitUnreachable(UnreachableInst &I) { /* noop */ }
476
477  // Helper for visitSwitch
478  void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
479  void visitJumpTable(SelectionDAGISel::JumpTable &JT);
480
481  // These all get lowered before this pass.
482  void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
483  void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
484
485  void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
486  void visitShift(User &I, unsigned Opcode);
487  void visitAdd(User &I) {
488    visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD);
489  }
490  void visitSub(User &I);
491  void visitMul(User &I) {
492    visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL);
493  }
494  void visitDiv(User &I) {
495    const Type *Ty = I.getType();
496    visitBinary(I,
497                Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
498                Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
499  }
500  void visitRem(User &I) {
501    const Type *Ty = I.getType();
502    visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
503  }
504  void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
505  void visitOr (User &I) { visitBinary(I, ISD::OR,  0, ISD::VOR); }
506  void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
507  void visitShl(User &I) { visitShift(I, ISD::SHL); }
508  void visitShr(User &I) {
509    visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
510  }
511
512  void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
513  void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
514  void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
515  void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
516  void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
517  void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
518  void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
519
520  void visitExtractElement(User &I);
521  void visitInsertElement(User &I);
522  void visitShuffleVector(User &I);
523
524  void visitGetElementPtr(User &I);
525  void visitCast(User &I);
526  void visitSelect(User &I);
527
528  void visitMalloc(MallocInst &I);
529  void visitFree(FreeInst &I);
530  void visitAlloca(AllocaInst &I);
531  void visitLoad(LoadInst &I);
532  void visitStore(StoreInst &I);
533  void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
534  void visitCall(CallInst &I);
535  void visitInlineAsm(CallInst &I);
536  const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
537  void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
538
539  void visitVAStart(CallInst &I);
540  void visitVAArg(VAArgInst &I);
541  void visitVAEnd(CallInst &I);
542  void visitVACopy(CallInst &I);
543  void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
544
545  void visitMemIntrinsic(CallInst &I, unsigned Op);
546
547  void visitUserOp1(Instruction &I) {
548    assert(0 && "UserOp1 should not exist at instruction selection time!");
549    abort();
550  }
551  void visitUserOp2(Instruction &I) {
552    assert(0 && "UserOp2 should not exist at instruction selection time!");
553    abort();
554  }
555};
556} // end namespace llvm
557
558SDOperand SelectionDAGLowering::getValue(const Value *V) {
559  SDOperand &N = NodeMap[V];
560  if (N.Val) return N;
561
562  const Type *VTy = V->getType();
563  MVT::ValueType VT = TLI.getValueType(VTy);
564  if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
565    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
566      visit(CE->getOpcode(), *CE);
567      assert(N.Val && "visit didn't populate the ValueMap!");
568      return N;
569    } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
570      return N = DAG.getGlobalAddress(GV, VT);
571    } else if (isa<ConstantPointerNull>(C)) {
572      return N = DAG.getConstant(0, TLI.getPointerTy());
573    } else if (isa<UndefValue>(C)) {
574      if (!isa<PackedType>(VTy))
575        return N = DAG.getNode(ISD::UNDEF, VT);
576
577      // Create a VBUILD_VECTOR of undef nodes.
578      const PackedType *PTy = cast<PackedType>(VTy);
579      unsigned NumElements = PTy->getNumElements();
580      MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
581
582      std::vector<SDOperand> Ops;
583      Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
584
585      // Create a VConstant node with generic Vector type.
586      Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
587      Ops.push_back(DAG.getValueType(PVT));
588      return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
589    } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
590      return N = DAG.getConstantFP(CFP->getValue(), VT);
591    } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
592      unsigned NumElements = PTy->getNumElements();
593      MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
594
595      // Now that we know the number and type of the elements, push a
596      // Constant or ConstantFP node onto the ops list for each element of
597      // the packed constant.
598      std::vector<SDOperand> Ops;
599      if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
600        for (unsigned i = 0; i != NumElements; ++i)
601          Ops.push_back(getValue(CP->getOperand(i)));
602      } else {
603        assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
604        SDOperand Op;
605        if (MVT::isFloatingPoint(PVT))
606          Op = DAG.getConstantFP(0, PVT);
607        else
608          Op = DAG.getConstant(0, PVT);
609        Ops.assign(NumElements, Op);
610      }
611
612      // Create a VBUILD_VECTOR node with generic Vector type.
613      Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
614      Ops.push_back(DAG.getValueType(PVT));
615      return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
616    } else {
617      // Canonicalize all constant ints to be unsigned.
618      return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
619    }
620  }
621
622  if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
623    std::map<const AllocaInst*, int>::iterator SI =
624    FuncInfo.StaticAllocaMap.find(AI);
625    if (SI != FuncInfo.StaticAllocaMap.end())
626      return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
627  }
628
629  std::map<const Value*, unsigned>::const_iterator VMI =
630      FuncInfo.ValueMap.find(V);
631  assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
632
633  unsigned InReg = VMI->second;
634
635  // If this type is not legal, make it so now.
636  if (VT != MVT::Vector) {
637    MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
638
639    N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
640    if (DestVT < VT) {
641      // Source must be expanded.  This input value is actually coming from the
642      // register pair VMI->second and VMI->second+1.
643      N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
644                      DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
645    } else if (DestVT > VT) { // Promotion case
646      if (MVT::isFloatingPoint(VT))
647        N = DAG.getNode(ISD::FP_ROUND, VT, N);
648      else
649        N = DAG.getNode(ISD::TRUNCATE, VT, N);
650    }
651  } else {
652    // Otherwise, if this is a vector, make it available as a generic vector
653    // here.
654    MVT::ValueType PTyElementVT, PTyLegalElementVT;
655    const PackedType *PTy = cast<PackedType>(VTy);
656    unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
657                                             PTyLegalElementVT);
658
659    // Build a VBUILD_VECTOR with the input registers.
660    std::vector<SDOperand> Ops;
661    if (PTyElementVT == PTyLegalElementVT) {
662      // If the value types are legal, just VBUILD the CopyFromReg nodes.
663      for (unsigned i = 0; i != NE; ++i)
664        Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
665                                         PTyElementVT));
666    } else if (PTyElementVT < PTyLegalElementVT) {
667      // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
668      for (unsigned i = 0; i != NE; ++i) {
669        SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
670                                          PTyElementVT);
671        if (MVT::isFloatingPoint(PTyElementVT))
672          Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
673        else
674          Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
675        Ops.push_back(Op);
676      }
677    } else {
678      // If the register was expanded, use BUILD_PAIR.
679      assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
680      for (unsigned i = 0; i != NE/2; ++i) {
681        SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
682                                           PTyElementVT);
683        SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
684                                           PTyElementVT);
685        Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
686      }
687    }
688
689    Ops.push_back(DAG.getConstant(NE, MVT::i32));
690    Ops.push_back(DAG.getValueType(PTyLegalElementVT));
691    N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
692
693    // Finally, use a VBIT_CONVERT to make this available as the appropriate
694    // vector type.
695    N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
696                    DAG.getConstant(PTy->getNumElements(),
697                                    MVT::i32),
698                    DAG.getValueType(TLI.getValueType(PTy->getElementType())));
699  }
700
701  return N;
702}
703
704
705void SelectionDAGLowering::visitRet(ReturnInst &I) {
706  if (I.getNumOperands() == 0) {
707    DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
708    return;
709  }
710  std::vector<SDOperand> NewValues;
711  NewValues.push_back(getRoot());
712  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
713    SDOperand RetOp = getValue(I.getOperand(i));
714
715    // If this is an integer return value, we need to promote it ourselves to
716    // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
717    // than sign/zero.
718    if (MVT::isInteger(RetOp.getValueType()) &&
719        RetOp.getValueType() < MVT::i64) {
720      MVT::ValueType TmpVT;
721      if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
722        TmpVT = TLI.getTypeToTransformTo(MVT::i32);
723      else
724        TmpVT = MVT::i32;
725
726      if (I.getOperand(i)->getType()->isSigned())
727        RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
728      else
729        RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
730    }
731    NewValues.push_back(RetOp);
732  }
733  DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
734}
735
736void SelectionDAGLowering::visitBr(BranchInst &I) {
737  // Update machine-CFG edges.
738  MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
739  CurMBB->addSuccessor(Succ0MBB);
740
741  // Figure out which block is immediately after the current one.
742  MachineBasicBlock *NextBlock = 0;
743  MachineFunction::iterator BBI = CurMBB;
744  if (++BBI != CurMBB->getParent()->end())
745    NextBlock = BBI;
746
747  if (I.isUnconditional()) {
748    // If this is not a fall-through branch, emit the branch.
749    if (Succ0MBB != NextBlock)
750      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
751                              DAG.getBasicBlock(Succ0MBB)));
752  } else {
753    MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
754    CurMBB->addSuccessor(Succ1MBB);
755
756    SDOperand Cond = getValue(I.getCondition());
757    if (Succ1MBB == NextBlock) {
758      // If the condition is false, fall through.  This means we should branch
759      // if the condition is true to Succ #0.
760      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
761                              Cond, DAG.getBasicBlock(Succ0MBB)));
762    } else if (Succ0MBB == NextBlock) {
763      // If the condition is true, fall through.  This means we should branch if
764      // the condition is false to Succ #1.  Invert the condition first.
765      SDOperand True = DAG.getConstant(1, Cond.getValueType());
766      Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
767      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
768                              Cond, DAG.getBasicBlock(Succ1MBB)));
769    } else {
770      std::vector<SDOperand> Ops;
771      Ops.push_back(getRoot());
772      // If the false case is the current basic block, then this is a self
773      // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
774      // adds an extra instruction in the loop.  Instead, invert the
775      // condition and emit "Loop: ... br!cond Loop; br Out.
776      if (CurMBB == Succ1MBB) {
777        std::swap(Succ0MBB, Succ1MBB);
778        SDOperand True = DAG.getConstant(1, Cond.getValueType());
779        Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
780      }
781      SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
782                                   DAG.getBasicBlock(Succ0MBB));
783      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True,
784                              DAG.getBasicBlock(Succ1MBB)));
785    }
786  }
787}
788
789/// visitSwitchCase - Emits the necessary code to represent a single node in
790/// the binary search tree resulting from lowering a switch instruction.
791void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
792  SDOperand SwitchOp = getValue(CB.SwitchV);
793  SDOperand CaseOp = getValue(CB.CaseC);
794  SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
795
796  // Set NextBlock to be the MBB immediately after the current one, if any.
797  // This is used to avoid emitting unnecessary branches to the next block.
798  MachineBasicBlock *NextBlock = 0;
799  MachineFunction::iterator BBI = CurMBB;
800  if (++BBI != CurMBB->getParent()->end())
801    NextBlock = BBI;
802
803  // If the lhs block is the next block, invert the condition so that we can
804  // fall through to the lhs instead of the rhs block.
805  if (CB.LHSBB == NextBlock) {
806    std::swap(CB.LHSBB, CB.RHSBB);
807    SDOperand True = DAG.getConstant(1, Cond.getValueType());
808    Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
809  }
810  SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
811                                 DAG.getBasicBlock(CB.LHSBB));
812  if (CB.RHSBB == NextBlock)
813    DAG.setRoot(BrCond);
814  else
815    DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
816                            DAG.getBasicBlock(CB.RHSBB)));
817  // Update successor info
818  CurMBB->addSuccessor(CB.LHSBB);
819  CurMBB->addSuccessor(CB.RHSBB);
820}
821
822/// visitSwitchCase - Emits the necessary code to represent a single node in
823/// the binary search tree resulting from lowering a switch instruction.
824void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
825  // FIXME: Need to emit different code for PIC vs. Non-PIC, specifically,
826  // we need to add the address of the jump table to the value loaded, since
827  // the entries in the jump table will be differences rather than absolute
828  // addresses.
829
830  // Emit the code for the jump table
831  MVT::ValueType PTy = TLI.getPointerTy();
832  unsigned PTyBytes = MVT::getSizeInBits(PTy)/8;
833  SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
834  SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
835                              DAG.getConstant(PTyBytes, PTy));
836  SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, DAG.getJumpTable(JT.JTI,PTy));
837  SDOperand LD  = DAG.getLoad(PTy, Copy.getValue(1), ADD, DAG.getSrcValue(0));
838  DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
839
840  // Update successor info
841  for (std::set<MachineBasicBlock*>::iterator ii = JT.SuccMBBs.begin(),
842       ee = JT.SuccMBBs.end(); ii != ee; ++ii)
843    JT.MBB->addSuccessor(*ii);
844}
845
846void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
847  // Figure out which block is immediately after the current one.
848  MachineBasicBlock *NextBlock = 0;
849  MachineFunction::iterator BBI = CurMBB;
850  if (++BBI != CurMBB->getParent()->end())
851    NextBlock = BBI;
852
853  // If there is only the default destination, branch to it if it is not the
854  // next basic block.  Otherwise, just fall through.
855  if (I.getNumOperands() == 2) {
856    // Update machine-CFG edges.
857    MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
858    // If this is not a fall-through branch, emit the branch.
859    if (DefaultMBB != NextBlock)
860      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
861                              DAG.getBasicBlock(DefaultMBB)));
862    return;
863  }
864
865  // If there are any non-default case statements, create a vector of Cases
866  // representing each one, and sort the vector so that we can efficiently
867  // create a binary search tree from them.
868  std::vector<Case> Cases;
869  for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
870    MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
871    Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
872  }
873  std::sort(Cases.begin(), Cases.end(), CaseCmp());
874
875  // Get the Value to be switched on and default basic blocks, which will be
876  // inserted into CaseBlock records, representing basic blocks in the binary
877  // search tree.
878  Value *SV = I.getOperand(0);
879  MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
880
881  // Get the MachineFunction which holds the current MBB.  This is used during
882  // emission of jump tables, and when inserting any additional MBBs necessary
883  // to represent the switch.
884  MachineFunction *CurMF = CurMBB->getParent();
885  const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
886  Reloc::Model Relocs = TLI.getTargetMachine().getRelocationModel();
887
888  // If the switch has more than 3 blocks, and is 100% dense, then emit a jump
889  // table rather than lowering the switch to a binary tree of conditional
890  // branches.
891  // FIXME: Make this work with 64 bit targets someday, possibly by always
892  // doing differences there so that entries stay 32 bits.
893  // FIXME: Make this work with PIC code
894  if (0 && TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
895      TLI.getPointerTy() == MVT::i32 &&
896      (Relocs == Reloc::Static || Relocs == Reloc::DynamicNoPIC) &&
897      Cases.size() > 3) {
898    uint64_t First = cast<ConstantIntegral>(Cases.front().first)->getRawValue();
899    uint64_t Last  = cast<ConstantIntegral>(Cases.back().first)->getRawValue();
900
901    // Determine density
902    // FIXME: support sub-100% density
903    if (((Last - First) + 1ULL) == (uint64_t)Cases.size()) {
904      // Create a new basic block to hold the code for loading the address
905      // of the jump table, and jumping to it.  Update successor information;
906      // we will either branch to the default case for the switch, or the jump
907      // table.
908      MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
909      CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
910      CurMBB->addSuccessor(Default);
911      CurMBB->addSuccessor(JumpTableBB);
912
913      // Subtract the lowest switch case value from the value being switched on
914      // and conditional branch to default mbb if the result is greater than the
915      // difference between smallest and largest cases.
916      SDOperand SwitchOp = getValue(SV);
917      MVT::ValueType VT = SwitchOp.getValueType();
918      SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
919                                  DAG.getConstant(First, VT));
920
921      // The SDNode we just created, which holds the value being switched on
922      // minus the the smallest case value, needs to be copied to a virtual
923      // register so it can be used as an index into the jump table in a
924      // subsequent basic block.  This value may be smaller or larger than the
925      // target's pointer type, and therefore require extension or truncating.
926      if (VT > TLI.getPointerTy())
927        SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
928      else
929        SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
930      unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
931      SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
932
933      // Emit the range check for the jump table, and branch to the default
934      // block for the switch statement if the value being switched on exceeds
935      // the largest case in the switch.
936      SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
937                                   DAG.getConstant(Last-First,VT), ISD::SETUGT);
938      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
939                              DAG.getBasicBlock(Default)));
940
941      // Build a sorted vector of destination BBs, corresponding to each target
942      // of the switch.
943      // FIXME: need to insert DefaultMBB for each "hole" in the jump table,
944      // when we support jump tables with < 100% density.
945      std::set<MachineBasicBlock*> UniqueBBs;
946      std::vector<MachineBasicBlock*> DestBBs;
947      for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++ii) {
948        DestBBs.push_back(ii->second);
949        UniqueBBs.insert(ii->second);
950      }
951      unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
952
953      // Set the jump table information so that we can codegen it as a second
954      // MachineBasicBlock
955      JT.Reg = JumpTableReg;
956      JT.JTI = JTI;
957      JT.MBB = JumpTableBB;
958      JT.SuccMBBs = UniqueBBs;
959      return;
960    }
961  }
962
963  // Push the initial CaseRec onto the worklist
964  std::vector<CaseRec> CaseVec;
965  CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
966
967  while (!CaseVec.empty()) {
968    // Grab a record representing a case range to process off the worklist
969    CaseRec CR = CaseVec.back();
970    CaseVec.pop_back();
971
972    // Size is the number of Cases represented by this range.  If Size is 1,
973    // then we are processing a leaf of the binary search tree.  Otherwise,
974    // we need to pick a pivot, and push left and right ranges onto the
975    // worklist.
976    unsigned Size = CR.Range.second - CR.Range.first;
977
978    if (Size == 1) {
979      // Create a CaseBlock record representing a conditional branch to
980      // the Case's target mbb if the value being switched on SV is equal
981      // to C.  Otherwise, branch to default.
982      Constant *C = CR.Range.first->first;
983      MachineBasicBlock *Target = CR.Range.first->second;
984      SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
985                                     CR.CaseBB);
986      // If the MBB representing the leaf node is the current MBB, then just
987      // call visitSwitchCase to emit the code into the current block.
988      // Otherwise, push the CaseBlock onto the vector to be later processed
989      // by SDISel, and insert the node's MBB before the next MBB.
990      if (CR.CaseBB == CurMBB)
991        visitSwitchCase(CB);
992      else {
993        SwitchCases.push_back(CB);
994        CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
995      }
996    } else {
997      // split case range at pivot
998      CaseItr Pivot = CR.Range.first + (Size / 2);
999      CaseRange LHSR(CR.Range.first, Pivot);
1000      CaseRange RHSR(Pivot, CR.Range.second);
1001      Constant *C = Pivot->first;
1002      MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
1003      // We know that we branch to the LHS if the Value being switched on is
1004      // less than the Pivot value, C.  We use this to optimize our binary
1005      // tree a bit, by recognizing that if SV is greater than or equal to the
1006      // LHS's Case Value, and that Case Value is exactly one less than the
1007      // Pivot's Value, then we can branch directly to the LHS's Target,
1008      // rather than creating a leaf node for it.
1009      if ((LHSR.second - LHSR.first) == 1 &&
1010          LHSR.first->first == CR.GE &&
1011          cast<ConstantIntegral>(C)->getRawValue() ==
1012          (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
1013        LHSBB = LHSR.first->second;
1014      } else {
1015        LHSBB = new MachineBasicBlock(LLVMBB);
1016        CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
1017      }
1018      // Similar to the optimization above, if the Value being switched on is
1019      // known to be less than the Constant CR.LT, and the current Case Value
1020      // is CR.LT - 1, then we can branch directly to the target block for
1021      // the current Case Value, rather than emitting a RHS leaf node for it.
1022      if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1023          cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
1024          (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
1025        RHSBB = RHSR.first->second;
1026      } else {
1027        RHSBB = new MachineBasicBlock(LLVMBB);
1028        CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
1029      }
1030      // Create a CaseBlock record representing a conditional branch to
1031      // the LHS node if the value being switched on SV is less than C.
1032      // Otherwise, branch to LHS.
1033      ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1034      SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
1035      if (CR.CaseBB == CurMBB)
1036        visitSwitchCase(CB);
1037      else {
1038        SwitchCases.push_back(CB);
1039        CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
1040      }
1041    }
1042  }
1043}
1044
1045void SelectionDAGLowering::visitSub(User &I) {
1046  // -0.0 - X --> fneg
1047  if (I.getType()->isFloatingPoint()) {
1048    if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1049      if (CFP->isExactlyValue(-0.0)) {
1050        SDOperand Op2 = getValue(I.getOperand(1));
1051        setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1052        return;
1053      }
1054  }
1055  visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
1056}
1057
1058void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp,
1059                                       unsigned VecOp) {
1060  const Type *Ty = I.getType();
1061  SDOperand Op1 = getValue(I.getOperand(0));
1062  SDOperand Op2 = getValue(I.getOperand(1));
1063
1064  if (Ty->isIntegral()) {
1065    setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1066  } else if (Ty->isFloatingPoint()) {
1067    setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1068  } else {
1069    const PackedType *PTy = cast<PackedType>(Ty);
1070    SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1071    SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1072    setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1073  }
1074}
1075
1076void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1077  SDOperand Op1 = getValue(I.getOperand(0));
1078  SDOperand Op2 = getValue(I.getOperand(1));
1079
1080  Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1081
1082  setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1083}
1084
1085void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
1086                                      ISD::CondCode UnsignedOpcode) {
1087  SDOperand Op1 = getValue(I.getOperand(0));
1088  SDOperand Op2 = getValue(I.getOperand(1));
1089  ISD::CondCode Opcode = SignedOpcode;
1090  if (I.getOperand(0)->getType()->isUnsigned())
1091    Opcode = UnsignedOpcode;
1092  setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1093}
1094
1095void SelectionDAGLowering::visitSelect(User &I) {
1096  SDOperand Cond     = getValue(I.getOperand(0));
1097  SDOperand TrueVal  = getValue(I.getOperand(1));
1098  SDOperand FalseVal = getValue(I.getOperand(2));
1099  if (!isa<PackedType>(I.getType())) {
1100    setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1101                             TrueVal, FalseVal));
1102  } else {
1103    setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1104                             *(TrueVal.Val->op_end()-2),
1105                             *(TrueVal.Val->op_end()-1)));
1106  }
1107}
1108
1109void SelectionDAGLowering::visitCast(User &I) {
1110  SDOperand N = getValue(I.getOperand(0));
1111  MVT::ValueType SrcVT = N.getValueType();
1112  MVT::ValueType DestVT = TLI.getValueType(I.getType());
1113
1114  if (DestVT == MVT::Vector) {
1115    // This is a cast to a vector from something else.  This is always a bit
1116    // convert.  Get information about the input vector.
1117    const PackedType *DestTy = cast<PackedType>(I.getType());
1118    MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1119    setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1120                             DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1121                             DAG.getValueType(EltVT)));
1122  } else if (SrcVT == DestVT) {
1123    setValue(&I, N);  // noop cast.
1124  } else if (DestVT == MVT::i1) {
1125    // Cast to bool is a comparison against zero, not truncation to zero.
1126    SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1127                                       DAG.getConstantFP(0.0, N.getValueType());
1128    setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1129  } else if (isInteger(SrcVT)) {
1130    if (isInteger(DestVT)) {        // Int -> Int cast
1131      if (DestVT < SrcVT)   // Truncating cast?
1132        setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1133      else if (I.getOperand(0)->getType()->isSigned())
1134        setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1135      else
1136        setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1137    } else if (isFloatingPoint(DestVT)) {           // Int -> FP cast
1138      if (I.getOperand(0)->getType()->isSigned())
1139        setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1140      else
1141        setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1142    } else {
1143      assert(0 && "Unknown cast!");
1144    }
1145  } else if (isFloatingPoint(SrcVT)) {
1146    if (isFloatingPoint(DestVT)) {  // FP -> FP cast
1147      if (DestVT < SrcVT)   // Rounding cast?
1148        setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1149      else
1150        setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1151    } else if (isInteger(DestVT)) {        // FP -> Int cast.
1152      if (I.getType()->isSigned())
1153        setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1154      else
1155        setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1156    } else {
1157      assert(0 && "Unknown cast!");
1158    }
1159  } else {
1160    assert(SrcVT == MVT::Vector && "Unknown cast!");
1161    assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1162    // This is a cast from a vector to something else.  This is always a bit
1163    // convert.  Get information about the input vector.
1164    setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1165  }
1166}
1167
1168void SelectionDAGLowering::visitInsertElement(User &I) {
1169  SDOperand InVec = getValue(I.getOperand(0));
1170  SDOperand InVal = getValue(I.getOperand(1));
1171  SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1172                                getValue(I.getOperand(2)));
1173
1174  SDOperand Num = *(InVec.Val->op_end()-2);
1175  SDOperand Typ = *(InVec.Val->op_end()-1);
1176  setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1177                           InVec, InVal, InIdx, Num, Typ));
1178}
1179
1180void SelectionDAGLowering::visitExtractElement(User &I) {
1181  SDOperand InVec = getValue(I.getOperand(0));
1182  SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1183                                getValue(I.getOperand(1)));
1184  SDOperand Typ = *(InVec.Val->op_end()-1);
1185  setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1186                           TLI.getValueType(I.getType()), InVec, InIdx));
1187}
1188
1189void SelectionDAGLowering::visitShuffleVector(User &I) {
1190  SDOperand V1   = getValue(I.getOperand(0));
1191  SDOperand V2   = getValue(I.getOperand(1));
1192  SDOperand Mask = getValue(I.getOperand(2));
1193
1194  SDOperand Num = *(V1.Val->op_end()-2);
1195  SDOperand Typ = *(V2.Val->op_end()-1);
1196  setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1197                           V1, V2, Mask, Num, Typ));
1198}
1199
1200
1201void SelectionDAGLowering::visitGetElementPtr(User &I) {
1202  SDOperand N = getValue(I.getOperand(0));
1203  const Type *Ty = I.getOperand(0)->getType();
1204  const Type *UIntPtrTy = TD.getIntPtrType();
1205
1206  for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1207       OI != E; ++OI) {
1208    Value *Idx = *OI;
1209    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1210      unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1211      if (Field) {
1212        // N = N + Offset
1213        uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
1214        N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1215                        getIntPtrConstant(Offset));
1216      }
1217      Ty = StTy->getElementType(Field);
1218    } else {
1219      Ty = cast<SequentialType>(Ty)->getElementType();
1220
1221      // If this is a constant subscript, handle it quickly.
1222      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1223        if (CI->getRawValue() == 0) continue;
1224
1225        uint64_t Offs;
1226        if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1227          Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1228        else
1229          Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1230        N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1231        continue;
1232      }
1233
1234      // N = N + Idx * ElementSize;
1235      uint64_t ElementSize = TD.getTypeSize(Ty);
1236      SDOperand IdxN = getValue(Idx);
1237
1238      // If the index is smaller or larger than intptr_t, truncate or extend
1239      // it.
1240      if (IdxN.getValueType() < N.getValueType()) {
1241        if (Idx->getType()->isSigned())
1242          IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1243        else
1244          IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1245      } else if (IdxN.getValueType() > N.getValueType())
1246        IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1247
1248      // If this is a multiply by a power of two, turn it into a shl
1249      // immediately.  This is a very common case.
1250      if (isPowerOf2_64(ElementSize)) {
1251        unsigned Amt = Log2_64(ElementSize);
1252        IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1253                           DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1254        N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1255        continue;
1256      }
1257
1258      SDOperand Scale = getIntPtrConstant(ElementSize);
1259      IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1260      N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1261    }
1262  }
1263  setValue(&I, N);
1264}
1265
1266void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1267  // If this is a fixed sized alloca in the entry block of the function,
1268  // allocate it statically on the stack.
1269  if (FuncInfo.StaticAllocaMap.count(&I))
1270    return;   // getValue will auto-populate this.
1271
1272  const Type *Ty = I.getAllocatedType();
1273  uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1274  unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
1275                            I.getAlignment());
1276
1277  SDOperand AllocSize = getValue(I.getArraySize());
1278  MVT::ValueType IntPtr = TLI.getPointerTy();
1279  if (IntPtr < AllocSize.getValueType())
1280    AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1281  else if (IntPtr > AllocSize.getValueType())
1282    AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1283
1284  AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1285                          getIntPtrConstant(TySize));
1286
1287  // Handle alignment.  If the requested alignment is less than or equal to the
1288  // stack alignment, ignore it and round the size of the allocation up to the
1289  // stack alignment size.  If the size is greater than the stack alignment, we
1290  // note this in the DYNAMIC_STACKALLOC node.
1291  unsigned StackAlign =
1292    TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1293  if (Align <= StackAlign) {
1294    Align = 0;
1295    // Add SA-1 to the size.
1296    AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1297                            getIntPtrConstant(StackAlign-1));
1298    // Mask out the low bits for alignment purposes.
1299    AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1300                            getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1301  }
1302
1303  std::vector<MVT::ValueType> VTs;
1304  VTs.push_back(AllocSize.getValueType());
1305  VTs.push_back(MVT::Other);
1306  std::vector<SDOperand> Ops;
1307  Ops.push_back(getRoot());
1308  Ops.push_back(AllocSize);
1309  Ops.push_back(getIntPtrConstant(Align));
1310  SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
1311  DAG.setRoot(setValue(&I, DSA).getValue(1));
1312
1313  // Inform the Frame Information that we have just allocated a variable-sized
1314  // object.
1315  CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1316}
1317
1318void SelectionDAGLowering::visitLoad(LoadInst &I) {
1319  SDOperand Ptr = getValue(I.getOperand(0));
1320
1321  SDOperand Root;
1322  if (I.isVolatile())
1323    Root = getRoot();
1324  else {
1325    // Do not serialize non-volatile loads against each other.
1326    Root = DAG.getRoot();
1327  }
1328
1329  setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1330                           Root, I.isVolatile()));
1331}
1332
1333SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1334                                            SDOperand SrcValue, SDOperand Root,
1335                                            bool isVolatile) {
1336  SDOperand L;
1337  if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1338    MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1339    L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
1340  } else {
1341    L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
1342  }
1343
1344  if (isVolatile)
1345    DAG.setRoot(L.getValue(1));
1346  else
1347    PendingLoads.push_back(L.getValue(1));
1348
1349  return L;
1350}
1351
1352
1353void SelectionDAGLowering::visitStore(StoreInst &I) {
1354  Value *SrcV = I.getOperand(0);
1355  SDOperand Src = getValue(SrcV);
1356  SDOperand Ptr = getValue(I.getOperand(1));
1357  DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1358                          DAG.getSrcValue(I.getOperand(1))));
1359}
1360
1361/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1362/// access memory and has no other side effects at all.
1363static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1364#define GET_NO_MEMORY_INTRINSICS
1365#include "llvm/Intrinsics.gen"
1366#undef GET_NO_MEMORY_INTRINSICS
1367  return false;
1368}
1369
1370// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1371// have any side-effects or if it only reads memory.
1372static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1373#define GET_SIDE_EFFECT_INFO
1374#include "llvm/Intrinsics.gen"
1375#undef GET_SIDE_EFFECT_INFO
1376  return false;
1377}
1378
1379/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1380/// node.
1381void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1382                                                unsigned Intrinsic) {
1383  bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1384  bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1385
1386  // Build the operand list.
1387  std::vector<SDOperand> Ops;
1388  if (HasChain) {  // If this intrinsic has side-effects, chainify it.
1389    if (OnlyLoad) {
1390      // We don't need to serialize loads against other loads.
1391      Ops.push_back(DAG.getRoot());
1392    } else {
1393      Ops.push_back(getRoot());
1394    }
1395  }
1396
1397  // Add the intrinsic ID as an integer operand.
1398  Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1399
1400  // Add all operands of the call to the operand list.
1401  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1402    SDOperand Op = getValue(I.getOperand(i));
1403
1404    // If this is a vector type, force it to the right packed type.
1405    if (Op.getValueType() == MVT::Vector) {
1406      const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1407      MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1408
1409      MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1410      assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1411      Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1412    }
1413
1414    assert(TLI.isTypeLegal(Op.getValueType()) &&
1415           "Intrinsic uses a non-legal type?");
1416    Ops.push_back(Op);
1417  }
1418
1419  std::vector<MVT::ValueType> VTs;
1420  if (I.getType() != Type::VoidTy) {
1421    MVT::ValueType VT = TLI.getValueType(I.getType());
1422    if (VT == MVT::Vector) {
1423      const PackedType *DestTy = cast<PackedType>(I.getType());
1424      MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1425
1426      VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1427      assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1428    }
1429
1430    assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1431    VTs.push_back(VT);
1432  }
1433  if (HasChain)
1434    VTs.push_back(MVT::Other);
1435
1436  // Create the node.
1437  SDOperand Result;
1438  if (!HasChain)
1439    Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTs, Ops);
1440  else if (I.getType() != Type::VoidTy)
1441    Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTs, Ops);
1442  else
1443    Result = DAG.getNode(ISD::INTRINSIC_VOID, VTs, Ops);
1444
1445  if (HasChain) {
1446    SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1447    if (OnlyLoad)
1448      PendingLoads.push_back(Chain);
1449    else
1450      DAG.setRoot(Chain);
1451  }
1452  if (I.getType() != Type::VoidTy) {
1453    if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1454      MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1455      Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1456                           DAG.getConstant(PTy->getNumElements(), MVT::i32),
1457                           DAG.getValueType(EVT));
1458    }
1459    setValue(&I, Result);
1460  }
1461}
1462
1463/// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
1464/// we want to emit this as a call to a named external function, return the name
1465/// otherwise lower it and return null.
1466const char *
1467SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1468  switch (Intrinsic) {
1469  default:
1470    // By default, turn this into a target intrinsic node.
1471    visitTargetIntrinsic(I, Intrinsic);
1472    return 0;
1473  case Intrinsic::vastart:  visitVAStart(I); return 0;
1474  case Intrinsic::vaend:    visitVAEnd(I); return 0;
1475  case Intrinsic::vacopy:   visitVACopy(I); return 0;
1476  case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1477  case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
1478  case Intrinsic::setjmp:
1479    return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1480    break;
1481  case Intrinsic::longjmp:
1482    return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1483    break;
1484  case Intrinsic::memcpy_i32:
1485  case Intrinsic::memcpy_i64:
1486    visitMemIntrinsic(I, ISD::MEMCPY);
1487    return 0;
1488  case Intrinsic::memset_i32:
1489  case Intrinsic::memset_i64:
1490    visitMemIntrinsic(I, ISD::MEMSET);
1491    return 0;
1492  case Intrinsic::memmove_i32:
1493  case Intrinsic::memmove_i64:
1494    visitMemIntrinsic(I, ISD::MEMMOVE);
1495    return 0;
1496
1497  case Intrinsic::dbg_stoppoint: {
1498    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1499    DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1500    if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1501      std::vector<SDOperand> Ops;
1502
1503      Ops.push_back(getRoot());
1504      Ops.push_back(getValue(SPI.getLineValue()));
1505      Ops.push_back(getValue(SPI.getColumnValue()));
1506
1507      DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1508      assert(DD && "Not a debug information descriptor");
1509      CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1510
1511      Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1512      Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1513
1514      DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1515    }
1516
1517    return 0;
1518  }
1519  case Intrinsic::dbg_region_start: {
1520    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1521    DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1522    if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1523      std::vector<SDOperand> Ops;
1524
1525      unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1526
1527      Ops.push_back(getRoot());
1528      Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1529
1530      DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1531    }
1532
1533    return 0;
1534  }
1535  case Intrinsic::dbg_region_end: {
1536    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1537    DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1538    if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1539      std::vector<SDOperand> Ops;
1540
1541      unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1542
1543      Ops.push_back(getRoot());
1544      Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1545
1546      DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1547    }
1548
1549    return 0;
1550  }
1551  case Intrinsic::dbg_func_start: {
1552    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1553    DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1554    if (DebugInfo && FSI.getSubprogram() &&
1555        DebugInfo->Verify(FSI.getSubprogram())) {
1556      std::vector<SDOperand> Ops;
1557
1558      unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1559
1560      Ops.push_back(getRoot());
1561      Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1562
1563      DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1564    }
1565
1566    return 0;
1567  }
1568  case Intrinsic::dbg_declare: {
1569    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1570    DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1571    if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1572      std::vector<SDOperand> Ops;
1573
1574      SDOperand AddressOp  = getValue(DI.getAddress());
1575      if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
1576        DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1577      }
1578    }
1579
1580    return 0;
1581  }
1582
1583  case Intrinsic::isunordered_f32:
1584  case Intrinsic::isunordered_f64:
1585    setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1586                              getValue(I.getOperand(2)), ISD::SETUO));
1587    return 0;
1588
1589  case Intrinsic::sqrt_f32:
1590  case Intrinsic::sqrt_f64:
1591    setValue(&I, DAG.getNode(ISD::FSQRT,
1592                             getValue(I.getOperand(1)).getValueType(),
1593                             getValue(I.getOperand(1))));
1594    return 0;
1595  case Intrinsic::pcmarker: {
1596    SDOperand Tmp = getValue(I.getOperand(1));
1597    DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1598    return 0;
1599  }
1600  case Intrinsic::readcyclecounter: {
1601    std::vector<MVT::ValueType> VTs;
1602    VTs.push_back(MVT::i64);
1603    VTs.push_back(MVT::Other);
1604    std::vector<SDOperand> Ops;
1605    Ops.push_back(getRoot());
1606    SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1607    setValue(&I, Tmp);
1608    DAG.setRoot(Tmp.getValue(1));
1609    return 0;
1610  }
1611  case Intrinsic::bswap_i16:
1612  case Intrinsic::bswap_i32:
1613  case Intrinsic::bswap_i64:
1614    setValue(&I, DAG.getNode(ISD::BSWAP,
1615                             getValue(I.getOperand(1)).getValueType(),
1616                             getValue(I.getOperand(1))));
1617    return 0;
1618  case Intrinsic::cttz_i8:
1619  case Intrinsic::cttz_i16:
1620  case Intrinsic::cttz_i32:
1621  case Intrinsic::cttz_i64:
1622    setValue(&I, DAG.getNode(ISD::CTTZ,
1623                             getValue(I.getOperand(1)).getValueType(),
1624                             getValue(I.getOperand(1))));
1625    return 0;
1626  case Intrinsic::ctlz_i8:
1627  case Intrinsic::ctlz_i16:
1628  case Intrinsic::ctlz_i32:
1629  case Intrinsic::ctlz_i64:
1630    setValue(&I, DAG.getNode(ISD::CTLZ,
1631                             getValue(I.getOperand(1)).getValueType(),
1632                             getValue(I.getOperand(1))));
1633    return 0;
1634  case Intrinsic::ctpop_i8:
1635  case Intrinsic::ctpop_i16:
1636  case Intrinsic::ctpop_i32:
1637  case Intrinsic::ctpop_i64:
1638    setValue(&I, DAG.getNode(ISD::CTPOP,
1639                             getValue(I.getOperand(1)).getValueType(),
1640                             getValue(I.getOperand(1))));
1641    return 0;
1642  case Intrinsic::stacksave: {
1643    std::vector<MVT::ValueType> VTs;
1644    VTs.push_back(TLI.getPointerTy());
1645    VTs.push_back(MVT::Other);
1646    std::vector<SDOperand> Ops;
1647    Ops.push_back(getRoot());
1648    SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1649    setValue(&I, Tmp);
1650    DAG.setRoot(Tmp.getValue(1));
1651    return 0;
1652  }
1653  case Intrinsic::stackrestore: {
1654    SDOperand Tmp = getValue(I.getOperand(1));
1655    DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1656    return 0;
1657  }
1658  case Intrinsic::prefetch:
1659    // FIXME: Currently discarding prefetches.
1660    return 0;
1661  }
1662}
1663
1664
1665void SelectionDAGLowering::visitCall(CallInst &I) {
1666  const char *RenameFn = 0;
1667  if (Function *F = I.getCalledFunction()) {
1668    if (F->isExternal())
1669      if (unsigned IID = F->getIntrinsicID()) {
1670        RenameFn = visitIntrinsicCall(I, IID);
1671        if (!RenameFn)
1672          return;
1673      } else {    // Not an LLVM intrinsic.
1674        const std::string &Name = F->getName();
1675        if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1676          if (I.getNumOperands() == 3 &&   // Basic sanity checks.
1677              I.getOperand(1)->getType()->isFloatingPoint() &&
1678              I.getType() == I.getOperand(1)->getType() &&
1679              I.getType() == I.getOperand(2)->getType()) {
1680            SDOperand LHS = getValue(I.getOperand(1));
1681            SDOperand RHS = getValue(I.getOperand(2));
1682            setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1683                                     LHS, RHS));
1684            return;
1685          }
1686        } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1687          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1688              I.getOperand(1)->getType()->isFloatingPoint() &&
1689              I.getType() == I.getOperand(1)->getType()) {
1690            SDOperand Tmp = getValue(I.getOperand(1));
1691            setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1692            return;
1693          }
1694        } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1695          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1696              I.getOperand(1)->getType()->isFloatingPoint() &&
1697              I.getType() == I.getOperand(1)->getType()) {
1698            SDOperand Tmp = getValue(I.getOperand(1));
1699            setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1700            return;
1701          }
1702        } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1703          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1704              I.getOperand(1)->getType()->isFloatingPoint() &&
1705              I.getType() == I.getOperand(1)->getType()) {
1706            SDOperand Tmp = getValue(I.getOperand(1));
1707            setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1708            return;
1709          }
1710        }
1711      }
1712  } else if (isa<InlineAsm>(I.getOperand(0))) {
1713    visitInlineAsm(I);
1714    return;
1715  }
1716
1717  SDOperand Callee;
1718  if (!RenameFn)
1719    Callee = getValue(I.getOperand(0));
1720  else
1721    Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1722  std::vector<std::pair<SDOperand, const Type*> > Args;
1723  Args.reserve(I.getNumOperands());
1724  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1725    Value *Arg = I.getOperand(i);
1726    SDOperand ArgNode = getValue(Arg);
1727    Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1728  }
1729
1730  const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1731  const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1732
1733  std::pair<SDOperand,SDOperand> Result =
1734    TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1735                    I.isTailCall(), Callee, Args, DAG);
1736  if (I.getType() != Type::VoidTy)
1737    setValue(&I, Result.first);
1738  DAG.setRoot(Result.second);
1739}
1740
1741SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1742                                        SDOperand &Chain, SDOperand &Flag)const{
1743  SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1744  Chain = Val.getValue(1);
1745  Flag  = Val.getValue(2);
1746
1747  // If the result was expanded, copy from the top part.
1748  if (Regs.size() > 1) {
1749    assert(Regs.size() == 2 &&
1750           "Cannot expand to more than 2 elts yet!");
1751    SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1752    Chain = Val.getValue(1);
1753    Flag  = Val.getValue(2);
1754    if (DAG.getTargetLoweringInfo().isLittleEndian())
1755      return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1756    else
1757      return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
1758  }
1759
1760  // Otherwise, if the return value was promoted, truncate it to the
1761  // appropriate type.
1762  if (RegVT == ValueVT)
1763    return Val;
1764
1765  if (MVT::isInteger(RegVT))
1766    return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1767  else
1768    return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1769}
1770
1771/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1772/// specified value into the registers specified by this object.  This uses
1773/// Chain/Flag as the input and updates them for the output Chain/Flag.
1774void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1775                                 SDOperand &Chain, SDOperand &Flag) const {
1776  if (Regs.size() == 1) {
1777    // If there is a single register and the types differ, this must be
1778    // a promotion.
1779    if (RegVT != ValueVT) {
1780      if (MVT::isInteger(RegVT))
1781        Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1782      else
1783        Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1784    }
1785    Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1786    Flag = Chain.getValue(1);
1787  } else {
1788    std::vector<unsigned> R(Regs);
1789    if (!DAG.getTargetLoweringInfo().isLittleEndian())
1790      std::reverse(R.begin(), R.end());
1791
1792    for (unsigned i = 0, e = R.size(); i != e; ++i) {
1793      SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
1794                                   DAG.getConstant(i, MVT::i32));
1795      Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
1796      Flag = Chain.getValue(1);
1797    }
1798  }
1799}
1800
1801/// AddInlineAsmOperands - Add this value to the specified inlineasm node
1802/// operand list.  This adds the code marker and includes the number of
1803/// values added into it.
1804void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1805                                        std::vector<SDOperand> &Ops) const {
1806  Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1807  for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1808    Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1809}
1810
1811/// isAllocatableRegister - If the specified register is safe to allocate,
1812/// i.e. it isn't a stack pointer or some other special register, return the
1813/// register class for the register.  Otherwise, return null.
1814static const TargetRegisterClass *
1815isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1816                      const TargetLowering &TLI, const MRegisterInfo *MRI) {
1817  MVT::ValueType FoundVT = MVT::Other;
1818  const TargetRegisterClass *FoundRC = 0;
1819  for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1820       E = MRI->regclass_end(); RCI != E; ++RCI) {
1821    MVT::ValueType ThisVT = MVT::Other;
1822
1823    const TargetRegisterClass *RC = *RCI;
1824    // If none of the the value types for this register class are valid, we
1825    // can't use it.  For example, 64-bit reg classes on 32-bit targets.
1826    for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1827         I != E; ++I) {
1828      if (TLI.isTypeLegal(*I)) {
1829        // If we have already found this register in a different register class,
1830        // choose the one with the largest VT specified.  For example, on
1831        // PowerPC, we favor f64 register classes over f32.
1832        if (FoundVT == MVT::Other ||
1833            MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
1834          ThisVT = *I;
1835          break;
1836        }
1837      }
1838    }
1839
1840    if (ThisVT == MVT::Other) continue;
1841
1842    // NOTE: This isn't ideal.  In particular, this might allocate the
1843    // frame pointer in functions that need it (due to them not being taken
1844    // out of allocation, because a variable sized allocation hasn't been seen
1845    // yet).  This is a slight code pessimization, but should still work.
1846    for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1847         E = RC->allocation_order_end(MF); I != E; ++I)
1848      if (*I == Reg) {
1849        // We found a matching register class.  Keep looking at others in case
1850        // we find one with larger registers that this physreg is also in.
1851        FoundRC = RC;
1852        FoundVT = ThisVT;
1853        break;
1854      }
1855  }
1856  return FoundRC;
1857}
1858
1859RegsForValue SelectionDAGLowering::
1860GetRegistersForValue(const std::string &ConstrCode,
1861                     MVT::ValueType VT, bool isOutReg, bool isInReg,
1862                     std::set<unsigned> &OutputRegs,
1863                     std::set<unsigned> &InputRegs) {
1864  std::pair<unsigned, const TargetRegisterClass*> PhysReg =
1865    TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1866  std::vector<unsigned> Regs;
1867
1868  unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1869  MVT::ValueType RegVT;
1870  MVT::ValueType ValueVT = VT;
1871
1872  if (PhysReg.first) {
1873    if (VT == MVT::Other)
1874      ValueVT = *PhysReg.second->vt_begin();
1875    RegVT = VT;
1876
1877    // This is a explicit reference to a physical register.
1878    Regs.push_back(PhysReg.first);
1879
1880    // If this is an expanded reference, add the rest of the regs to Regs.
1881    if (NumRegs != 1) {
1882      RegVT = *PhysReg.second->vt_begin();
1883      TargetRegisterClass::iterator I = PhysReg.second->begin();
1884      TargetRegisterClass::iterator E = PhysReg.second->end();
1885      for (; *I != PhysReg.first; ++I)
1886        assert(I != E && "Didn't find reg!");
1887
1888      // Already added the first reg.
1889      --NumRegs; ++I;
1890      for (; NumRegs; --NumRegs, ++I) {
1891        assert(I != E && "Ran out of registers to allocate!");
1892        Regs.push_back(*I);
1893      }
1894    }
1895    return RegsForValue(Regs, RegVT, ValueVT);
1896  }
1897
1898  // This is a reference to a register class.  Allocate NumRegs consecutive,
1899  // available, registers from the class.
1900  std::vector<unsigned> RegClassRegs =
1901    TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1902
1903  const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1904  MachineFunction &MF = *CurMBB->getParent();
1905  unsigned NumAllocated = 0;
1906  for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1907    unsigned Reg = RegClassRegs[i];
1908    // See if this register is available.
1909    if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
1910        (isInReg  && InputRegs.count(Reg))) {    // Already used.
1911      // Make sure we find consecutive registers.
1912      NumAllocated = 0;
1913      continue;
1914    }
1915
1916    // Check to see if this register is allocatable (i.e. don't give out the
1917    // stack pointer).
1918    const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1919    if (!RC) {
1920      // Make sure we find consecutive registers.
1921      NumAllocated = 0;
1922      continue;
1923    }
1924
1925    // Okay, this register is good, we can use it.
1926    ++NumAllocated;
1927
1928    // If we allocated enough consecutive
1929    if (NumAllocated == NumRegs) {
1930      unsigned RegStart = (i-NumAllocated)+1;
1931      unsigned RegEnd   = i+1;
1932      // Mark all of the allocated registers used.
1933      for (unsigned i = RegStart; i != RegEnd; ++i) {
1934        unsigned Reg = RegClassRegs[i];
1935        Regs.push_back(Reg);
1936        if (isOutReg) OutputRegs.insert(Reg);    // Mark reg used.
1937        if (isInReg)  InputRegs.insert(Reg);     // Mark reg used.
1938      }
1939
1940      return RegsForValue(Regs, *RC->vt_begin(), VT);
1941    }
1942  }
1943
1944  // Otherwise, we couldn't allocate enough registers for this.
1945  return RegsForValue();
1946}
1947
1948
1949/// visitInlineAsm - Handle a call to an InlineAsm object.
1950///
1951void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1952  InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1953
1954  SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1955                                                 MVT::Other);
1956
1957  // Note, we treat inline asms both with and without side-effects as the same.
1958  // If an inline asm doesn't have side effects and doesn't access memory, we
1959  // could not choose to not chain it.
1960  bool hasSideEffects = IA->hasSideEffects();
1961
1962  std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1963  std::vector<MVT::ValueType> ConstraintVTs;
1964
1965  /// AsmNodeOperands - A list of pairs.  The first element is a register, the
1966  /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1967  /// if it is a def of that register.
1968  std::vector<SDOperand> AsmNodeOperands;
1969  AsmNodeOperands.push_back(SDOperand());  // reserve space for input chain
1970  AsmNodeOperands.push_back(AsmStr);
1971
1972  SDOperand Chain = getRoot();
1973  SDOperand Flag;
1974
1975  // We fully assign registers here at isel time.  This is not optimal, but
1976  // should work.  For register classes that correspond to LLVM classes, we
1977  // could let the LLVM RA do its thing, but we currently don't.  Do a prepass
1978  // over the constraints, collecting fixed registers that we know we can't use.
1979  std::set<unsigned> OutputRegs, InputRegs;
1980  unsigned OpNum = 1;
1981  for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1982    assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1983    std::string &ConstraintCode = Constraints[i].Codes[0];
1984
1985    MVT::ValueType OpVT;
1986
1987    // Compute the value type for each operand and add it to ConstraintVTs.
1988    switch (Constraints[i].Type) {
1989    case InlineAsm::isOutput:
1990      if (!Constraints[i].isIndirectOutput) {
1991        assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1992        OpVT = TLI.getValueType(I.getType());
1993      } else {
1994        const Type *OpTy = I.getOperand(OpNum)->getType();
1995        OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1996        OpNum++;  // Consumes a call operand.
1997      }
1998      break;
1999    case InlineAsm::isInput:
2000      OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2001      OpNum++;  // Consumes a call operand.
2002      break;
2003    case InlineAsm::isClobber:
2004      OpVT = MVT::Other;
2005      break;
2006    }
2007
2008    ConstraintVTs.push_back(OpVT);
2009
2010    if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2011      continue;  // Not assigned a fixed reg.
2012
2013    // Build a list of regs that this operand uses.  This always has a single
2014    // element for promoted/expanded operands.
2015    RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2016                                             false, false,
2017                                             OutputRegs, InputRegs);
2018
2019    switch (Constraints[i].Type) {
2020    case InlineAsm::isOutput:
2021      // We can't assign any other output to this register.
2022      OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2023      // If this is an early-clobber output, it cannot be assigned to the same
2024      // value as the input reg.
2025      if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2026        InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2027      break;
2028    case InlineAsm::isInput:
2029      // We can't assign any other input to this register.
2030      InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2031      break;
2032    case InlineAsm::isClobber:
2033      // Clobbered regs cannot be used as inputs or outputs.
2034      InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2035      OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2036      break;
2037    }
2038  }
2039
2040  // Loop over all of the inputs, copying the operand values into the
2041  // appropriate registers and processing the output regs.
2042  RegsForValue RetValRegs;
2043  std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2044  OpNum = 1;
2045
2046  for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2047    assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2048    std::string &ConstraintCode = Constraints[i].Codes[0];
2049
2050    switch (Constraints[i].Type) {
2051    case InlineAsm::isOutput: {
2052      TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2053      if (ConstraintCode.size() == 1)   // not a physreg name.
2054        CTy = TLI.getConstraintType(ConstraintCode[0]);
2055
2056      if (CTy == TargetLowering::C_Memory) {
2057        // Memory output.
2058        SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2059
2060        // Check that the operand (the address to store to) isn't a float.
2061        if (!MVT::isInteger(InOperandVal.getValueType()))
2062          assert(0 && "MATCH FAIL!");
2063
2064        if (!Constraints[i].isIndirectOutput)
2065          assert(0 && "MATCH FAIL!");
2066
2067        OpNum++;  // Consumes a call operand.
2068
2069        // Extend/truncate to the right pointer type if needed.
2070        MVT::ValueType PtrType = TLI.getPointerTy();
2071        if (InOperandVal.getValueType() < PtrType)
2072          InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2073        else if (InOperandVal.getValueType() > PtrType)
2074          InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2075
2076        // Add information to the INLINEASM node to know about this output.
2077        unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2078        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2079        AsmNodeOperands.push_back(InOperandVal);
2080        break;
2081      }
2082
2083      // Otherwise, this is a register output.
2084      assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2085
2086      // If this is an early-clobber output, or if there is an input
2087      // constraint that matches this, we need to reserve the input register
2088      // so no other inputs allocate to it.
2089      bool UsesInputRegister = false;
2090      if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2091        UsesInputRegister = true;
2092
2093      // Copy the output from the appropriate register.  Find a register that
2094      // we can use.
2095      RegsForValue Regs =
2096        GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2097                             true, UsesInputRegister,
2098                             OutputRegs, InputRegs);
2099      assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
2100
2101      if (!Constraints[i].isIndirectOutput) {
2102        assert(RetValRegs.Regs.empty() &&
2103               "Cannot have multiple output constraints yet!");
2104        assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2105        RetValRegs = Regs;
2106      } else {
2107        IndirectStoresToEmit.push_back(std::make_pair(Regs,
2108                                                      I.getOperand(OpNum)));
2109        OpNum++;  // Consumes a call operand.
2110      }
2111
2112      // Add information to the INLINEASM node to know that this register is
2113      // set.
2114      Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2115      break;
2116    }
2117    case InlineAsm::isInput: {
2118      SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2119      OpNum++;  // Consumes a call operand.
2120
2121      if (isdigit(ConstraintCode[0])) {    // Matching constraint?
2122        // If this is required to match an output register we have already set,
2123        // just use its register.
2124        unsigned OperandNo = atoi(ConstraintCode.c_str());
2125
2126        // Scan until we find the definition we already emitted of this operand.
2127        // When we find it, create a RegsForValue operand.
2128        unsigned CurOp = 2;  // The first operand.
2129        for (; OperandNo; --OperandNo) {
2130          // Advance to the next operand.
2131          unsigned NumOps =
2132            cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2133          assert((NumOps & 7) == 2 /*REGDEF*/ &&
2134                 "Skipped past definitions?");
2135          CurOp += (NumOps>>3)+1;
2136        }
2137
2138        unsigned NumOps =
2139          cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2140        assert((NumOps & 7) == 2 /*REGDEF*/ &&
2141               "Skipped past definitions?");
2142
2143        // Add NumOps>>3 registers to MatchedRegs.
2144        RegsForValue MatchedRegs;
2145        MatchedRegs.ValueVT = InOperandVal.getValueType();
2146        MatchedRegs.RegVT   = AsmNodeOperands[CurOp+1].getValueType();
2147        for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2148          unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2149          MatchedRegs.Regs.push_back(Reg);
2150        }
2151
2152        // Use the produced MatchedRegs object to
2153        MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2154        MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2155        break;
2156      }
2157
2158      TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2159      if (ConstraintCode.size() == 1)   // not a physreg name.
2160        CTy = TLI.getConstraintType(ConstraintCode[0]);
2161
2162      if (CTy == TargetLowering::C_Other) {
2163        if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2164          assert(0 && "MATCH FAIL!");
2165
2166        // Add information to the INLINEASM node to know about this input.
2167        unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2168        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2169        AsmNodeOperands.push_back(InOperandVal);
2170        break;
2171      } else if (CTy == TargetLowering::C_Memory) {
2172        // Memory input.
2173
2174        // Check that the operand isn't a float.
2175        if (!MVT::isInteger(InOperandVal.getValueType()))
2176          assert(0 && "MATCH FAIL!");
2177
2178        // Extend/truncate to the right pointer type if needed.
2179        MVT::ValueType PtrType = TLI.getPointerTy();
2180        if (InOperandVal.getValueType() < PtrType)
2181          InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2182        else if (InOperandVal.getValueType() > PtrType)
2183          InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2184
2185        // Add information to the INLINEASM node to know about this input.
2186        unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2187        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2188        AsmNodeOperands.push_back(InOperandVal);
2189        break;
2190      }
2191
2192      assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2193
2194      // Copy the input into the appropriate registers.
2195      RegsForValue InRegs =
2196        GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2197                             false, true, OutputRegs, InputRegs);
2198      // FIXME: should be match fail.
2199      assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2200
2201      InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2202
2203      InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2204      break;
2205    }
2206    case InlineAsm::isClobber: {
2207      RegsForValue ClobberedRegs =
2208        GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2209                             OutputRegs, InputRegs);
2210      // Add the clobbered value to the operand list, so that the register
2211      // allocator is aware that the physreg got clobbered.
2212      if (!ClobberedRegs.Regs.empty())
2213        ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2214      break;
2215    }
2216    }
2217  }
2218
2219  // Finish up input operands.
2220  AsmNodeOperands[0] = Chain;
2221  if (Flag.Val) AsmNodeOperands.push_back(Flag);
2222
2223  std::vector<MVT::ValueType> VTs;
2224  VTs.push_back(MVT::Other);
2225  VTs.push_back(MVT::Flag);
2226  Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2227  Flag = Chain.getValue(1);
2228
2229  // If this asm returns a register value, copy the result from that register
2230  // and set it as the value of the call.
2231  if (!RetValRegs.Regs.empty())
2232    setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2233
2234  std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2235
2236  // Process indirect outputs, first output all of the flagged copies out of
2237  // physregs.
2238  for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2239    RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2240    Value *Ptr = IndirectStoresToEmit[i].second;
2241    SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2242    StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2243  }
2244
2245  // Emit the non-flagged stores from the physregs.
2246  std::vector<SDOperand> OutChains;
2247  for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2248    OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
2249                                    StoresToEmit[i].first,
2250                                    getValue(StoresToEmit[i].second),
2251                                    DAG.getSrcValue(StoresToEmit[i].second)));
2252  if (!OutChains.empty())
2253    Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2254  DAG.setRoot(Chain);
2255}
2256
2257
2258void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2259  SDOperand Src = getValue(I.getOperand(0));
2260
2261  MVT::ValueType IntPtr = TLI.getPointerTy();
2262
2263  if (IntPtr < Src.getValueType())
2264    Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2265  else if (IntPtr > Src.getValueType())
2266    Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2267
2268  // Scale the source by the type size.
2269  uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
2270  Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2271                    Src, getIntPtrConstant(ElementSize));
2272
2273  std::vector<std::pair<SDOperand, const Type*> > Args;
2274  Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
2275
2276  std::pair<SDOperand,SDOperand> Result =
2277    TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2278                    DAG.getExternalSymbol("malloc", IntPtr),
2279                    Args, DAG);
2280  setValue(&I, Result.first);  // Pointers always fit in registers
2281  DAG.setRoot(Result.second);
2282}
2283
2284void SelectionDAGLowering::visitFree(FreeInst &I) {
2285  std::vector<std::pair<SDOperand, const Type*> > Args;
2286  Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2287                                TLI.getTargetData().getIntPtrType()));
2288  MVT::ValueType IntPtr = TLI.getPointerTy();
2289  std::pair<SDOperand,SDOperand> Result =
2290    TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2291                    DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2292  DAG.setRoot(Result.second);
2293}
2294
2295// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2296// mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
2297// instructions are special in various ways, which require special support to
2298// insert.  The specified MachineInstr is created but not inserted into any
2299// basic blocks, and the scheduler passes ownership of it to this method.
2300MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2301                                                       MachineBasicBlock *MBB) {
2302  std::cerr << "If a target marks an instruction with "
2303               "'usesCustomDAGSchedInserter', it must implement "
2304               "TargetLowering::InsertAtEndOfBasicBlock!\n";
2305  abort();
2306  return 0;
2307}
2308
2309void SelectionDAGLowering::visitVAStart(CallInst &I) {
2310  DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2311                          getValue(I.getOperand(1)),
2312                          DAG.getSrcValue(I.getOperand(1))));
2313}
2314
2315void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2316  SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2317                             getValue(I.getOperand(0)),
2318                             DAG.getSrcValue(I.getOperand(0)));
2319  setValue(&I, V);
2320  DAG.setRoot(V.getValue(1));
2321}
2322
2323void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2324  DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2325                          getValue(I.getOperand(1)),
2326                          DAG.getSrcValue(I.getOperand(1))));
2327}
2328
2329void SelectionDAGLowering::visitVACopy(CallInst &I) {
2330  DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2331                          getValue(I.getOperand(1)),
2332                          getValue(I.getOperand(2)),
2333                          DAG.getSrcValue(I.getOperand(1)),
2334                          DAG.getSrcValue(I.getOperand(2))));
2335}
2336
2337/// TargetLowering::LowerArguments - This is the default LowerArguments
2338/// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
2339/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be removed.
2340std::vector<SDOperand>
2341TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2342  // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2343  std::vector<SDOperand> Ops;
2344  Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2345  Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2346
2347  // Add one result value for each formal argument.
2348  std::vector<MVT::ValueType> RetVals;
2349  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2350    MVT::ValueType VT = getValueType(I->getType());
2351
2352    switch (getTypeAction(VT)) {
2353    default: assert(0 && "Unknown type action!");
2354    case Legal:
2355      RetVals.push_back(VT);
2356      break;
2357    case Promote:
2358      RetVals.push_back(getTypeToTransformTo(VT));
2359      break;
2360    case Expand:
2361      if (VT != MVT::Vector) {
2362        // If this is a large integer, it needs to be broken up into small
2363        // integers.  Figure out what the destination type is and how many small
2364        // integers it turns into.
2365        MVT::ValueType NVT = getTypeToTransformTo(VT);
2366        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2367        for (unsigned i = 0; i != NumVals; ++i)
2368          RetVals.push_back(NVT);
2369      } else {
2370        // Otherwise, this is a vector type.  We only support legal vectors
2371        // right now.
2372        unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2373        const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2374
2375        // Figure out if there is a Packed type corresponding to this Vector
2376        // type.  If so, convert to the packed type.
2377        MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2378        if (TVT != MVT::Other && isTypeLegal(TVT)) {
2379          RetVals.push_back(TVT);
2380        } else {
2381          assert(0 && "Don't support illegal by-val vector arguments yet!");
2382        }
2383      }
2384      break;
2385    }
2386  }
2387
2388  // Create the node.
2389  SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, RetVals, Ops).Val;
2390
2391  // Set up the return result vector.
2392  Ops.clear();
2393  unsigned i = 0;
2394  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2395    MVT::ValueType VT = getValueType(I->getType());
2396
2397    switch (getTypeAction(VT)) {
2398    default: assert(0 && "Unknown type action!");
2399    case Legal:
2400      Ops.push_back(SDOperand(Result, i++));
2401      break;
2402    case Promote: {
2403      SDOperand Op(Result, i++);
2404      if (MVT::isInteger(VT)) {
2405        unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2406                                                     : ISD::AssertZext;
2407        Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2408        Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2409      } else {
2410        assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2411        Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2412      }
2413      Ops.push_back(Op);
2414      break;
2415    }
2416    case Expand:
2417      if (VT != MVT::Vector) {
2418        // If this is a large integer, it needs to be reassembled from small
2419        // integers.  Figure out what the source elt type is and how many small
2420        // integers it is.
2421        MVT::ValueType NVT = getTypeToTransformTo(VT);
2422        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2423        if (NumVals == 2) {
2424          SDOperand Lo = SDOperand(Result, i++);
2425          SDOperand Hi = SDOperand(Result, i++);
2426
2427          if (!isLittleEndian())
2428            std::swap(Lo, Hi);
2429
2430          Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2431        } else {
2432          // Value scalarized into many values.  Unimp for now.
2433          assert(0 && "Cannot expand i64 -> i16 yet!");
2434        }
2435      } else {
2436        // Otherwise, this is a vector type.  We only support legal vectors
2437        // right now.
2438        unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2439        const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2440
2441        // Figure out if there is a Packed type corresponding to this Vector
2442        // type.  If so, convert to the packed type.
2443        MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2444        if (TVT != MVT::Other && isTypeLegal(TVT)) {
2445          Ops.push_back(SDOperand(Result, i++));
2446        } else {
2447          assert(0 && "Don't support illegal by-val vector arguments yet!");
2448        }
2449      }
2450      break;
2451    }
2452  }
2453  return Ops;
2454}
2455
2456// It is always conservatively correct for llvm.returnaddress and
2457// llvm.frameaddress to return 0.
2458std::pair<SDOperand, SDOperand>
2459TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2460                                        unsigned Depth, SelectionDAG &DAG) {
2461  return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
2462}
2463
2464SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
2465  assert(0 && "LowerOperation not implemented for this target!");
2466  abort();
2467  return SDOperand();
2468}
2469
2470SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2471                                                 SelectionDAG &DAG) {
2472  assert(0 && "CustomPromoteOperation not implemented for this target!");
2473  abort();
2474  return SDOperand();
2475}
2476
2477void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2478  unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2479  std::pair<SDOperand,SDOperand> Result =
2480    TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
2481  setValue(&I, Result.first);
2482  DAG.setRoot(Result.second);
2483}
2484
2485/// getMemsetValue - Vectorized representation of the memset value
2486/// operand.
2487static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2488                                SelectionDAG &DAG) {
2489  MVT::ValueType CurVT = VT;
2490  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2491    uint64_t Val   = C->getValue() & 255;
2492    unsigned Shift = 8;
2493    while (CurVT != MVT::i8) {
2494      Val = (Val << Shift) | Val;
2495      Shift <<= 1;
2496      CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2497    }
2498    return DAG.getConstant(Val, VT);
2499  } else {
2500    Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2501    unsigned Shift = 8;
2502    while (CurVT != MVT::i8) {
2503      Value =
2504        DAG.getNode(ISD::OR, VT,
2505                    DAG.getNode(ISD::SHL, VT, Value,
2506                                DAG.getConstant(Shift, MVT::i8)), Value);
2507      Shift <<= 1;
2508      CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2509    }
2510
2511    return Value;
2512  }
2513}
2514
2515/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2516/// used when a memcpy is turned into a memset when the source is a constant
2517/// string ptr.
2518static SDOperand getMemsetStringVal(MVT::ValueType VT,
2519                                    SelectionDAG &DAG, TargetLowering &TLI,
2520                                    std::string &Str, unsigned Offset) {
2521  MVT::ValueType CurVT = VT;
2522  uint64_t Val = 0;
2523  unsigned MSB = getSizeInBits(VT) / 8;
2524  if (TLI.isLittleEndian())
2525    Offset = Offset + MSB - 1;
2526  for (unsigned i = 0; i != MSB; ++i) {
2527    Val = (Val << 8) | Str[Offset];
2528    Offset += TLI.isLittleEndian() ? -1 : 1;
2529  }
2530  return DAG.getConstant(Val, VT);
2531}
2532
2533/// getMemBasePlusOffset - Returns base and offset node for the
2534static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2535                                      SelectionDAG &DAG, TargetLowering &TLI) {
2536  MVT::ValueType VT = Base.getValueType();
2537  return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2538}
2539
2540/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2541/// to replace the memset / memcpy is below the threshold. It also returns the
2542/// types of the sequence of  memory ops to perform memset / memcpy.
2543static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2544                                     unsigned Limit, uint64_t Size,
2545                                     unsigned Align, TargetLowering &TLI) {
2546  MVT::ValueType VT;
2547
2548  if (TLI.allowsUnalignedMemoryAccesses()) {
2549    VT = MVT::i64;
2550  } else {
2551    switch (Align & 7) {
2552    case 0:
2553      VT = MVT::i64;
2554      break;
2555    case 4:
2556      VT = MVT::i32;
2557      break;
2558    case 2:
2559      VT = MVT::i16;
2560      break;
2561    default:
2562      VT = MVT::i8;
2563      break;
2564    }
2565  }
2566
2567  MVT::ValueType LVT = MVT::i64;
2568  while (!TLI.isTypeLegal(LVT))
2569    LVT = (MVT::ValueType)((unsigned)LVT - 1);
2570  assert(MVT::isInteger(LVT));
2571
2572  if (VT > LVT)
2573    VT = LVT;
2574
2575  unsigned NumMemOps = 0;
2576  while (Size != 0) {
2577    unsigned VTSize = getSizeInBits(VT) / 8;
2578    while (VTSize > Size) {
2579      VT = (MVT::ValueType)((unsigned)VT - 1);
2580      VTSize >>= 1;
2581    }
2582    assert(MVT::isInteger(VT));
2583
2584    if (++NumMemOps > Limit)
2585      return false;
2586    MemOps.push_back(VT);
2587    Size -= VTSize;
2588  }
2589
2590  return true;
2591}
2592
2593void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
2594  SDOperand Op1 = getValue(I.getOperand(1));
2595  SDOperand Op2 = getValue(I.getOperand(2));
2596  SDOperand Op3 = getValue(I.getOperand(3));
2597  SDOperand Op4 = getValue(I.getOperand(4));
2598  unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2599  if (Align == 0) Align = 1;
2600
2601  if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2602    std::vector<MVT::ValueType> MemOps;
2603
2604    // Expand memset / memcpy to a series of load / store ops
2605    // if the size operand falls below a certain threshold.
2606    std::vector<SDOperand> OutChains;
2607    switch (Op) {
2608    default: break;  // Do nothing for now.
2609    case ISD::MEMSET: {
2610      if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2611                                   Size->getValue(), Align, TLI)) {
2612        unsigned NumMemOps = MemOps.size();
2613        unsigned Offset = 0;
2614        for (unsigned i = 0; i < NumMemOps; i++) {
2615          MVT::ValueType VT = MemOps[i];
2616          unsigned VTSize = getSizeInBits(VT) / 8;
2617          SDOperand Value = getMemsetValue(Op2, VT, DAG);
2618          SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2619                                        Value,
2620                                    getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2621                                      DAG.getSrcValue(I.getOperand(1), Offset));
2622          OutChains.push_back(Store);
2623          Offset += VTSize;
2624        }
2625      }
2626      break;
2627    }
2628    case ISD::MEMCPY: {
2629      if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2630                                   Size->getValue(), Align, TLI)) {
2631        unsigned NumMemOps = MemOps.size();
2632        unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
2633        GlobalAddressSDNode *G = NULL;
2634        std::string Str;
2635        bool CopyFromStr = false;
2636
2637        if (Op2.getOpcode() == ISD::GlobalAddress)
2638          G = cast<GlobalAddressSDNode>(Op2);
2639        else if (Op2.getOpcode() == ISD::ADD &&
2640                 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2641                 Op2.getOperand(1).getOpcode() == ISD::Constant) {
2642          G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
2643          SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
2644        }
2645        if (G) {
2646          GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2647          if (GV) {
2648            Str = GV->getStringValue(false);
2649            if (!Str.empty()) {
2650              CopyFromStr = true;
2651              SrcOff += SrcDelta;
2652            }
2653          }
2654        }
2655
2656        for (unsigned i = 0; i < NumMemOps; i++) {
2657          MVT::ValueType VT = MemOps[i];
2658          unsigned VTSize = getSizeInBits(VT) / 8;
2659          SDOperand Value, Chain, Store;
2660
2661          if (CopyFromStr) {
2662            Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2663            Chain = getRoot();
2664            Store =
2665              DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2666                          getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2667                          DAG.getSrcValue(I.getOperand(1), DstOff));
2668          } else {
2669            Value = DAG.getLoad(VT, getRoot(),
2670                        getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2671                        DAG.getSrcValue(I.getOperand(2), SrcOff));
2672            Chain = Value.getValue(1);
2673            Store =
2674              DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2675                          getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2676                          DAG.getSrcValue(I.getOperand(1), DstOff));
2677          }
2678          OutChains.push_back(Store);
2679          SrcOff += VTSize;
2680          DstOff += VTSize;
2681        }
2682      }
2683      break;
2684    }
2685    }
2686
2687    if (!OutChains.empty()) {
2688      DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2689      return;
2690    }
2691  }
2692
2693  std::vector<SDOperand> Ops;
2694  Ops.push_back(getRoot());
2695  Ops.push_back(Op1);
2696  Ops.push_back(Op2);
2697  Ops.push_back(Op3);
2698  Ops.push_back(Op4);
2699  DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
2700}
2701
2702//===----------------------------------------------------------------------===//
2703// SelectionDAGISel code
2704//===----------------------------------------------------------------------===//
2705
2706unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2707  return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2708}
2709
2710void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
2711  // FIXME: we only modify the CFG to split critical edges.  This
2712  // updates dom and loop info.
2713}
2714
2715
2716/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2717/// casting to the type of GEPI.
2718static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2719                                   Value *Ptr, Value *PtrOffset) {
2720  if (V) return V;   // Already computed.
2721
2722  BasicBlock::iterator InsertPt;
2723  if (BB == GEPI->getParent()) {
2724    // If insert into the GEP's block, insert right after the GEP.
2725    InsertPt = GEPI;
2726    ++InsertPt;
2727  } else {
2728    // Otherwise, insert at the top of BB, after any PHI nodes
2729    InsertPt = BB->begin();
2730    while (isa<PHINode>(InsertPt)) ++InsertPt;
2731  }
2732
2733  // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2734  // BB so that there is only one value live across basic blocks (the cast
2735  // operand).
2736  if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2737    if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2738      Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2739
2740  // Add the offset, cast it to the right type.
2741  Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2742  Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2743  return V = Ptr;
2744}
2745
2746
2747/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2748/// selection, we want to be a bit careful about some things.  In particular, if
2749/// we have a GEP instruction that is used in a different block than it is
2750/// defined, the addressing expression of the GEP cannot be folded into loads or
2751/// stores that use it.  In this case, decompose the GEP and move constant
2752/// indices into blocks that use it.
2753static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2754                                  const TargetData &TD) {
2755  // If this GEP is only used inside the block it is defined in, there is no
2756  // need to rewrite it.
2757  bool isUsedOutsideDefBB = false;
2758  BasicBlock *DefBB = GEPI->getParent();
2759  for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
2760       UI != E; ++UI) {
2761    if (cast<Instruction>(*UI)->getParent() != DefBB) {
2762      isUsedOutsideDefBB = true;
2763      break;
2764    }
2765  }
2766  if (!isUsedOutsideDefBB) return;
2767
2768  // If this GEP has no non-zero constant indices, there is nothing we can do,
2769  // ignore it.
2770  bool hasConstantIndex = false;
2771  for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2772       E = GEPI->op_end(); OI != E; ++OI) {
2773    if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2774      if (CI->getRawValue()) {
2775        hasConstantIndex = true;
2776        break;
2777      }
2778  }
2779  // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2780  if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
2781
2782  // Otherwise, decompose the GEP instruction into multiplies and adds.  Sum the
2783  // constant offset (which we now know is non-zero) and deal with it later.
2784  uint64_t ConstantOffset = 0;
2785  const Type *UIntPtrTy = TD.getIntPtrType();
2786  Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2787  const Type *Ty = GEPI->getOperand(0)->getType();
2788
2789  for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2790       E = GEPI->op_end(); OI != E; ++OI) {
2791    Value *Idx = *OI;
2792    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2793      unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2794      if (Field)
2795        ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2796      Ty = StTy->getElementType(Field);
2797    } else {
2798      Ty = cast<SequentialType>(Ty)->getElementType();
2799
2800      // Handle constant subscripts.
2801      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2802        if (CI->getRawValue() == 0) continue;
2803
2804        if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2805          ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2806        else
2807          ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2808        continue;
2809      }
2810
2811      // Ptr = Ptr + Idx * ElementSize;
2812
2813      // Cast Idx to UIntPtrTy if needed.
2814      Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2815
2816      uint64_t ElementSize = TD.getTypeSize(Ty);
2817      // Mask off bits that should not be set.
2818      ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2819      Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2820
2821      // Multiply by the element size and add to the base.
2822      Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2823      Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2824    }
2825  }
2826
2827  // Make sure that the offset fits in uintptr_t.
2828  ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2829  Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2830
2831  // Okay, we have now emitted all of the variable index parts to the BB that
2832  // the GEP is defined in.  Loop over all of the using instructions, inserting
2833  // an "add Ptr, ConstantOffset" into each block that uses it and update the
2834  // instruction to use the newly computed value, making GEPI dead.  When the
2835  // user is a load or store instruction address, we emit the add into the user
2836  // block, otherwise we use a canonical version right next to the gep (these
2837  // won't be foldable as addresses, so we might as well share the computation).
2838
2839  std::map<BasicBlock*,Value*> InsertedExprs;
2840  while (!GEPI->use_empty()) {
2841    Instruction *User = cast<Instruction>(GEPI->use_back());
2842
2843    // If this use is not foldable into the addressing mode, use a version
2844    // emitted in the GEP block.
2845    Value *NewVal;
2846    if (!isa<LoadInst>(User) &&
2847        (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2848      NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
2849                                    Ptr, PtrOffset);
2850    } else {
2851      // Otherwise, insert the code in the User's block so it can be folded into
2852      // any users in that block.
2853      NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
2854                                    User->getParent(), GEPI,
2855                                    Ptr, PtrOffset);
2856    }
2857    User->replaceUsesOfWith(GEPI, NewVal);
2858  }
2859
2860  // Finally, the GEP is dead, remove it.
2861  GEPI->eraseFromParent();
2862}
2863
2864bool SelectionDAGISel::runOnFunction(Function &Fn) {
2865  MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2866  RegMap = MF.getSSARegMap();
2867  DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2868
2869  // First, split all critical edges for PHI nodes with incoming values that are
2870  // constants, this way the load of the constant into a vreg will not be placed
2871  // into MBBs that are used some other way.
2872  //
2873  // In this pass we also look for GEP instructions that are used across basic
2874  // blocks and rewrites them to improve basic-block-at-a-time selection.
2875  //
2876  for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2877    PHINode *PN;
2878    BasicBlock::iterator BBI;
2879    for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
2880      for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2881        if (isa<Constant>(PN->getIncomingValue(i)))
2882          SplitCriticalEdge(PN->getIncomingBlock(i), BB);
2883
2884    for (BasicBlock::iterator E = BB->end(); BBI != E; )
2885      if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2886        OptimizeGEPExpression(GEPI, TLI.getTargetData());
2887  }
2888
2889  FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2890
2891  for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2892    SelectBasicBlock(I, MF, FuncInfo);
2893
2894  return true;
2895}
2896
2897
2898SDOperand SelectionDAGISel::
2899CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
2900  SDOperand Op = SDL.getValue(V);
2901  assert((Op.getOpcode() != ISD::CopyFromReg ||
2902          cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
2903         "Copy from a reg to the same reg!");
2904
2905  // If this type is not legal, we must make sure to not create an invalid
2906  // register use.
2907  MVT::ValueType SrcVT = Op.getValueType();
2908  MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2909  SelectionDAG &DAG = SDL.DAG;
2910  if (SrcVT == DestVT) {
2911    return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2912  } else if (SrcVT == MVT::Vector) {
2913    // Handle copies from generic vectors to registers.
2914    MVT::ValueType PTyElementVT, PTyLegalElementVT;
2915    unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
2916                                             PTyElementVT, PTyLegalElementVT);
2917
2918    // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
2919    // MVT::Vector type.
2920    Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
2921                     DAG.getConstant(NE, MVT::i32),
2922                     DAG.getValueType(PTyElementVT));
2923
2924    // Loop over all of the elements of the resultant vector,
2925    // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
2926    // copying them into output registers.
2927    std::vector<SDOperand> OutChains;
2928    SDOperand Root = SDL.getRoot();
2929    for (unsigned i = 0; i != NE; ++i) {
2930      SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
2931                                  Op, DAG.getConstant(i, MVT::i32));
2932      if (PTyElementVT == PTyLegalElementVT) {
2933        // Elements are legal.
2934        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2935      } else if (PTyLegalElementVT > PTyElementVT) {
2936        // Elements are promoted.
2937        if (MVT::isFloatingPoint(PTyLegalElementVT))
2938          Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
2939        else
2940          Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
2941        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
2942      } else {
2943        // Elements are expanded.
2944        // The src value is expanded into multiple registers.
2945        SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2946                                   Elt, DAG.getConstant(0, MVT::i32));
2947        SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
2948                                   Elt, DAG.getConstant(1, MVT::i32));
2949        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
2950        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
2951      }
2952    }
2953    return DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2954  } else if (SrcVT < DestVT) {
2955    // The src value is promoted to the register.
2956    if (MVT::isFloatingPoint(SrcVT))
2957      Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2958    else
2959      Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
2960    return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2961  } else  {
2962    // The src value is expanded into multiple registers.
2963    SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2964                               Op, DAG.getConstant(0, MVT::i32));
2965    SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2966                               Op, DAG.getConstant(1, MVT::i32));
2967    Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2968    return DAG.getCopyToReg(Op, Reg+1, Hi);
2969  }
2970}
2971
2972void SelectionDAGISel::
2973LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2974               std::vector<SDOperand> &UnorderedChains) {
2975  // If this is the entry block, emit arguments.
2976  Function &F = *BB->getParent();
2977  FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
2978  SDOperand OldRoot = SDL.DAG.getRoot();
2979  std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
2980
2981  unsigned a = 0;
2982  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2983       AI != E; ++AI, ++a)
2984    if (!AI->use_empty()) {
2985      SDL.setValue(AI, Args[a]);
2986
2987      // If this argument is live outside of the entry block, insert a copy from
2988      // whereever we got it to the vreg that other BB's will reference it as.
2989      if (FuncInfo.ValueMap.count(AI)) {
2990        SDOperand Copy =
2991          CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2992        UnorderedChains.push_back(Copy);
2993      }
2994    }
2995
2996  // Next, if the function has live ins that need to be copied into vregs,
2997  // emit the copies now, into the top of the block.
2998  MachineFunction &MF = SDL.DAG.getMachineFunction();
2999  if (MF.livein_begin() != MF.livein_end()) {
3000    SSARegMap *RegMap = MF.getSSARegMap();
3001    const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
3002    for (MachineFunction::livein_iterator LI = MF.livein_begin(),
3003         E = MF.livein_end(); LI != E; ++LI)
3004      if (LI->second)
3005        MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
3006                         LI->first, RegMap->getRegClass(LI->second));
3007  }
3008
3009  // Finally, if the target has anything special to do, allow it to do so.
3010  EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3011}
3012
3013
3014void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3015       std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3016                                         FunctionLoweringInfo &FuncInfo) {
3017  SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3018
3019  std::vector<SDOperand> UnorderedChains;
3020
3021  // Lower any arguments needed in this block if this is the entry block.
3022  if (LLVMBB == &LLVMBB->getParent()->front())
3023    LowerArguments(LLVMBB, SDL, UnorderedChains);
3024
3025  BB = FuncInfo.MBBMap[LLVMBB];
3026  SDL.setCurrentBasicBlock(BB);
3027
3028  // Lower all of the non-terminator instructions.
3029  for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3030       I != E; ++I)
3031    SDL.visit(*I);
3032
3033  // Ensure that all instructions which are used outside of their defining
3034  // blocks are available as virtual registers.
3035  for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3036    if (!I->use_empty() && !isa<PHINode>(I)) {
3037      std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3038      if (VMI != FuncInfo.ValueMap.end())
3039        UnorderedChains.push_back(
3040                           CopyValueToVirtualRegister(SDL, I, VMI->second));
3041    }
3042
3043  // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
3044  // ensure constants are generated when needed.  Remember the virtual registers
3045  // that need to be added to the Machine PHI nodes as input.  We cannot just
3046  // directly add them, because expansion might result in multiple MBB's for one
3047  // BB.  As such, the start of the BB might correspond to a different MBB than
3048  // the end.
3049  //
3050
3051  // Emit constants only once even if used by multiple PHI nodes.
3052  std::map<Constant*, unsigned> ConstantsOut;
3053
3054  // Check successor nodes PHI nodes that expect a constant to be available from
3055  // this block.
3056  TerminatorInst *TI = LLVMBB->getTerminator();
3057  for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3058    BasicBlock *SuccBB = TI->getSuccessor(succ);
3059    MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
3060    PHINode *PN;
3061
3062    // At this point we know that there is a 1-1 correspondence between LLVM PHI
3063    // nodes and Machine PHI nodes, but the incoming operands have not been
3064    // emitted yet.
3065    for (BasicBlock::iterator I = SuccBB->begin();
3066         (PN = dyn_cast<PHINode>(I)); ++I)
3067      if (!PN->use_empty()) {
3068        unsigned Reg;
3069        Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3070        if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3071          unsigned &RegOut = ConstantsOut[C];
3072          if (RegOut == 0) {
3073            RegOut = FuncInfo.CreateRegForValue(C);
3074            UnorderedChains.push_back(
3075                             CopyValueToVirtualRegister(SDL, C, RegOut));
3076          }
3077          Reg = RegOut;
3078        } else {
3079          Reg = FuncInfo.ValueMap[PHIOp];
3080          if (Reg == 0) {
3081            assert(isa<AllocaInst>(PHIOp) &&
3082                   FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3083                   "Didn't codegen value into a register!??");
3084            Reg = FuncInfo.CreateRegForValue(PHIOp);
3085            UnorderedChains.push_back(
3086                             CopyValueToVirtualRegister(SDL, PHIOp, Reg));
3087          }
3088        }
3089
3090        // Remember that this register needs to added to the machine PHI node as
3091        // the input for this MBB.
3092        MVT::ValueType VT = TLI.getValueType(PN->getType());
3093        unsigned NumElements;
3094        if (VT != MVT::Vector)
3095          NumElements = TLI.getNumElements(VT);
3096        else {
3097          MVT::ValueType VT1,VT2;
3098          NumElements =
3099            TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3100                                       VT1, VT2);
3101        }
3102        for (unsigned i = 0, e = NumElements; i != e; ++i)
3103          PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3104      }
3105  }
3106  ConstantsOut.clear();
3107
3108  // Turn all of the unordered chains into one factored node.
3109  if (!UnorderedChains.empty()) {
3110    SDOperand Root = SDL.getRoot();
3111    if (Root.getOpcode() != ISD::EntryToken) {
3112      unsigned i = 0, e = UnorderedChains.size();
3113      for (; i != e; ++i) {
3114        assert(UnorderedChains[i].Val->getNumOperands() > 1);
3115        if (UnorderedChains[i].Val->getOperand(0) == Root)
3116          break;  // Don't add the root if we already indirectly depend on it.
3117      }
3118
3119      if (i == e)
3120        UnorderedChains.push_back(Root);
3121    }
3122    DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
3123  }
3124
3125  // Lower the terminator after the copies are emitted.
3126  SDL.visit(*LLVMBB->getTerminator());
3127
3128  // Copy over any CaseBlock records that may now exist due to SwitchInst
3129  // lowering, as well as any jump table information.
3130  SwitchCases.clear();
3131  SwitchCases = SDL.SwitchCases;
3132  JT = SDL.JT;
3133
3134  // Make sure the root of the DAG is up-to-date.
3135  DAG.setRoot(SDL.getRoot());
3136}
3137
3138void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
3139  // Run the DAG combiner in pre-legalize mode.
3140  DAG.Combine(false);
3141
3142  DEBUG(std::cerr << "Lowered selection DAG:\n");
3143  DEBUG(DAG.dump());
3144
3145  // Second step, hack on the DAG until it only uses operations and types that
3146  // the target supports.
3147  DAG.Legalize();
3148
3149  DEBUG(std::cerr << "Legalized selection DAG:\n");
3150  DEBUG(DAG.dump());
3151
3152  // Run the DAG combiner in post-legalize mode.
3153  DAG.Combine(true);
3154
3155  if (ViewISelDAGs) DAG.viewGraph();
3156
3157  // Third, instruction select all of the operations to machine code, adding the
3158  // code to the MachineBasicBlock.
3159  InstructionSelectBasicBlock(DAG);
3160
3161  DEBUG(std::cerr << "Selected machine code:\n");
3162  DEBUG(BB->dump());
3163}
3164
3165void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3166                                        FunctionLoweringInfo &FuncInfo) {
3167  std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3168  {
3169    SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3170    CurDAG = &DAG;
3171
3172    // First step, lower LLVM code to some DAG.  This DAG may use operations and
3173    // types that are not supported by the target.
3174    BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3175
3176    // Second step, emit the lowered DAG as machine code.
3177    CodeGenAndEmitDAG(DAG);
3178  }
3179
3180  // Next, now that we know what the last MBB the LLVM BB expanded is, update
3181  // PHI nodes in successors.
3182  if (SwitchCases.empty() && JT.Reg == 0) {
3183    for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3184      MachineInstr *PHI = PHINodesToUpdate[i].first;
3185      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3186             "This is not a machine PHI node that we are updating!");
3187      PHI->addRegOperand(PHINodesToUpdate[i].second);
3188      PHI->addMachineBasicBlockOperand(BB);
3189    }
3190    return;
3191  }
3192
3193  // If we need to emit a jump table,
3194  if (JT.Reg) {
3195    assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3196    SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3197    CurDAG = &SDAG;
3198    SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3199    // Set the current basic block to the mbb we wish to insert the code into
3200    BB = JT.MBB;
3201    SDL.setCurrentBasicBlock(BB);
3202    // Emit the code
3203    SDL.visitJumpTable(JT);
3204    SDAG.setRoot(SDL.getRoot());
3205    CodeGenAndEmitDAG(SDAG);
3206    // Update PHI Nodes
3207    for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3208      MachineInstr *PHI = PHINodesToUpdate[pi].first;
3209      MachineBasicBlock *PHIBB = PHI->getParent();
3210      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3211             "This is not a machine PHI node that we are updating!");
3212      if (JT.SuccMBBs.find(PHIBB) != JT.SuccMBBs.end()) {
3213        PHI->addRegOperand(PHINodesToUpdate[pi].second);
3214        PHI->addMachineBasicBlockOperand(BB);
3215      }
3216    }
3217    return;
3218  }
3219
3220  // If we generated any switch lowering information, build and codegen any
3221  // additional DAGs necessary.
3222  for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
3223    SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3224    CurDAG = &SDAG;
3225    SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3226    // Set the current basic block to the mbb we wish to insert the code into
3227    BB = SwitchCases[i].ThisBB;
3228    SDL.setCurrentBasicBlock(BB);
3229    // Emit the code
3230    SDL.visitSwitchCase(SwitchCases[i]);
3231    SDAG.setRoot(SDL.getRoot());
3232    CodeGenAndEmitDAG(SDAG);
3233    // Iterate over the phi nodes, if there is a phi node in a successor of this
3234    // block (for instance, the default block), then add a pair of operands to
3235    // the phi node for this block, as if we were coming from the original
3236    // BB before switch expansion.
3237    for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3238      MachineInstr *PHI = PHINodesToUpdate[pi].first;
3239      MachineBasicBlock *PHIBB = PHI->getParent();
3240      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3241             "This is not a machine PHI node that we are updating!");
3242      if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
3243        PHI->addRegOperand(PHINodesToUpdate[pi].second);
3244        PHI->addMachineBasicBlockOperand(BB);
3245      }
3246    }
3247  }
3248}
3249
3250//===----------------------------------------------------------------------===//
3251/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
3252/// target node in the graph.
3253void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
3254  if (ViewSchedDAGs) DAG.viewGraph();
3255  ScheduleDAG *SL = NULL;
3256
3257  switch (ISHeuristic) {
3258  default: assert(0 && "Unrecognized scheduling heuristic");
3259  case defaultScheduling:
3260    if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
3261      SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3262    else {
3263      assert(TLI.getSchedulingPreference() ==
3264             TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
3265      SL = createBURRListDAGScheduler(DAG, BB);
3266    }
3267    break;
3268  case noScheduling:
3269    SL = createBFS_DAGScheduler(DAG, BB);
3270    break;
3271  case simpleScheduling:
3272    SL = createSimpleDAGScheduler(false, DAG, BB);
3273    break;
3274  case simpleNoItinScheduling:
3275    SL = createSimpleDAGScheduler(true, DAG, BB);
3276    break;
3277  case listSchedulingBURR:
3278    SL = createBURRListDAGScheduler(DAG, BB);
3279    break;
3280  case listSchedulingTD:
3281    SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
3282    break;
3283  }
3284  BB = SL->Run();
3285  delete SL;
3286}
3287
3288HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
3289  return new HazardRecognizer();
3290}
3291
3292/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
3293/// by tblgen.  Others should not call it.
3294void SelectionDAGISel::
3295SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
3296  std::vector<SDOperand> InOps;
3297  std::swap(InOps, Ops);
3298
3299  Ops.push_back(InOps[0]);  // input chain.
3300  Ops.push_back(InOps[1]);  // input asm string.
3301
3302  const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
3303  unsigned i = 2, e = InOps.size();
3304  if (InOps[e-1].getValueType() == MVT::Flag)
3305    --e;  // Don't process a flag operand if it is here.
3306
3307  while (i != e) {
3308    unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
3309    if ((Flags & 7) != 4 /*MEM*/) {
3310      // Just skip over this operand, copying the operands verbatim.
3311      Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
3312      i += (Flags >> 3) + 1;
3313    } else {
3314      assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
3315      // Otherwise, this is a memory operand.  Ask the target to select it.
3316      std::vector<SDOperand> SelOps;
3317      if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
3318        std::cerr << "Could not match memory address.  Inline asm failure!\n";
3319        exit(1);
3320      }
3321
3322      // Add this to the output node.
3323      Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
3324      Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
3325      i += 2;
3326    }
3327  }
3328
3329  // Add the flag input back if present.
3330  if (e != InOps.size())
3331    Ops.push_back(InOps.back());
3332}
3333