SelectionDAGISel.cpp revision 6a586c8d9a7ba032adf0619d06473310c41cae14
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/Analysis/AliasAnalysis.h"
16#include "llvm/CodeGen/SelectionDAGISel.h"
17#include "llvm/CodeGen/ScheduleDAG.h"
18#include "llvm/CallingConv.h"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
21#include "llvm/Function.h"
22#include "llvm/GlobalVariable.h"
23#include "llvm/InlineAsm.h"
24#include "llvm/Instructions.h"
25#include "llvm/Intrinsics.h"
26#include "llvm/IntrinsicInst.h"
27#include "llvm/CodeGen/IntrinsicLowering.h"
28#include "llvm/CodeGen/MachineDebugInfo.h"
29#include "llvm/CodeGen/MachineFunction.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineJumpTableInfo.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/SchedulerRegistry.h"
34#include "llvm/CodeGen/SelectionDAG.h"
35#include "llvm/CodeGen/SSARegMap.h"
36#include "llvm/Target/MRegisterInfo.h"
37#include "llvm/Target/TargetData.h"
38#include "llvm/Target/TargetFrameInfo.h"
39#include "llvm/Target/TargetInstrInfo.h"
40#include "llvm/Target/TargetLowering.h"
41#include "llvm/Target/TargetMachine.h"
42#include "llvm/Target/TargetOptions.h"
43#include "llvm/Transforms/Utils/BasicBlockUtils.h"
44#include "llvm/Support/MathExtras.h"
45#include "llvm/Support/Debug.h"
46#include "llvm/Support/Compiler.h"
47#include <iostream>
48#include <algorithm>
49using namespace llvm;
50
51#ifndef NDEBUG
52static cl::opt<bool>
53ViewISelDAGs("view-isel-dags", cl::Hidden,
54          cl::desc("Pop up a window to show isel dags as they are selected"));
55static cl::opt<bool>
56ViewSchedDAGs("view-sched-dags", cl::Hidden,
57          cl::desc("Pop up a window to show sched dags as they are processed"));
58#else
59static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
60#endif
61
62
63//===---------------------------------------------------------------------===//
64///
65/// RegisterScheduler class - Track the registration of instruction schedulers.
66///
67//===---------------------------------------------------------------------===//
68MachinePassRegistry RegisterScheduler::Registry;
69
70//===---------------------------------------------------------------------===//
71///
72/// ISHeuristic command line option for instruction schedulers.
73///
74//===---------------------------------------------------------------------===//
75namespace {
76  cl::opt<RegisterScheduler::FunctionPassCtor, false,
77          RegisterPassParser<RegisterScheduler> >
78  ISHeuristic("sched",
79              cl::init(&createDefaultScheduler),
80              cl::desc("Instruction schedulers available:"));
81
82  static RegisterScheduler
83  defaultListDAGScheduler("default", "  Best scheduler for the target",
84                          createDefaultScheduler);
85} // namespace
86
87namespace {
88  /// RegsForValue - This struct represents the physical registers that a
89  /// particular value is assigned and the type information about the value.
90  /// This is needed because values can be promoted into larger registers and
91  /// expanded into multiple smaller registers than the value.
92  struct VISIBILITY_HIDDEN RegsForValue {
93    /// Regs - This list hold the register (for legal and promoted values)
94    /// or register set (for expanded values) that the value should be assigned
95    /// to.
96    std::vector<unsigned> Regs;
97
98    /// RegVT - The value type of each register.
99    ///
100    MVT::ValueType RegVT;
101
102    /// ValueVT - The value type of the LLVM value, which may be promoted from
103    /// RegVT or made from merging the two expanded parts.
104    MVT::ValueType ValueVT;
105
106    RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
107
108    RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
109      : RegVT(regvt), ValueVT(valuevt) {
110        Regs.push_back(Reg);
111    }
112    RegsForValue(const std::vector<unsigned> &regs,
113                 MVT::ValueType regvt, MVT::ValueType valuevt)
114      : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
115    }
116
117    /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
118    /// this value and returns the result as a ValueVT value.  This uses
119    /// Chain/Flag as the input and updates them for the output Chain/Flag.
120    SDOperand getCopyFromRegs(SelectionDAG &DAG,
121                              SDOperand &Chain, SDOperand &Flag) const;
122
123    /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
124    /// specified value into the registers specified by this object.  This uses
125    /// Chain/Flag as the input and updates them for the output Chain/Flag.
126    void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
127                       SDOperand &Chain, SDOperand &Flag,
128                       MVT::ValueType PtrVT) const;
129
130    /// AddInlineAsmOperands - Add this value to the specified inlineasm node
131    /// operand list.  This adds the code marker and includes the number of
132    /// values added into it.
133    void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
134                              std::vector<SDOperand> &Ops) const;
135  };
136}
137
138namespace llvm {
139  //===--------------------------------------------------------------------===//
140  /// createDefaultScheduler - This creates an instruction scheduler appropriate
141  /// for the target.
142  ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
143                                      SelectionDAG *DAG,
144                                      MachineBasicBlock *BB) {
145    TargetLowering &TLI = IS->getTargetLowering();
146
147    if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
148      return createTDListDAGScheduler(IS, DAG, BB);
149    } else {
150      assert(TLI.getSchedulingPreference() ==
151           TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
152      return createBURRListDAGScheduler(IS, DAG, BB);
153    }
154  }
155
156
157  //===--------------------------------------------------------------------===//
158  /// FunctionLoweringInfo - This contains information that is global to a
159  /// function that is used when lowering a region of the function.
160  class FunctionLoweringInfo {
161  public:
162    TargetLowering &TLI;
163    Function &Fn;
164    MachineFunction &MF;
165    SSARegMap *RegMap;
166
167    FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
168
169    /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
170    std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
171
172    /// ValueMap - Since we emit code for the function a basic block at a time,
173    /// we must remember which virtual registers hold the values for
174    /// cross-basic-block values.
175    std::map<const Value*, unsigned> ValueMap;
176
177    /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
178    /// the entry block.  This allows the allocas to be efficiently referenced
179    /// anywhere in the function.
180    std::map<const AllocaInst*, int> StaticAllocaMap;
181
182    unsigned MakeReg(MVT::ValueType VT) {
183      return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
184    }
185
186    /// isExportedInst - Return true if the specified value is an instruction
187    /// exported from its block.
188    bool isExportedInst(const Value *V) {
189      return ValueMap.count(V);
190    }
191
192    unsigned CreateRegForValue(const Value *V);
193
194    unsigned InitializeRegForValue(const Value *V) {
195      unsigned &R = ValueMap[V];
196      assert(R == 0 && "Already initialized this value register!");
197      return R = CreateRegForValue(V);
198    }
199  };
200}
201
202/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
203/// PHI nodes or outside of the basic block that defines it, or used by a
204/// switch instruction, which may expand to multiple basic blocks.
205static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
206  if (isa<PHINode>(I)) return true;
207  BasicBlock *BB = I->getParent();
208  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
209    if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
210        // FIXME: Remove switchinst special case.
211        isa<SwitchInst>(*UI))
212      return true;
213  return false;
214}
215
216/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
217/// entry block, return true.  This includes arguments used by switches, since
218/// the switch may expand into multiple basic blocks.
219static bool isOnlyUsedInEntryBlock(Argument *A) {
220  BasicBlock *Entry = A->getParent()->begin();
221  for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
222    if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
223      return false;  // Use not in entry block.
224  return true;
225}
226
227FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
228                                           Function &fn, MachineFunction &mf)
229    : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
230
231  // Create a vreg for each argument register that is not dead and is used
232  // outside of the entry block for the function.
233  for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
234       AI != E; ++AI)
235    if (!isOnlyUsedInEntryBlock(AI))
236      InitializeRegForValue(AI);
237
238  // Initialize the mapping of values to registers.  This is only set up for
239  // instruction values that are used outside of the block that defines
240  // them.
241  Function::iterator BB = Fn.begin(), EB = Fn.end();
242  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
243    if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
244      if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
245        const Type *Ty = AI->getAllocatedType();
246        uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
247        unsigned Align =
248          std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
249                   AI->getAlignment());
250
251        // If the alignment of the value is smaller than the size of the
252        // value, and if the size of the value is particularly small
253        // (<= 8 bytes), round up to the size of the value for potentially
254        // better performance.
255        //
256        // FIXME: This could be made better with a preferred alignment hook in
257        // TargetData.  It serves primarily to 8-byte align doubles for X86.
258        if (Align < TySize && TySize <= 8) Align = TySize;
259        TySize *= CUI->getZExtValue();   // Get total allocated size.
260        if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
261        StaticAllocaMap[AI] =
262          MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
263      }
264
265  for (; BB != EB; ++BB)
266    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
267      if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
268        if (!isa<AllocaInst>(I) ||
269            !StaticAllocaMap.count(cast<AllocaInst>(I)))
270          InitializeRegForValue(I);
271
272  // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
273  // also creates the initial PHI MachineInstrs, though none of the input
274  // operands are populated.
275  for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
276    MachineBasicBlock *MBB = new MachineBasicBlock(BB);
277    MBBMap[BB] = MBB;
278    MF.getBasicBlockList().push_back(MBB);
279
280    // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
281    // appropriate.
282    PHINode *PN;
283    for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
284      if (PN->use_empty()) continue;
285
286      MVT::ValueType VT = TLI.getValueType(PN->getType());
287      unsigned NumElements;
288      if (VT != MVT::Vector)
289        NumElements = TLI.getNumElements(VT);
290      else {
291        MVT::ValueType VT1,VT2;
292        NumElements =
293          TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
294                                     VT1, VT2);
295      }
296      unsigned PHIReg = ValueMap[PN];
297      assert(PHIReg && "PHI node does not have an assigned virtual register!");
298      for (unsigned i = 0; i != NumElements; ++i)
299        BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
300    }
301  }
302}
303
304/// CreateRegForValue - Allocate the appropriate number of virtual registers of
305/// the correctly promoted or expanded types.  Assign these registers
306/// consecutive vreg numbers and return the first assigned number.
307unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
308  MVT::ValueType VT = TLI.getValueType(V->getType());
309
310  // The number of multiples of registers that we need, to, e.g., split up
311  // a <2 x int64> -> 4 x i32 registers.
312  unsigned NumVectorRegs = 1;
313
314  // If this is a packed type, figure out what type it will decompose into
315  // and how many of the elements it will use.
316  if (VT == MVT::Vector) {
317    const PackedType *PTy = cast<PackedType>(V->getType());
318    unsigned NumElts = PTy->getNumElements();
319    MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
320
321    // Divide the input until we get to a supported size.  This will always
322    // end with a scalar if the target doesn't support vectors.
323    while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
324      NumElts >>= 1;
325      NumVectorRegs <<= 1;
326    }
327    if (NumElts == 1)
328      VT = EltTy;
329    else
330      VT = getVectorType(EltTy, NumElts);
331  }
332
333  // The common case is that we will only create one register for this
334  // value.  If we have that case, create and return the virtual register.
335  unsigned NV = TLI.getNumElements(VT);
336  if (NV == 1) {
337    // If we are promoting this value, pick the next largest supported type.
338    MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
339    unsigned Reg = MakeReg(PromotedType);
340    // If this is a vector of supported or promoted types (e.g. 4 x i16),
341    // create all of the registers.
342    for (unsigned i = 1; i != NumVectorRegs; ++i)
343      MakeReg(PromotedType);
344    return Reg;
345  }
346
347  // If this value is represented with multiple target registers, make sure
348  // to create enough consecutive registers of the right (smaller) type.
349  unsigned NT = VT-1;  // Find the type to use.
350  while (TLI.getNumElements((MVT::ValueType)NT) != 1)
351    --NT;
352
353  unsigned R = MakeReg((MVT::ValueType)NT);
354  for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
355    MakeReg((MVT::ValueType)NT);
356  return R;
357}
358
359//===----------------------------------------------------------------------===//
360/// SelectionDAGLowering - This is the common target-independent lowering
361/// implementation that is parameterized by a TargetLowering object.
362/// Also, targets can overload any lowering method.
363///
364namespace llvm {
365class SelectionDAGLowering {
366  MachineBasicBlock *CurMBB;
367
368  std::map<const Value*, SDOperand> NodeMap;
369
370  /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
371  /// them up and then emit token factor nodes when possible.  This allows us to
372  /// get simple disambiguation between loads without worrying about alias
373  /// analysis.
374  std::vector<SDOperand> PendingLoads;
375
376  /// Case - A pair of values to record the Value for a switch case, and the
377  /// case's target basic block.
378  typedef std::pair<Constant*, MachineBasicBlock*> Case;
379  typedef std::vector<Case>::iterator              CaseItr;
380  typedef std::pair<CaseItr, CaseItr>              CaseRange;
381
382  /// CaseRec - A struct with ctor used in lowering switches to a binary tree
383  /// of conditional branches.
384  struct CaseRec {
385    CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
386    CaseBB(bb), LT(lt), GE(ge), Range(r) {}
387
388    /// CaseBB - The MBB in which to emit the compare and branch
389    MachineBasicBlock *CaseBB;
390    /// LT, GE - If nonzero, we know the current case value must be less-than or
391    /// greater-than-or-equal-to these Constants.
392    Constant *LT;
393    Constant *GE;
394    /// Range - A pair of iterators representing the range of case values to be
395    /// processed at this point in the binary search tree.
396    CaseRange Range;
397  };
398
399  /// The comparison function for sorting Case values.
400  struct CaseCmp {
401    bool operator () (const Case& C1, const Case& C2) {
402      if (const ConstantInt* I1 = dyn_cast<const ConstantInt>(C1.first))
403        if (I1->getType()->isUnsigned())
404          return I1->getZExtValue() <
405            cast<const ConstantInt>(C2.first)->getZExtValue();
406
407      return cast<const ConstantInt>(C1.first)->getSExtValue() <
408         cast<const ConstantInt>(C2.first)->getSExtValue();
409    }
410  };
411
412public:
413  // TLI - This is information that describes the available target features we
414  // need for lowering.  This indicates when operations are unavailable,
415  // implemented with a libcall, etc.
416  TargetLowering &TLI;
417  SelectionDAG &DAG;
418  const TargetData *TD;
419
420  /// SwitchCases - Vector of CaseBlock structures used to communicate
421  /// SwitchInst code generation information.
422  std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
423  SelectionDAGISel::JumpTable JT;
424
425  /// FuncInfo - Information about the function as a whole.
426  ///
427  FunctionLoweringInfo &FuncInfo;
428
429  SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
430                       FunctionLoweringInfo &funcinfo)
431    : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
432      JT(0,0,0,0), FuncInfo(funcinfo) {
433  }
434
435  /// getRoot - Return the current virtual root of the Selection DAG.
436  ///
437  SDOperand getRoot() {
438    if (PendingLoads.empty())
439      return DAG.getRoot();
440
441    if (PendingLoads.size() == 1) {
442      SDOperand Root = PendingLoads[0];
443      DAG.setRoot(Root);
444      PendingLoads.clear();
445      return Root;
446    }
447
448    // Otherwise, we have to make a token factor node.
449    SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
450                                 &PendingLoads[0], PendingLoads.size());
451    PendingLoads.clear();
452    DAG.setRoot(Root);
453    return Root;
454  }
455
456  SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
457
458  void visit(Instruction &I) { visit(I.getOpcode(), I); }
459
460  void visit(unsigned Opcode, User &I) {
461    switch (Opcode) {
462    default: assert(0 && "Unknown instruction type encountered!");
463             abort();
464      // Build the switch statement using the Instruction.def file.
465#define HANDLE_INST(NUM, OPCODE, CLASS) \
466    case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
467#include "llvm/Instruction.def"
468    }
469  }
470
471  void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
472
473  SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
474                        const Value *SV, SDOperand Root,
475                        bool isVolatile);
476
477  SDOperand getIntPtrConstant(uint64_t Val) {
478    return DAG.getConstant(Val, TLI.getPointerTy());
479  }
480
481  SDOperand getValue(const Value *V);
482
483  const SDOperand &setValue(const Value *V, SDOperand NewN) {
484    SDOperand &N = NodeMap[V];
485    assert(N.Val == 0 && "Already set a value for this node!");
486    return N = NewN;
487  }
488
489  RegsForValue GetRegistersForValue(const std::string &ConstrCode,
490                                    MVT::ValueType VT,
491                                    bool OutReg, bool InReg,
492                                    std::set<unsigned> &OutputRegs,
493                                    std::set<unsigned> &InputRegs);
494
495  void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
496                            MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
497                            unsigned Opc);
498  bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
499  void ExportFromCurrentBlock(Value *V);
500
501  // Terminator instructions.
502  void visitRet(ReturnInst &I);
503  void visitBr(BranchInst &I);
504  void visitSwitch(SwitchInst &I);
505  void visitUnreachable(UnreachableInst &I) { /* noop */ }
506
507  // Helper for visitSwitch
508  void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
509  void visitJumpTable(SelectionDAGISel::JumpTable &JT);
510
511  // These all get lowered before this pass.
512  void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
513  void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
514
515  void visitIntBinary(User &I, unsigned IntOp, unsigned VecOp);
516  void visitFPBinary(User &I, unsigned FPOp, unsigned VecOp);
517  void visitShift(User &I, unsigned Opcode);
518  void visitAdd(User &I) {
519    if (I.getType()->isFloatingPoint())
520      visitFPBinary(I, ISD::FADD, ISD::VADD);
521    else
522      visitIntBinary(I, ISD::ADD, ISD::VADD);
523  }
524  void visitSub(User &I);
525  void visitMul(User &I) {
526    if (I.getType()->isFloatingPoint())
527      visitFPBinary(I, ISD::FMUL, ISD::VMUL);
528    else
529      visitIntBinary(I, ISD::MUL, ISD::VMUL);
530  }
531  void visitUDiv(User &I) { visitIntBinary(I, ISD::UDIV, ISD::VUDIV); }
532  void visitSDiv(User &I) { visitIntBinary(I, ISD::SDIV, ISD::VSDIV); }
533  void visitFDiv(User &I) { visitFPBinary(I, ISD::FDIV,  ISD::VSDIV); }
534  void visitRem(User &I) {
535    const Type *Ty = I.getType();
536    if (Ty->isFloatingPoint())
537      visitFPBinary(I, ISD::FREM, 0);
538    else
539      visitIntBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, 0);
540  }
541  void visitAnd(User &I) { visitIntBinary(I, ISD::AND, ISD::VAND); }
542  void visitOr (User &I) { visitIntBinary(I, ISD::OR,  ISD::VOR); }
543  void visitXor(User &I) { visitIntBinary(I, ISD::XOR, ISD::VXOR); }
544  void visitShl(User &I) { visitShift(I, ISD::SHL); }
545  void visitShr(User &I) {
546    visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
547  }
548
549  void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc,
550                  ISD::CondCode FPOpc);
551  void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ,
552                                        ISD::SETOEQ); }
553  void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE,
554                                        ISD::SETUNE); }
555  void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE,
556                                        ISD::SETOLE); }
557  void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE,
558                                        ISD::SETOGE); }
559  void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT,
560                                        ISD::SETOLT); }
561  void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT,
562                                        ISD::SETOGT); }
563
564  void visitExtractElement(User &I);
565  void visitInsertElement(User &I);
566  void visitShuffleVector(User &I);
567
568  void visitGetElementPtr(User &I);
569  void visitCast(User &I);
570  void visitSelect(User &I);
571
572  void visitMalloc(MallocInst &I);
573  void visitFree(FreeInst &I);
574  void visitAlloca(AllocaInst &I);
575  void visitLoad(LoadInst &I);
576  void visitStore(StoreInst &I);
577  void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
578  void visitCall(CallInst &I);
579  void visitInlineAsm(CallInst &I);
580  const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
581  void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
582
583  void visitVAStart(CallInst &I);
584  void visitVAArg(VAArgInst &I);
585  void visitVAEnd(CallInst &I);
586  void visitVACopy(CallInst &I);
587  void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
588
589  void visitMemIntrinsic(CallInst &I, unsigned Op);
590
591  void visitUserOp1(Instruction &I) {
592    assert(0 && "UserOp1 should not exist at instruction selection time!");
593    abort();
594  }
595  void visitUserOp2(Instruction &I) {
596    assert(0 && "UserOp2 should not exist at instruction selection time!");
597    abort();
598  }
599};
600} // end namespace llvm
601
602SDOperand SelectionDAGLowering::getValue(const Value *V) {
603  SDOperand &N = NodeMap[V];
604  if (N.Val) return N;
605
606  const Type *VTy = V->getType();
607  MVT::ValueType VT = TLI.getValueType(VTy);
608  if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
609    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
610      visit(CE->getOpcode(), *CE);
611      assert(N.Val && "visit didn't populate the ValueMap!");
612      return N;
613    } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
614      return N = DAG.getGlobalAddress(GV, VT);
615    } else if (isa<ConstantPointerNull>(C)) {
616      return N = DAG.getConstant(0, TLI.getPointerTy());
617    } else if (isa<UndefValue>(C)) {
618      if (!isa<PackedType>(VTy))
619        return N = DAG.getNode(ISD::UNDEF, VT);
620
621      // Create a VBUILD_VECTOR of undef nodes.
622      const PackedType *PTy = cast<PackedType>(VTy);
623      unsigned NumElements = PTy->getNumElements();
624      MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
625
626      SmallVector<SDOperand, 8> Ops;
627      Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
628
629      // Create a VConstant node with generic Vector type.
630      Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
631      Ops.push_back(DAG.getValueType(PVT));
632      return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
633                             &Ops[0], Ops.size());
634    } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
635      return N = DAG.getConstantFP(CFP->getValue(), VT);
636    } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
637      unsigned NumElements = PTy->getNumElements();
638      MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
639
640      // Now that we know the number and type of the elements, push a
641      // Constant or ConstantFP node onto the ops list for each element of
642      // the packed constant.
643      SmallVector<SDOperand, 8> Ops;
644      if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
645        for (unsigned i = 0; i != NumElements; ++i)
646          Ops.push_back(getValue(CP->getOperand(i)));
647      } else {
648        assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
649        SDOperand Op;
650        if (MVT::isFloatingPoint(PVT))
651          Op = DAG.getConstantFP(0, PVT);
652        else
653          Op = DAG.getConstant(0, PVT);
654        Ops.assign(NumElements, Op);
655      }
656
657      // Create a VBUILD_VECTOR node with generic Vector type.
658      Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
659      Ops.push_back(DAG.getValueType(PVT));
660      return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
661    } else {
662      // Canonicalize all constant ints to be unsigned.
663      return N = DAG.getConstant(cast<ConstantIntegral>(C)->getZExtValue(),VT);
664    }
665  }
666
667  if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
668    std::map<const AllocaInst*, int>::iterator SI =
669    FuncInfo.StaticAllocaMap.find(AI);
670    if (SI != FuncInfo.StaticAllocaMap.end())
671      return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
672  }
673
674  std::map<const Value*, unsigned>::const_iterator VMI =
675      FuncInfo.ValueMap.find(V);
676  assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
677
678  unsigned InReg = VMI->second;
679
680  // If this type is not legal, make it so now.
681  if (VT != MVT::Vector) {
682    MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
683
684    N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
685    if (DestVT < VT) {
686      // Source must be expanded.  This input value is actually coming from the
687      // register pair VMI->second and VMI->second+1.
688      N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
689                      DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
690    } else if (DestVT > VT) { // Promotion case
691      if (MVT::isFloatingPoint(VT))
692        N = DAG.getNode(ISD::FP_ROUND, VT, N);
693      else
694        N = DAG.getNode(ISD::TRUNCATE, VT, N);
695    }
696  } else {
697    // Otherwise, if this is a vector, make it available as a generic vector
698    // here.
699    MVT::ValueType PTyElementVT, PTyLegalElementVT;
700    const PackedType *PTy = cast<PackedType>(VTy);
701    unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
702                                             PTyLegalElementVT);
703
704    // Build a VBUILD_VECTOR with the input registers.
705    SmallVector<SDOperand, 8> Ops;
706    if (PTyElementVT == PTyLegalElementVT) {
707      // If the value types are legal, just VBUILD the CopyFromReg nodes.
708      for (unsigned i = 0; i != NE; ++i)
709        Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
710                                         PTyElementVT));
711    } else if (PTyElementVT < PTyLegalElementVT) {
712      // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
713      for (unsigned i = 0; i != NE; ++i) {
714        SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
715                                          PTyElementVT);
716        if (MVT::isFloatingPoint(PTyElementVT))
717          Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
718        else
719          Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
720        Ops.push_back(Op);
721      }
722    } else {
723      // If the register was expanded, use BUILD_PAIR.
724      assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
725      for (unsigned i = 0; i != NE/2; ++i) {
726        SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
727                                           PTyElementVT);
728        SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++,
729                                           PTyElementVT);
730        Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
731      }
732    }
733
734    Ops.push_back(DAG.getConstant(NE, MVT::i32));
735    Ops.push_back(DAG.getValueType(PTyLegalElementVT));
736    N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
737
738    // Finally, use a VBIT_CONVERT to make this available as the appropriate
739    // vector type.
740    N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
741                    DAG.getConstant(PTy->getNumElements(),
742                                    MVT::i32),
743                    DAG.getValueType(TLI.getValueType(PTy->getElementType())));
744  }
745
746  return N;
747}
748
749
750void SelectionDAGLowering::visitRet(ReturnInst &I) {
751  if (I.getNumOperands() == 0) {
752    DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
753    return;
754  }
755  SmallVector<SDOperand, 8> NewValues;
756  NewValues.push_back(getRoot());
757  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
758    SDOperand RetOp = getValue(I.getOperand(i));
759    bool isSigned = I.getOperand(i)->getType()->isSigned();
760
761    // If this is an integer return value, we need to promote it ourselves to
762    // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
763    // than sign/zero.
764    // FIXME: C calling convention requires the return type to be promoted to
765    // at least 32-bit. But this is not necessary for non-C calling conventions.
766    if (MVT::isInteger(RetOp.getValueType()) &&
767        RetOp.getValueType() < MVT::i64) {
768      MVT::ValueType TmpVT;
769      if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
770        TmpVT = TLI.getTypeToTransformTo(MVT::i32);
771      else
772        TmpVT = MVT::i32;
773
774      if (isSigned)
775        RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
776      else
777        RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
778    }
779    NewValues.push_back(RetOp);
780    NewValues.push_back(DAG.getConstant(isSigned, MVT::i32));
781  }
782  DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
783                          &NewValues[0], NewValues.size()));
784}
785
786/// ExportFromCurrentBlock - If this condition isn't known to be exported from
787/// the current basic block, add it to ValueMap now so that we'll get a
788/// CopyTo/FromReg.
789void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
790  // No need to export constants.
791  if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
792
793  // Already exported?
794  if (FuncInfo.isExportedInst(V)) return;
795
796  unsigned Reg = FuncInfo.InitializeRegForValue(V);
797  PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
798}
799
800bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
801                                                    const BasicBlock *FromBB) {
802  // The operands of the setcc have to be in this block.  We don't know
803  // how to export them from some other block.
804  if (Instruction *VI = dyn_cast<Instruction>(V)) {
805    // Can export from current BB.
806    if (VI->getParent() == FromBB)
807      return true;
808
809    // Is already exported, noop.
810    return FuncInfo.isExportedInst(V);
811  }
812
813  // If this is an argument, we can export it if the BB is the entry block or
814  // if it is already exported.
815  if (isa<Argument>(V)) {
816    if (FromBB == &FromBB->getParent()->getEntryBlock())
817      return true;
818
819    // Otherwise, can only export this if it is already exported.
820    return FuncInfo.isExportedInst(V);
821  }
822
823  // Otherwise, constants can always be exported.
824  return true;
825}
826
827static bool InBlock(const Value *V, const BasicBlock *BB) {
828  if (const Instruction *I = dyn_cast<Instruction>(V))
829    return I->getParent() == BB;
830  return true;
831}
832
833/// FindMergedConditions - If Cond is an expression like
834void SelectionDAGLowering::FindMergedConditions(Value *Cond,
835                                                MachineBasicBlock *TBB,
836                                                MachineBasicBlock *FBB,
837                                                MachineBasicBlock *CurBB,
838                                                unsigned Opc) {
839  // If this node is not part of the or/and tree, emit it as a branch.
840  BinaryOperator *BOp = dyn_cast<BinaryOperator>(Cond);
841
842  if (!BOp || (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
843      BOp->getParent() != CurBB->getBasicBlock() ||
844      !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
845      !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
846    const BasicBlock *BB = CurBB->getBasicBlock();
847
848    // If the leaf of the tree is a setcond inst, merge the condition into the
849    // caseblock.
850    if (BOp && isa<SetCondInst>(BOp) &&
851        // The operands of the setcc have to be in this block.  We don't know
852        // how to export them from some other block.  If this is the first block
853        // of the sequence, no exporting is needed.
854        (CurBB == CurMBB ||
855         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
856          isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
857      ISD::CondCode SignCond, UnsCond, FPCond, Condition;
858      switch (BOp->getOpcode()) {
859      default: assert(0 && "Unknown setcc opcode!");
860      case Instruction::SetEQ:
861        SignCond = ISD::SETEQ;
862        UnsCond  = ISD::SETEQ;
863        FPCond   = ISD::SETOEQ;
864        break;
865      case Instruction::SetNE:
866        SignCond = ISD::SETNE;
867        UnsCond  = ISD::SETNE;
868        FPCond   = ISD::SETUNE;
869        break;
870      case Instruction::SetLE:
871        SignCond = ISD::SETLE;
872        UnsCond  = ISD::SETULE;
873        FPCond   = ISD::SETOLE;
874        break;
875      case Instruction::SetGE:
876        SignCond = ISD::SETGE;
877        UnsCond  = ISD::SETUGE;
878        FPCond   = ISD::SETOGE;
879        break;
880      case Instruction::SetLT:
881        SignCond = ISD::SETLT;
882        UnsCond  = ISD::SETULT;
883        FPCond   = ISD::SETOLT;
884        break;
885      case Instruction::SetGT:
886        SignCond = ISD::SETGT;
887        UnsCond  = ISD::SETUGT;
888        FPCond   = ISD::SETOGT;
889        break;
890      }
891
892      const Type *OpType = BOp->getOperand(0)->getType();
893      if (const PackedType *PTy = dyn_cast<PackedType>(OpType))
894        OpType = PTy->getElementType();
895
896      if (!FiniteOnlyFPMath() && OpType->isFloatingPoint())
897        Condition = FPCond;
898      else if (OpType->isUnsigned())
899        Condition = UnsCond;
900      else
901        Condition = SignCond;
902
903      SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
904                                     BOp->getOperand(1), TBB, FBB, CurBB);
905      SwitchCases.push_back(CB);
906      return;
907    }
908
909    // Create a CaseBlock record representing this branch.
910    SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantBool::getTrue(),
911                                   TBB, FBB, CurBB);
912    SwitchCases.push_back(CB);
913    return;
914  }
915
916
917  //  Create TmpBB after CurBB.
918  MachineFunction::iterator BBI = CurBB;
919  MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
920  CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
921
922  if (Opc == Instruction::Or) {
923    // Codegen X | Y as:
924    //   jmp_if_X TBB
925    //   jmp TmpBB
926    // TmpBB:
927    //   jmp_if_Y TBB
928    //   jmp FBB
929    //
930
931    // Emit the LHS condition.
932    FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
933
934    // Emit the RHS condition into TmpBB.
935    FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
936  } else {
937    assert(Opc == Instruction::And && "Unknown merge op!");
938    // Codegen X & Y as:
939    //   jmp_if_X TmpBB
940    //   jmp FBB
941    // TmpBB:
942    //   jmp_if_Y TBB
943    //   jmp FBB
944    //
945    //  This requires creation of TmpBB after CurBB.
946
947    // Emit the LHS condition.
948    FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
949
950    // Emit the RHS condition into TmpBB.
951    FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
952  }
953}
954
955void SelectionDAGLowering::visitBr(BranchInst &I) {
956  // Update machine-CFG edges.
957  MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
958
959  // Figure out which block is immediately after the current one.
960  MachineBasicBlock *NextBlock = 0;
961  MachineFunction::iterator BBI = CurMBB;
962  if (++BBI != CurMBB->getParent()->end())
963    NextBlock = BBI;
964
965  if (I.isUnconditional()) {
966    // If this is not a fall-through branch, emit the branch.
967    if (Succ0MBB != NextBlock)
968      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
969                              DAG.getBasicBlock(Succ0MBB)));
970
971    // Update machine-CFG edges.
972    CurMBB->addSuccessor(Succ0MBB);
973
974    return;
975  }
976
977  // If this condition is one of the special cases we handle, do special stuff
978  // now.
979  Value *CondVal = I.getCondition();
980  MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
981
982  // If this is a series of conditions that are or'd or and'd together, emit
983  // this as a sequence of branches instead of setcc's with and/or operations.
984  // For example, instead of something like:
985  //     cmp A, B
986  //     C = seteq
987  //     cmp D, E
988  //     F = setle
989  //     or C, F
990  //     jnz foo
991  // Emit:
992  //     cmp A, B
993  //     je foo
994  //     cmp D, E
995  //     jle foo
996  //
997  if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
998    if (BOp->hasOneUse() &&
999        (BOp->getOpcode() == Instruction::And ||
1000         BOp->getOpcode() == Instruction::Or)) {
1001      FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1002
1003      // If the compares in later blocks need to use values not currently
1004      // exported from this block, export them now.  This block should always be
1005      // the first entry.
1006      assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1007
1008      for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1009        ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1010        ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1011      }
1012
1013      // Emit the branch for this block.
1014      visitSwitchCase(SwitchCases[0]);
1015      SwitchCases.erase(SwitchCases.begin());
1016      return;
1017    }
1018  }
1019
1020  // Create a CaseBlock record representing this branch.
1021  SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantBool::getTrue(),
1022                                 Succ0MBB, Succ1MBB, CurMBB);
1023  // Use visitSwitchCase to actually insert the fast branch sequence for this
1024  // cond branch.
1025  visitSwitchCase(CB);
1026}
1027
1028/// visitSwitchCase - Emits the necessary code to represent a single node in
1029/// the binary search tree resulting from lowering a switch instruction.
1030void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1031  SDOperand Cond;
1032  SDOperand CondLHS = getValue(CB.CmpLHS);
1033
1034  // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1035  // handle common cases produced by branch lowering.
1036  if (CB.CmpRHS == ConstantBool::getTrue() && CB.CC == ISD::SETEQ)
1037    Cond = CondLHS;
1038  else if (CB.CmpRHS == ConstantBool::getFalse() && CB.CC == ISD::SETEQ) {
1039    SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1040    Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1041  } else
1042    Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1043
1044  // Set NextBlock to be the MBB immediately after the current one, if any.
1045  // This is used to avoid emitting unnecessary branches to the next block.
1046  MachineBasicBlock *NextBlock = 0;
1047  MachineFunction::iterator BBI = CurMBB;
1048  if (++BBI != CurMBB->getParent()->end())
1049    NextBlock = BBI;
1050
1051  // If the lhs block is the next block, invert the condition so that we can
1052  // fall through to the lhs instead of the rhs block.
1053  if (CB.TrueBB == NextBlock) {
1054    std::swap(CB.TrueBB, CB.FalseBB);
1055    SDOperand True = DAG.getConstant(1, Cond.getValueType());
1056    Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1057  }
1058  SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1059                                 DAG.getBasicBlock(CB.TrueBB));
1060  if (CB.FalseBB == NextBlock)
1061    DAG.setRoot(BrCond);
1062  else
1063    DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1064                            DAG.getBasicBlock(CB.FalseBB)));
1065  // Update successor info
1066  CurMBB->addSuccessor(CB.TrueBB);
1067  CurMBB->addSuccessor(CB.FalseBB);
1068}
1069
1070void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1071  // Emit the code for the jump table
1072  MVT::ValueType PTy = TLI.getPointerTy();
1073  assert((PTy == MVT::i32 || PTy == MVT::i64) &&
1074         "Jump table entries are 32-bit values");
1075  bool isPIC = TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_;
1076  // PIC jump table entries are 32-bit values.
1077  unsigned EntrySize = isPIC ? 4 : MVT::getSizeInBits(PTy)/8;
1078  SDOperand Copy = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1079  SDOperand IDX = DAG.getNode(ISD::MUL, PTy, Copy,
1080                              DAG.getConstant(EntrySize, PTy));
1081  SDOperand TAB = DAG.getJumpTable(JT.JTI,PTy);
1082  SDOperand ADD = DAG.getNode(ISD::ADD, PTy, IDX, TAB);
1083  SDOperand LD  = DAG.getLoad(isPIC ? MVT::i32 : PTy, Copy.getValue(1), ADD,
1084                              NULL, 0);
1085  if (isPIC) {
1086    // For Pic, the sequence is:
1087    // BRIND(load(Jumptable + index) + RelocBase)
1088    // RelocBase is the JumpTable on PPC and X86, GOT on Alpha
1089    SDOperand Reloc;
1090    if (TLI.usesGlobalOffsetTable())
1091      Reloc = DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, PTy);
1092    else
1093      Reloc = TAB;
1094    ADD = (PTy != MVT::i32) ? DAG.getNode(ISD::SIGN_EXTEND, PTy, LD) : LD;
1095    ADD = DAG.getNode(ISD::ADD, PTy, ADD, Reloc);
1096    DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), ADD));
1097  } else {
1098    DAG.setRoot(DAG.getNode(ISD::BRIND, MVT::Other, LD.getValue(1), LD));
1099  }
1100}
1101
1102void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1103  // Figure out which block is immediately after the current one.
1104  MachineBasicBlock *NextBlock = 0;
1105  MachineFunction::iterator BBI = CurMBB;
1106
1107  if (++BBI != CurMBB->getParent()->end())
1108    NextBlock = BBI;
1109
1110  MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1111
1112  // If there is only the default destination, branch to it if it is not the
1113  // next basic block.  Otherwise, just fall through.
1114  if (I.getNumOperands() == 2) {
1115    // Update machine-CFG edges.
1116
1117    // If this is not a fall-through branch, emit the branch.
1118    if (Default != NextBlock)
1119      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1120                              DAG.getBasicBlock(Default)));
1121
1122    CurMBB->addSuccessor(Default);
1123    return;
1124  }
1125
1126  // If there are any non-default case statements, create a vector of Cases
1127  // representing each one, and sort the vector so that we can efficiently
1128  // create a binary search tree from them.
1129  std::vector<Case> Cases;
1130
1131  for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1132    MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1133    Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1134  }
1135
1136  std::sort(Cases.begin(), Cases.end(), CaseCmp());
1137
1138  // Get the Value to be switched on and default basic blocks, which will be
1139  // inserted into CaseBlock records, representing basic blocks in the binary
1140  // search tree.
1141  Value *SV = I.getOperand(0);
1142
1143  // Get the MachineFunction which holds the current MBB.  This is used during
1144  // emission of jump tables, and when inserting any additional MBBs necessary
1145  // to represent the switch.
1146  MachineFunction *CurMF = CurMBB->getParent();
1147  const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
1148
1149  // If the switch has few cases (two or less) emit a series of specific
1150  // tests.
1151  if (Cases.size() < 3) {
1152    // TODO: If any two of the cases has the same destination, and if one value
1153    // is the same as the other, but has one bit unset that the other has set,
1154    // use bit manipulation to do two compares at once.  For example:
1155    // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1156
1157    // Rearrange the case blocks so that the last one falls through if possible.
1158    if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1159      // The last case block won't fall through into 'NextBlock' if we emit the
1160      // branches in this order.  See if rearranging a case value would help.
1161      for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1162        if (Cases[i].second == NextBlock) {
1163          std::swap(Cases[i], Cases.back());
1164          break;
1165        }
1166      }
1167    }
1168
1169    // Create a CaseBlock record representing a conditional branch to
1170    // the Case's target mbb if the value being switched on SV is equal
1171    // to C.
1172    MachineBasicBlock *CurBlock = CurMBB;
1173    for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1174      MachineBasicBlock *FallThrough;
1175      if (i != e-1) {
1176        FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1177        CurMF->getBasicBlockList().insert(BBI, FallThrough);
1178      } else {
1179        // If the last case doesn't match, go to the default block.
1180        FallThrough = Default;
1181      }
1182
1183      SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1184                                     Cases[i].second, FallThrough, CurBlock);
1185
1186      // If emitting the first comparison, just call visitSwitchCase to emit the
1187      // code into the current block.  Otherwise, push the CaseBlock onto the
1188      // vector to be later processed by SDISel, and insert the node's MBB
1189      // before the next MBB.
1190      if (CurBlock == CurMBB)
1191        visitSwitchCase(CB);
1192      else
1193        SwitchCases.push_back(CB);
1194
1195      CurBlock = FallThrough;
1196    }
1197    return;
1198  }
1199
1200  // If the switch has more than 5 blocks, and at least 31.25% dense, and the
1201  // target supports indirect branches, then emit a jump table rather than
1202  // lowering the switch to a binary tree of conditional branches.
1203  if (TLI.isOperationLegal(ISD::BRIND, TLI.getPointerTy()) &&
1204      Cases.size() > 5) {
1205    uint64_t First =cast<ConstantIntegral>(Cases.front().first)->getZExtValue();
1206    uint64_t Last  = cast<ConstantIntegral>(Cases.back().first)->getZExtValue();
1207    double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1208
1209    if (Density >= 0.3125) {
1210      // Create a new basic block to hold the code for loading the address
1211      // of the jump table, and jumping to it.  Update successor information;
1212      // we will either branch to the default case for the switch, or the jump
1213      // table.
1214      MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1215      CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1216      CurMBB->addSuccessor(Default);
1217      CurMBB->addSuccessor(JumpTableBB);
1218
1219      // Subtract the lowest switch case value from the value being switched on
1220      // and conditional branch to default mbb if the result is greater than the
1221      // difference between smallest and largest cases.
1222      SDOperand SwitchOp = getValue(SV);
1223      MVT::ValueType VT = SwitchOp.getValueType();
1224      SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1225                                  DAG.getConstant(First, VT));
1226
1227      // The SDNode we just created, which holds the value being switched on
1228      // minus the the smallest case value, needs to be copied to a virtual
1229      // register so it can be used as an index into the jump table in a
1230      // subsequent basic block.  This value may be smaller or larger than the
1231      // target's pointer type, and therefore require extension or truncating.
1232      if (VT > TLI.getPointerTy())
1233        SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1234      else
1235        SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1236
1237      unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1238      SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1239
1240      // Emit the range check for the jump table, and branch to the default
1241      // block for the switch statement if the value being switched on exceeds
1242      // the largest case in the switch.
1243      SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1244                                   DAG.getConstant(Last-First,VT), ISD::SETUGT);
1245      DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1246                              DAG.getBasicBlock(Default)));
1247
1248      // Build a vector of destination BBs, corresponding to each target
1249      // of the jump table.  If the value of the jump table slot corresponds to
1250      // a case statement, push the case's BB onto the vector, otherwise, push
1251      // the default BB.
1252      std::vector<MachineBasicBlock*> DestBBs;
1253      uint64_t TEI = First;
1254      for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
1255        if (cast<ConstantIntegral>(ii->first)->getZExtValue() == TEI) {
1256          DestBBs.push_back(ii->second);
1257          ++ii;
1258        } else {
1259          DestBBs.push_back(Default);
1260        }
1261
1262      // Update successor info.  Add one edge to each unique successor.
1263      // Vector bool would be better, but vector<bool> is really slow.
1264      std::vector<unsigned char> SuccsHandled;
1265      SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1266
1267      for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1268           E = DestBBs.end(); I != E; ++I) {
1269        if (!SuccsHandled[(*I)->getNumber()]) {
1270          SuccsHandled[(*I)->getNumber()] = true;
1271          JumpTableBB->addSuccessor(*I);
1272        }
1273      }
1274
1275      // Create a jump table index for this jump table, or return an existing
1276      // one.
1277      unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1278
1279      // Set the jump table information so that we can codegen it as a second
1280      // MachineBasicBlock
1281      JT.Reg = JumpTableReg;
1282      JT.JTI = JTI;
1283      JT.MBB = JumpTableBB;
1284      JT.Default = Default;
1285      return;
1286    }
1287  }
1288
1289  // Push the initial CaseRec onto the worklist
1290  std::vector<CaseRec> CaseVec;
1291  CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1292
1293  while (!CaseVec.empty()) {
1294    // Grab a record representing a case range to process off the worklist
1295    CaseRec CR = CaseVec.back();
1296    CaseVec.pop_back();
1297
1298    // Size is the number of Cases represented by this range.  If Size is 1,
1299    // then we are processing a leaf of the binary search tree.  Otherwise,
1300    // we need to pick a pivot, and push left and right ranges onto the
1301    // worklist.
1302    unsigned Size = CR.Range.second - CR.Range.first;
1303
1304    if (Size == 1) {
1305      // Create a CaseBlock record representing a conditional branch to
1306      // the Case's target mbb if the value being switched on SV is equal
1307      // to C.  Otherwise, branch to default.
1308      Constant *C = CR.Range.first->first;
1309      MachineBasicBlock *Target = CR.Range.first->second;
1310      SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default,
1311                                     CR.CaseBB);
1312
1313      // If the MBB representing the leaf node is the current MBB, then just
1314      // call visitSwitchCase to emit the code into the current block.
1315      // Otherwise, push the CaseBlock onto the vector to be later processed
1316      // by SDISel, and insert the node's MBB before the next MBB.
1317      if (CR.CaseBB == CurMBB)
1318        visitSwitchCase(CB);
1319      else
1320        SwitchCases.push_back(CB);
1321    } else {
1322      // split case range at pivot
1323      CaseItr Pivot = CR.Range.first + (Size / 2);
1324      CaseRange LHSR(CR.Range.first, Pivot);
1325      CaseRange RHSR(Pivot, CR.Range.second);
1326      Constant *C = Pivot->first;
1327      MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1328
1329      // We know that we branch to the LHS if the Value being switched on is
1330      // less than the Pivot value, C.  We use this to optimize our binary
1331      // tree a bit, by recognizing that if SV is greater than or equal to the
1332      // LHS's Case Value, and that Case Value is exactly one less than the
1333      // Pivot's Value, then we can branch directly to the LHS's Target,
1334      // rather than creating a leaf node for it.
1335      if ((LHSR.second - LHSR.first) == 1 &&
1336          LHSR.first->first == CR.GE &&
1337          cast<ConstantIntegral>(C)->getZExtValue() ==
1338          (cast<ConstantIntegral>(CR.GE)->getZExtValue() + 1ULL)) {
1339        TrueBB = LHSR.first->second;
1340      } else {
1341        TrueBB = new MachineBasicBlock(LLVMBB);
1342        CurMF->getBasicBlockList().insert(BBI, TrueBB);
1343        CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1344      }
1345
1346      // Similar to the optimization above, if the Value being switched on is
1347      // known to be less than the Constant CR.LT, and the current Case Value
1348      // is CR.LT - 1, then we can branch directly to the target block for
1349      // the current Case Value, rather than emitting a RHS leaf node for it.
1350      if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1351          cast<ConstantIntegral>(RHSR.first->first)->getZExtValue() ==
1352          (cast<ConstantIntegral>(CR.LT)->getZExtValue() - 1ULL)) {
1353        FalseBB = RHSR.first->second;
1354      } else {
1355        FalseBB = new MachineBasicBlock(LLVMBB);
1356        CurMF->getBasicBlockList().insert(BBI, FalseBB);
1357        CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1358      }
1359
1360      // Create a CaseBlock record representing a conditional branch to
1361      // the LHS node if the value being switched on SV is less than C.
1362      // Otherwise, branch to LHS.
1363      ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
1364      SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
1365
1366      if (CR.CaseBB == CurMBB)
1367        visitSwitchCase(CB);
1368      else
1369        SwitchCases.push_back(CB);
1370    }
1371  }
1372}
1373
1374void SelectionDAGLowering::visitSub(User &I) {
1375  // -0.0 - X --> fneg
1376  if (I.getType()->isFloatingPoint()) {
1377    if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1378      if (CFP->isExactlyValue(-0.0)) {
1379        SDOperand Op2 = getValue(I.getOperand(1));
1380        setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1381        return;
1382      }
1383    visitFPBinary(I, ISD::FSUB, ISD::VSUB);
1384  } else
1385    visitIntBinary(I, ISD::SUB, ISD::VSUB);
1386}
1387
1388void
1389SelectionDAGLowering::visitIntBinary(User &I, unsigned IntOp, unsigned VecOp) {
1390  const Type *Ty = I.getType();
1391  SDOperand Op1 = getValue(I.getOperand(0));
1392  SDOperand Op2 = getValue(I.getOperand(1));
1393
1394  if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1395    SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1396    SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1397    setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1398  } else {
1399    setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
1400  }
1401}
1402
1403void
1404SelectionDAGLowering::visitFPBinary(User &I, unsigned FPOp, unsigned VecOp) {
1405  const Type *Ty = I.getType();
1406  SDOperand Op1 = getValue(I.getOperand(0));
1407  SDOperand Op2 = getValue(I.getOperand(1));
1408
1409  if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1410    SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
1411    SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
1412    setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
1413  } else {
1414    setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
1415  }
1416}
1417
1418void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1419  SDOperand Op1 = getValue(I.getOperand(0));
1420  SDOperand Op2 = getValue(I.getOperand(1));
1421
1422  Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1423
1424  setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1425}
1426
1427void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
1428                                      ISD::CondCode UnsignedOpcode,
1429                                      ISD::CondCode FPOpcode) {
1430  SDOperand Op1 = getValue(I.getOperand(0));
1431  SDOperand Op2 = getValue(I.getOperand(1));
1432  ISD::CondCode Opcode = SignedOpcode;
1433  if (!FiniteOnlyFPMath() && I.getOperand(0)->getType()->isFloatingPoint())
1434    Opcode = FPOpcode;
1435  else if (I.getOperand(0)->getType()->isUnsigned())
1436    Opcode = UnsignedOpcode;
1437  setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1438}
1439
1440void SelectionDAGLowering::visitSelect(User &I) {
1441  SDOperand Cond     = getValue(I.getOperand(0));
1442  SDOperand TrueVal  = getValue(I.getOperand(1));
1443  SDOperand FalseVal = getValue(I.getOperand(2));
1444  if (!isa<PackedType>(I.getType())) {
1445    setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1446                             TrueVal, FalseVal));
1447  } else {
1448    setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1449                             *(TrueVal.Val->op_end()-2),
1450                             *(TrueVal.Val->op_end()-1)));
1451  }
1452}
1453
1454void SelectionDAGLowering::visitCast(User &I) {
1455  SDOperand N = getValue(I.getOperand(0));
1456  MVT::ValueType SrcVT = N.getValueType();
1457  MVT::ValueType DestVT = TLI.getValueType(I.getType());
1458
1459  if (DestVT == MVT::Vector) {
1460    // This is a cast to a vector from something else.  This is always a bit
1461    // convert.  Get information about the input vector.
1462    const PackedType *DestTy = cast<PackedType>(I.getType());
1463    MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1464    setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N,
1465                             DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1466                             DAG.getValueType(EltVT)));
1467  } else if (SrcVT == DestVT) {
1468    setValue(&I, N);  // noop cast.
1469  } else if (DestVT == MVT::i1) {
1470    // Cast to bool is a comparison against zero, not truncation to zero.
1471    SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
1472                                       DAG.getConstantFP(0.0, N.getValueType());
1473    setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
1474  } else if (isInteger(SrcVT)) {
1475    if (isInteger(DestVT)) {        // Int -> Int cast
1476      if (DestVT < SrcVT)   // Truncating cast?
1477        setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1478      else if (I.getOperand(0)->getType()->isSigned())
1479        setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1480      else
1481        setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1482    } else if (isFloatingPoint(DestVT)) {           // Int -> FP cast
1483      if (I.getOperand(0)->getType()->isSigned())
1484        setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1485      else
1486        setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1487    } else {
1488      assert(0 && "Unknown cast!");
1489    }
1490  } else if (isFloatingPoint(SrcVT)) {
1491    if (isFloatingPoint(DestVT)) {  // FP -> FP cast
1492      if (DestVT < SrcVT)   // Rounding cast?
1493        setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1494      else
1495        setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1496    } else if (isInteger(DestVT)) {        // FP -> Int cast.
1497      if (I.getType()->isSigned())
1498        setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1499      else
1500        setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1501    } else {
1502      assert(0 && "Unknown cast!");
1503    }
1504  } else {
1505    assert(SrcVT == MVT::Vector && "Unknown cast!");
1506    assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1507    // This is a cast from a vector to something else.  This is always a bit
1508    // convert.  Get information about the input vector.
1509    setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1510  }
1511}
1512
1513void SelectionDAGLowering::visitInsertElement(User &I) {
1514  SDOperand InVec = getValue(I.getOperand(0));
1515  SDOperand InVal = getValue(I.getOperand(1));
1516  SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1517                                getValue(I.getOperand(2)));
1518
1519  SDOperand Num = *(InVec.Val->op_end()-2);
1520  SDOperand Typ = *(InVec.Val->op_end()-1);
1521  setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1522                           InVec, InVal, InIdx, Num, Typ));
1523}
1524
1525void SelectionDAGLowering::visitExtractElement(User &I) {
1526  SDOperand InVec = getValue(I.getOperand(0));
1527  SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1528                                getValue(I.getOperand(1)));
1529  SDOperand Typ = *(InVec.Val->op_end()-1);
1530  setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1531                           TLI.getValueType(I.getType()), InVec, InIdx));
1532}
1533
1534void SelectionDAGLowering::visitShuffleVector(User &I) {
1535  SDOperand V1   = getValue(I.getOperand(0));
1536  SDOperand V2   = getValue(I.getOperand(1));
1537  SDOperand Mask = getValue(I.getOperand(2));
1538
1539  SDOperand Num = *(V1.Val->op_end()-2);
1540  SDOperand Typ = *(V2.Val->op_end()-1);
1541  setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1542                           V1, V2, Mask, Num, Typ));
1543}
1544
1545
1546void SelectionDAGLowering::visitGetElementPtr(User &I) {
1547  SDOperand N = getValue(I.getOperand(0));
1548  const Type *Ty = I.getOperand(0)->getType();
1549
1550  for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1551       OI != E; ++OI) {
1552    Value *Idx = *OI;
1553    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1554      unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
1555      if (Field) {
1556        // N = N + Offset
1557        uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1558        N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1559                        getIntPtrConstant(Offset));
1560      }
1561      Ty = StTy->getElementType(Field);
1562    } else {
1563      Ty = cast<SequentialType>(Ty)->getElementType();
1564
1565      // If this is a constant subscript, handle it quickly.
1566      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1567        if (CI->getZExtValue() == 0) continue;
1568        uint64_t Offs;
1569        if (CI->getType()->isSigned())
1570          Offs = (int64_t)
1571            TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
1572        else
1573          Offs =
1574            TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getZExtValue();
1575        N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1576        continue;
1577      }
1578
1579      // N = N + Idx * ElementSize;
1580      uint64_t ElementSize = TD->getTypeSize(Ty);
1581      SDOperand IdxN = getValue(Idx);
1582
1583      // If the index is smaller or larger than intptr_t, truncate or extend
1584      // it.
1585      if (IdxN.getValueType() < N.getValueType()) {
1586        if (Idx->getType()->isSigned())
1587          IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1588        else
1589          IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1590      } else if (IdxN.getValueType() > N.getValueType())
1591        IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1592
1593      // If this is a multiply by a power of two, turn it into a shl
1594      // immediately.  This is a very common case.
1595      if (isPowerOf2_64(ElementSize)) {
1596        unsigned Amt = Log2_64(ElementSize);
1597        IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1598                           DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1599        N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1600        continue;
1601      }
1602
1603      SDOperand Scale = getIntPtrConstant(ElementSize);
1604      IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1605      N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1606    }
1607  }
1608  setValue(&I, N);
1609}
1610
1611void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1612  // If this is a fixed sized alloca in the entry block of the function,
1613  // allocate it statically on the stack.
1614  if (FuncInfo.StaticAllocaMap.count(&I))
1615    return;   // getValue will auto-populate this.
1616
1617  const Type *Ty = I.getAllocatedType();
1618  uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1619  unsigned Align = std::max((unsigned)TLI.getTargetData()->getTypeAlignment(Ty),
1620                            I.getAlignment());
1621
1622  SDOperand AllocSize = getValue(I.getArraySize());
1623  MVT::ValueType IntPtr = TLI.getPointerTy();
1624  if (IntPtr < AllocSize.getValueType())
1625    AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1626  else if (IntPtr > AllocSize.getValueType())
1627    AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1628
1629  AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1630                          getIntPtrConstant(TySize));
1631
1632  // Handle alignment.  If the requested alignment is less than or equal to the
1633  // stack alignment, ignore it and round the size of the allocation up to the
1634  // stack alignment size.  If the size is greater than the stack alignment, we
1635  // note this in the DYNAMIC_STACKALLOC node.
1636  unsigned StackAlign =
1637    TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1638  if (Align <= StackAlign) {
1639    Align = 0;
1640    // Add SA-1 to the size.
1641    AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1642                            getIntPtrConstant(StackAlign-1));
1643    // Mask out the low bits for alignment purposes.
1644    AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1645                            getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1646  }
1647
1648  SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
1649  const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1650                                                    MVT::Other);
1651  SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
1652  DAG.setRoot(setValue(&I, DSA).getValue(1));
1653
1654  // Inform the Frame Information that we have just allocated a variable-sized
1655  // object.
1656  CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1657}
1658
1659void SelectionDAGLowering::visitLoad(LoadInst &I) {
1660  SDOperand Ptr = getValue(I.getOperand(0));
1661
1662  SDOperand Root;
1663  if (I.isVolatile())
1664    Root = getRoot();
1665  else {
1666    // Do not serialize non-volatile loads against each other.
1667    Root = DAG.getRoot();
1668  }
1669
1670  setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
1671                           Root, I.isVolatile()));
1672}
1673
1674SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1675                                            const Value *SV, SDOperand Root,
1676                                            bool isVolatile) {
1677  SDOperand L;
1678  if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1679    MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1680    L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1681                       DAG.getSrcValue(SV));
1682  } else {
1683    L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, isVolatile);
1684  }
1685
1686  if (isVolatile)
1687    DAG.setRoot(L.getValue(1));
1688  else
1689    PendingLoads.push_back(L.getValue(1));
1690
1691  return L;
1692}
1693
1694
1695void SelectionDAGLowering::visitStore(StoreInst &I) {
1696  Value *SrcV = I.getOperand(0);
1697  SDOperand Src = getValue(SrcV);
1698  SDOperand Ptr = getValue(I.getOperand(1));
1699  DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1),
1700                           I.isVolatile()));
1701}
1702
1703/// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1704/// access memory and has no other side effects at all.
1705static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1706#define GET_NO_MEMORY_INTRINSICS
1707#include "llvm/Intrinsics.gen"
1708#undef GET_NO_MEMORY_INTRINSICS
1709  return false;
1710}
1711
1712// IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1713// have any side-effects or if it only reads memory.
1714static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1715#define GET_SIDE_EFFECT_INFO
1716#include "llvm/Intrinsics.gen"
1717#undef GET_SIDE_EFFECT_INFO
1718  return false;
1719}
1720
1721/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1722/// node.
1723void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
1724                                                unsigned Intrinsic) {
1725  bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1726  bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1727
1728  // Build the operand list.
1729  SmallVector<SDOperand, 8> Ops;
1730  if (HasChain) {  // If this intrinsic has side-effects, chainify it.
1731    if (OnlyLoad) {
1732      // We don't need to serialize loads against other loads.
1733      Ops.push_back(DAG.getRoot());
1734    } else {
1735      Ops.push_back(getRoot());
1736    }
1737  }
1738
1739  // Add the intrinsic ID as an integer operand.
1740  Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1741
1742  // Add all operands of the call to the operand list.
1743  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1744    SDOperand Op = getValue(I.getOperand(i));
1745
1746    // If this is a vector type, force it to the right packed type.
1747    if (Op.getValueType() == MVT::Vector) {
1748      const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1749      MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1750
1751      MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1752      assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1753      Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1754    }
1755
1756    assert(TLI.isTypeLegal(Op.getValueType()) &&
1757           "Intrinsic uses a non-legal type?");
1758    Ops.push_back(Op);
1759  }
1760
1761  std::vector<MVT::ValueType> VTs;
1762  if (I.getType() != Type::VoidTy) {
1763    MVT::ValueType VT = TLI.getValueType(I.getType());
1764    if (VT == MVT::Vector) {
1765      const PackedType *DestTy = cast<PackedType>(I.getType());
1766      MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1767
1768      VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1769      assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1770    }
1771
1772    assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1773    VTs.push_back(VT);
1774  }
1775  if (HasChain)
1776    VTs.push_back(MVT::Other);
1777
1778  const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1779
1780  // Create the node.
1781  SDOperand Result;
1782  if (!HasChain)
1783    Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1784                         &Ops[0], Ops.size());
1785  else if (I.getType() != Type::VoidTy)
1786    Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1787                         &Ops[0], Ops.size());
1788  else
1789    Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1790                         &Ops[0], Ops.size());
1791
1792  if (HasChain) {
1793    SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1794    if (OnlyLoad)
1795      PendingLoads.push_back(Chain);
1796    else
1797      DAG.setRoot(Chain);
1798  }
1799  if (I.getType() != Type::VoidTy) {
1800    if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1801      MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1802      Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1803                           DAG.getConstant(PTy->getNumElements(), MVT::i32),
1804                           DAG.getValueType(EVT));
1805    }
1806    setValue(&I, Result);
1807  }
1808}
1809
1810/// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
1811/// we want to emit this as a call to a named external function, return the name
1812/// otherwise lower it and return null.
1813const char *
1814SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1815  switch (Intrinsic) {
1816  default:
1817    // By default, turn this into a target intrinsic node.
1818    visitTargetIntrinsic(I, Intrinsic);
1819    return 0;
1820  case Intrinsic::vastart:  visitVAStart(I); return 0;
1821  case Intrinsic::vaend:    visitVAEnd(I); return 0;
1822  case Intrinsic::vacopy:   visitVACopy(I); return 0;
1823  case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1824  case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
1825  case Intrinsic::setjmp:
1826    return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1827    break;
1828  case Intrinsic::longjmp:
1829    return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1830    break;
1831  case Intrinsic::memcpy_i32:
1832  case Intrinsic::memcpy_i64:
1833    visitMemIntrinsic(I, ISD::MEMCPY);
1834    return 0;
1835  case Intrinsic::memset_i32:
1836  case Intrinsic::memset_i64:
1837    visitMemIntrinsic(I, ISD::MEMSET);
1838    return 0;
1839  case Intrinsic::memmove_i32:
1840  case Intrinsic::memmove_i64:
1841    visitMemIntrinsic(I, ISD::MEMMOVE);
1842    return 0;
1843
1844  case Intrinsic::dbg_stoppoint: {
1845    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1846    DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1847    if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1848      SDOperand Ops[5];
1849
1850      Ops[0] = getRoot();
1851      Ops[1] = getValue(SPI.getLineValue());
1852      Ops[2] = getValue(SPI.getColumnValue());
1853
1854      DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1855      assert(DD && "Not a debug information descriptor");
1856      CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1857
1858      Ops[3] = DAG.getString(CompileUnit->getFileName());
1859      Ops[4] = DAG.getString(CompileUnit->getDirectory());
1860
1861      DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
1862    }
1863
1864    return 0;
1865  }
1866  case Intrinsic::dbg_region_start: {
1867    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1868    DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1869    if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1870      unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1871      DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, getRoot(),
1872                              DAG.getConstant(LabelID, MVT::i32)));
1873    }
1874
1875    return 0;
1876  }
1877  case Intrinsic::dbg_region_end: {
1878    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1879    DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1880    if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1881      unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1882      DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1883                              getRoot(), DAG.getConstant(LabelID, MVT::i32)));
1884    }
1885
1886    return 0;
1887  }
1888  case Intrinsic::dbg_func_start: {
1889    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1890    DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1891    if (DebugInfo && FSI.getSubprogram() &&
1892        DebugInfo->Verify(FSI.getSubprogram())) {
1893      unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1894      DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other,
1895                  getRoot(), DAG.getConstant(LabelID, MVT::i32)));
1896    }
1897
1898    return 0;
1899  }
1900  case Intrinsic::dbg_declare: {
1901    MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1902    DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1903    if (DebugInfo && DI.getVariable() && DebugInfo->Verify(DI.getVariable())) {
1904      SDOperand AddressOp  = getValue(DI.getAddress());
1905      if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
1906        DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1907    }
1908
1909    return 0;
1910  }
1911
1912  case Intrinsic::isunordered_f32:
1913  case Intrinsic::isunordered_f64:
1914    setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1915                              getValue(I.getOperand(2)), ISD::SETUO));
1916    return 0;
1917
1918  case Intrinsic::sqrt_f32:
1919  case Intrinsic::sqrt_f64:
1920    setValue(&I, DAG.getNode(ISD::FSQRT,
1921                             getValue(I.getOperand(1)).getValueType(),
1922                             getValue(I.getOperand(1))));
1923    return 0;
1924  case Intrinsic::powi_f32:
1925  case Intrinsic::powi_f64:
1926    setValue(&I, DAG.getNode(ISD::FPOWI,
1927                             getValue(I.getOperand(1)).getValueType(),
1928                             getValue(I.getOperand(1)),
1929                             getValue(I.getOperand(2))));
1930    return 0;
1931  case Intrinsic::pcmarker: {
1932    SDOperand Tmp = getValue(I.getOperand(1));
1933    DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1934    return 0;
1935  }
1936  case Intrinsic::readcyclecounter: {
1937    SDOperand Op = getRoot();
1938    SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
1939                                DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
1940                                &Op, 1);
1941    setValue(&I, Tmp);
1942    DAG.setRoot(Tmp.getValue(1));
1943    return 0;
1944  }
1945  case Intrinsic::bswap_i16:
1946  case Intrinsic::bswap_i32:
1947  case Intrinsic::bswap_i64:
1948    setValue(&I, DAG.getNode(ISD::BSWAP,
1949                             getValue(I.getOperand(1)).getValueType(),
1950                             getValue(I.getOperand(1))));
1951    return 0;
1952  case Intrinsic::cttz_i8:
1953  case Intrinsic::cttz_i16:
1954  case Intrinsic::cttz_i32:
1955  case Intrinsic::cttz_i64:
1956    setValue(&I, DAG.getNode(ISD::CTTZ,
1957                             getValue(I.getOperand(1)).getValueType(),
1958                             getValue(I.getOperand(1))));
1959    return 0;
1960  case Intrinsic::ctlz_i8:
1961  case Intrinsic::ctlz_i16:
1962  case Intrinsic::ctlz_i32:
1963  case Intrinsic::ctlz_i64:
1964    setValue(&I, DAG.getNode(ISD::CTLZ,
1965                             getValue(I.getOperand(1)).getValueType(),
1966                             getValue(I.getOperand(1))));
1967    return 0;
1968  case Intrinsic::ctpop_i8:
1969  case Intrinsic::ctpop_i16:
1970  case Intrinsic::ctpop_i32:
1971  case Intrinsic::ctpop_i64:
1972    setValue(&I, DAG.getNode(ISD::CTPOP,
1973                             getValue(I.getOperand(1)).getValueType(),
1974                             getValue(I.getOperand(1))));
1975    return 0;
1976  case Intrinsic::stacksave: {
1977    SDOperand Op = getRoot();
1978    SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
1979              DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
1980    setValue(&I, Tmp);
1981    DAG.setRoot(Tmp.getValue(1));
1982    return 0;
1983  }
1984  case Intrinsic::stackrestore: {
1985    SDOperand Tmp = getValue(I.getOperand(1));
1986    DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1987    return 0;
1988  }
1989  case Intrinsic::prefetch:
1990    // FIXME: Currently discarding prefetches.
1991    return 0;
1992  }
1993}
1994
1995
1996void SelectionDAGLowering::visitCall(CallInst &I) {
1997  const char *RenameFn = 0;
1998  if (Function *F = I.getCalledFunction()) {
1999    if (F->isExternal())
2000      if (unsigned IID = F->getIntrinsicID()) {
2001        RenameFn = visitIntrinsicCall(I, IID);
2002        if (!RenameFn)
2003          return;
2004      } else {    // Not an LLVM intrinsic.
2005        const std::string &Name = F->getName();
2006        if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2007          if (I.getNumOperands() == 3 &&   // Basic sanity checks.
2008              I.getOperand(1)->getType()->isFloatingPoint() &&
2009              I.getType() == I.getOperand(1)->getType() &&
2010              I.getType() == I.getOperand(2)->getType()) {
2011            SDOperand LHS = getValue(I.getOperand(1));
2012            SDOperand RHS = getValue(I.getOperand(2));
2013            setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2014                                     LHS, RHS));
2015            return;
2016          }
2017        } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2018          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
2019              I.getOperand(1)->getType()->isFloatingPoint() &&
2020              I.getType() == I.getOperand(1)->getType()) {
2021            SDOperand Tmp = getValue(I.getOperand(1));
2022            setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2023            return;
2024          }
2025        } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2026          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
2027              I.getOperand(1)->getType()->isFloatingPoint() &&
2028              I.getType() == I.getOperand(1)->getType()) {
2029            SDOperand Tmp = getValue(I.getOperand(1));
2030            setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2031            return;
2032          }
2033        } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2034          if (I.getNumOperands() == 2 &&   // Basic sanity checks.
2035              I.getOperand(1)->getType()->isFloatingPoint() &&
2036              I.getType() == I.getOperand(1)->getType()) {
2037            SDOperand Tmp = getValue(I.getOperand(1));
2038            setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2039            return;
2040          }
2041        }
2042      }
2043  } else if (isa<InlineAsm>(I.getOperand(0))) {
2044    visitInlineAsm(I);
2045    return;
2046  }
2047
2048  SDOperand Callee;
2049  if (!RenameFn)
2050    Callee = getValue(I.getOperand(0));
2051  else
2052    Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2053  std::vector<std::pair<SDOperand, const Type*> > Args;
2054  Args.reserve(I.getNumOperands());
2055  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2056    Value *Arg = I.getOperand(i);
2057    SDOperand ArgNode = getValue(Arg);
2058    Args.push_back(std::make_pair(ArgNode, Arg->getType()));
2059  }
2060
2061  const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2062  const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2063
2064  std::pair<SDOperand,SDOperand> Result =
2065    TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
2066                    I.isTailCall(), Callee, Args, DAG);
2067  if (I.getType() != Type::VoidTy)
2068    setValue(&I, Result.first);
2069  DAG.setRoot(Result.second);
2070}
2071
2072SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2073                                        SDOperand &Chain, SDOperand &Flag)const{
2074  SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2075  Chain = Val.getValue(1);
2076  Flag  = Val.getValue(2);
2077
2078  // If the result was expanded, copy from the top part.
2079  if (Regs.size() > 1) {
2080    assert(Regs.size() == 2 &&
2081           "Cannot expand to more than 2 elts yet!");
2082    SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2083    Chain = Hi.getValue(1);
2084    Flag  = Hi.getValue(2);
2085    if (DAG.getTargetLoweringInfo().isLittleEndian())
2086      return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2087    else
2088      return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2089  }
2090
2091  // Otherwise, if the return value was promoted or extended, truncate it to the
2092  // appropriate type.
2093  if (RegVT == ValueVT)
2094    return Val;
2095
2096  if (MVT::isInteger(RegVT)) {
2097    if (ValueVT < RegVT)
2098      return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2099    else
2100      return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2101  } else {
2102    return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2103  }
2104}
2105
2106/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2107/// specified value into the registers specified by this object.  This uses
2108/// Chain/Flag as the input and updates them for the output Chain/Flag.
2109void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2110                                 SDOperand &Chain, SDOperand &Flag,
2111                                 MVT::ValueType PtrVT) const {
2112  if (Regs.size() == 1) {
2113    // If there is a single register and the types differ, this must be
2114    // a promotion.
2115    if (RegVT != ValueVT) {
2116      if (MVT::isInteger(RegVT)) {
2117        if (RegVT < ValueVT)
2118          Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2119        else
2120          Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2121      } else
2122        Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2123    }
2124    Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2125    Flag = Chain.getValue(1);
2126  } else {
2127    std::vector<unsigned> R(Regs);
2128    if (!DAG.getTargetLoweringInfo().isLittleEndian())
2129      std::reverse(R.begin(), R.end());
2130
2131    for (unsigned i = 0, e = R.size(); i != e; ++i) {
2132      SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val,
2133                                   DAG.getConstant(i, PtrVT));
2134      Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2135      Flag = Chain.getValue(1);
2136    }
2137  }
2138}
2139
2140/// AddInlineAsmOperands - Add this value to the specified inlineasm node
2141/// operand list.  This adds the code marker and includes the number of
2142/// values added into it.
2143void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2144                                        std::vector<SDOperand> &Ops) const {
2145  Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2146  for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2147    Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2148}
2149
2150/// isAllocatableRegister - If the specified register is safe to allocate,
2151/// i.e. it isn't a stack pointer or some other special register, return the
2152/// register class for the register.  Otherwise, return null.
2153static const TargetRegisterClass *
2154isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2155                      const TargetLowering &TLI, const MRegisterInfo *MRI) {
2156  MVT::ValueType FoundVT = MVT::Other;
2157  const TargetRegisterClass *FoundRC = 0;
2158  for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2159       E = MRI->regclass_end(); RCI != E; ++RCI) {
2160    MVT::ValueType ThisVT = MVT::Other;
2161
2162    const TargetRegisterClass *RC = *RCI;
2163    // If none of the the value types for this register class are valid, we
2164    // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2165    for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2166         I != E; ++I) {
2167      if (TLI.isTypeLegal(*I)) {
2168        // If we have already found this register in a different register class,
2169        // choose the one with the largest VT specified.  For example, on
2170        // PowerPC, we favor f64 register classes over f32.
2171        if (FoundVT == MVT::Other ||
2172            MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2173          ThisVT = *I;
2174          break;
2175        }
2176      }
2177    }
2178
2179    if (ThisVT == MVT::Other) continue;
2180
2181    // NOTE: This isn't ideal.  In particular, this might allocate the
2182    // frame pointer in functions that need it (due to them not being taken
2183    // out of allocation, because a variable sized allocation hasn't been seen
2184    // yet).  This is a slight code pessimization, but should still work.
2185    for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2186         E = RC->allocation_order_end(MF); I != E; ++I)
2187      if (*I == Reg) {
2188        // We found a matching register class.  Keep looking at others in case
2189        // we find one with larger registers that this physreg is also in.
2190        FoundRC = RC;
2191        FoundVT = ThisVT;
2192        break;
2193      }
2194  }
2195  return FoundRC;
2196}
2197
2198RegsForValue SelectionDAGLowering::
2199GetRegistersForValue(const std::string &ConstrCode,
2200                     MVT::ValueType VT, bool isOutReg, bool isInReg,
2201                     std::set<unsigned> &OutputRegs,
2202                     std::set<unsigned> &InputRegs) {
2203  std::pair<unsigned, const TargetRegisterClass*> PhysReg =
2204    TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2205  std::vector<unsigned> Regs;
2206
2207  unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2208  MVT::ValueType RegVT;
2209  MVT::ValueType ValueVT = VT;
2210
2211  if (PhysReg.first) {
2212    if (VT == MVT::Other)
2213      ValueVT = *PhysReg.second->vt_begin();
2214
2215    // Get the actual register value type.  This is important, because the user
2216    // may have asked for (e.g.) the AX register in i32 type.  We need to
2217    // remember that AX is actually i16 to get the right extension.
2218    RegVT = *PhysReg.second->vt_begin();
2219
2220    // This is a explicit reference to a physical register.
2221    Regs.push_back(PhysReg.first);
2222
2223    // If this is an expanded reference, add the rest of the regs to Regs.
2224    if (NumRegs != 1) {
2225      TargetRegisterClass::iterator I = PhysReg.second->begin();
2226      TargetRegisterClass::iterator E = PhysReg.second->end();
2227      for (; *I != PhysReg.first; ++I)
2228        assert(I != E && "Didn't find reg!");
2229
2230      // Already added the first reg.
2231      --NumRegs; ++I;
2232      for (; NumRegs; --NumRegs, ++I) {
2233        assert(I != E && "Ran out of registers to allocate!");
2234        Regs.push_back(*I);
2235      }
2236    }
2237    return RegsForValue(Regs, RegVT, ValueVT);
2238  }
2239
2240  // This is a reference to a register class.  Allocate NumRegs consecutive,
2241  // available, registers from the class.
2242  std::vector<unsigned> RegClassRegs =
2243    TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2244
2245  const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2246  MachineFunction &MF = *CurMBB->getParent();
2247  unsigned NumAllocated = 0;
2248  for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2249    unsigned Reg = RegClassRegs[i];
2250    // See if this register is available.
2251    if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
2252        (isInReg  && InputRegs.count(Reg))) {    // Already used.
2253      // Make sure we find consecutive registers.
2254      NumAllocated = 0;
2255      continue;
2256    }
2257
2258    // Check to see if this register is allocatable (i.e. don't give out the
2259    // stack pointer).
2260    const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
2261    if (!RC) {
2262      // Make sure we find consecutive registers.
2263      NumAllocated = 0;
2264      continue;
2265    }
2266
2267    // Okay, this register is good, we can use it.
2268    ++NumAllocated;
2269
2270    // If we allocated enough consecutive
2271    if (NumAllocated == NumRegs) {
2272      unsigned RegStart = (i-NumAllocated)+1;
2273      unsigned RegEnd   = i+1;
2274      // Mark all of the allocated registers used.
2275      for (unsigned i = RegStart; i != RegEnd; ++i) {
2276        unsigned Reg = RegClassRegs[i];
2277        Regs.push_back(Reg);
2278        if (isOutReg) OutputRegs.insert(Reg);    // Mark reg used.
2279        if (isInReg)  InputRegs.insert(Reg);     // Mark reg used.
2280      }
2281
2282      return RegsForValue(Regs, *RC->vt_begin(), VT);
2283    }
2284  }
2285
2286  // Otherwise, we couldn't allocate enough registers for this.
2287  return RegsForValue();
2288}
2289
2290
2291/// visitInlineAsm - Handle a call to an InlineAsm object.
2292///
2293void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2294  InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2295
2296  SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2297                                                 MVT::Other);
2298
2299  // Note, we treat inline asms both with and without side-effects as the same.
2300  // If an inline asm doesn't have side effects and doesn't access memory, we
2301  // could not choose to not chain it.
2302  bool hasSideEffects = IA->hasSideEffects();
2303
2304  std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
2305  std::vector<MVT::ValueType> ConstraintVTs;
2306
2307  /// AsmNodeOperands - A list of pairs.  The first element is a register, the
2308  /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2309  /// if it is a def of that register.
2310  std::vector<SDOperand> AsmNodeOperands;
2311  AsmNodeOperands.push_back(SDOperand());  // reserve space for input chain
2312  AsmNodeOperands.push_back(AsmStr);
2313
2314  SDOperand Chain = getRoot();
2315  SDOperand Flag;
2316
2317  // We fully assign registers here at isel time.  This is not optimal, but
2318  // should work.  For register classes that correspond to LLVM classes, we
2319  // could let the LLVM RA do its thing, but we currently don't.  Do a prepass
2320  // over the constraints, collecting fixed registers that we know we can't use.
2321  std::set<unsigned> OutputRegs, InputRegs;
2322  unsigned OpNum = 1;
2323  for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2324    assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2325    std::string &ConstraintCode = Constraints[i].Codes[0];
2326
2327    MVT::ValueType OpVT;
2328
2329    // Compute the value type for each operand and add it to ConstraintVTs.
2330    switch (Constraints[i].Type) {
2331    case InlineAsm::isOutput:
2332      if (!Constraints[i].isIndirectOutput) {
2333        assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2334        OpVT = TLI.getValueType(I.getType());
2335      } else {
2336        const Type *OpTy = I.getOperand(OpNum)->getType();
2337        OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2338        OpNum++;  // Consumes a call operand.
2339      }
2340      break;
2341    case InlineAsm::isInput:
2342      OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2343      OpNum++;  // Consumes a call operand.
2344      break;
2345    case InlineAsm::isClobber:
2346      OpVT = MVT::Other;
2347      break;
2348    }
2349
2350    ConstraintVTs.push_back(OpVT);
2351
2352    if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2353      continue;  // Not assigned a fixed reg.
2354
2355    // Build a list of regs that this operand uses.  This always has a single
2356    // element for promoted/expanded operands.
2357    RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2358                                             false, false,
2359                                             OutputRegs, InputRegs);
2360
2361    switch (Constraints[i].Type) {
2362    case InlineAsm::isOutput:
2363      // We can't assign any other output to this register.
2364      OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2365      // If this is an early-clobber output, it cannot be assigned to the same
2366      // value as the input reg.
2367      if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2368        InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2369      break;
2370    case InlineAsm::isInput:
2371      // We can't assign any other input to this register.
2372      InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2373      break;
2374    case InlineAsm::isClobber:
2375      // Clobbered regs cannot be used as inputs or outputs.
2376      InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2377      OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2378      break;
2379    }
2380  }
2381
2382  // Loop over all of the inputs, copying the operand values into the
2383  // appropriate registers and processing the output regs.
2384  RegsForValue RetValRegs;
2385  std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2386  OpNum = 1;
2387
2388  for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2389    assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2390    std::string &ConstraintCode = Constraints[i].Codes[0];
2391
2392    switch (Constraints[i].Type) {
2393    case InlineAsm::isOutput: {
2394      TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2395      if (ConstraintCode.size() == 1)   // not a physreg name.
2396        CTy = TLI.getConstraintType(ConstraintCode[0]);
2397
2398      if (CTy == TargetLowering::C_Memory) {
2399        // Memory output.
2400        SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2401
2402        // Check that the operand (the address to store to) isn't a float.
2403        if (!MVT::isInteger(InOperandVal.getValueType()))
2404          assert(0 && "MATCH FAIL!");
2405
2406        if (!Constraints[i].isIndirectOutput)
2407          assert(0 && "MATCH FAIL!");
2408
2409        OpNum++;  // Consumes a call operand.
2410
2411        // Extend/truncate to the right pointer type if needed.
2412        MVT::ValueType PtrType = TLI.getPointerTy();
2413        if (InOperandVal.getValueType() < PtrType)
2414          InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2415        else if (InOperandVal.getValueType() > PtrType)
2416          InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2417
2418        // Add information to the INLINEASM node to know about this output.
2419        unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2420        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2421        AsmNodeOperands.push_back(InOperandVal);
2422        break;
2423      }
2424
2425      // Otherwise, this is a register output.
2426      assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2427
2428      // If this is an early-clobber output, or if there is an input
2429      // constraint that matches this, we need to reserve the input register
2430      // so no other inputs allocate to it.
2431      bool UsesInputRegister = false;
2432      if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2433        UsesInputRegister = true;
2434
2435      // Copy the output from the appropriate register.  Find a register that
2436      // we can use.
2437      RegsForValue Regs =
2438        GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2439                             true, UsesInputRegister,
2440                             OutputRegs, InputRegs);
2441      assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
2442
2443      if (!Constraints[i].isIndirectOutput) {
2444        assert(RetValRegs.Regs.empty() &&
2445               "Cannot have multiple output constraints yet!");
2446        assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2447        RetValRegs = Regs;
2448      } else {
2449        IndirectStoresToEmit.push_back(std::make_pair(Regs,
2450                                                      I.getOperand(OpNum)));
2451        OpNum++;  // Consumes a call operand.
2452      }
2453
2454      // Add information to the INLINEASM node to know that this register is
2455      // set.
2456      Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2457      break;
2458    }
2459    case InlineAsm::isInput: {
2460      SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2461      OpNum++;  // Consumes a call operand.
2462
2463      if (isdigit(ConstraintCode[0])) {    // Matching constraint?
2464        // If this is required to match an output register we have already set,
2465        // just use its register.
2466        unsigned OperandNo = atoi(ConstraintCode.c_str());
2467
2468        // Scan until we find the definition we already emitted of this operand.
2469        // When we find it, create a RegsForValue operand.
2470        unsigned CurOp = 2;  // The first operand.
2471        for (; OperandNo; --OperandNo) {
2472          // Advance to the next operand.
2473          unsigned NumOps =
2474            cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2475          assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2476                  (NumOps & 7) == 4 /*MEM*/) &&
2477                 "Skipped past definitions?");
2478          CurOp += (NumOps>>3)+1;
2479        }
2480
2481        unsigned NumOps =
2482          cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2483        assert((NumOps & 7) == 2 /*REGDEF*/ &&
2484               "Skipped past definitions?");
2485
2486        // Add NumOps>>3 registers to MatchedRegs.
2487        RegsForValue MatchedRegs;
2488        MatchedRegs.ValueVT = InOperandVal.getValueType();
2489        MatchedRegs.RegVT   = AsmNodeOperands[CurOp+1].getValueType();
2490        for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2491          unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2492          MatchedRegs.Regs.push_back(Reg);
2493        }
2494
2495        // Use the produced MatchedRegs object to
2496        MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2497                                  TLI.getPointerTy());
2498        MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2499        break;
2500      }
2501
2502      TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2503      if (ConstraintCode.size() == 1)   // not a physreg name.
2504        CTy = TLI.getConstraintType(ConstraintCode[0]);
2505
2506      if (CTy == TargetLowering::C_Other) {
2507        if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
2508          assert(0 && "MATCH FAIL!");
2509
2510        // Add information to the INLINEASM node to know about this input.
2511        unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2512        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2513        AsmNodeOperands.push_back(InOperandVal);
2514        break;
2515      } else if (CTy == TargetLowering::C_Memory) {
2516        // Memory input.
2517
2518        // Check that the operand isn't a float.
2519        if (!MVT::isInteger(InOperandVal.getValueType()))
2520          assert(0 && "MATCH FAIL!");
2521
2522        // Extend/truncate to the right pointer type if needed.
2523        MVT::ValueType PtrType = TLI.getPointerTy();
2524        if (InOperandVal.getValueType() < PtrType)
2525          InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2526        else if (InOperandVal.getValueType() > PtrType)
2527          InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2528
2529        // Add information to the INLINEASM node to know about this input.
2530        unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2531        AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2532        AsmNodeOperands.push_back(InOperandVal);
2533        break;
2534      }
2535
2536      assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2537
2538      // Copy the input into the appropriate registers.
2539      RegsForValue InRegs =
2540        GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2541                             false, true, OutputRegs, InputRegs);
2542      // FIXME: should be match fail.
2543      assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2544
2545      InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2546
2547      InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2548      break;
2549    }
2550    case InlineAsm::isClobber: {
2551      RegsForValue ClobberedRegs =
2552        GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2553                             OutputRegs, InputRegs);
2554      // Add the clobbered value to the operand list, so that the register
2555      // allocator is aware that the physreg got clobbered.
2556      if (!ClobberedRegs.Regs.empty())
2557        ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2558      break;
2559    }
2560    }
2561  }
2562
2563  // Finish up input operands.
2564  AsmNodeOperands[0] = Chain;
2565  if (Flag.Val) AsmNodeOperands.push_back(Flag);
2566
2567  Chain = DAG.getNode(ISD::INLINEASM,
2568                      DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
2569                      &AsmNodeOperands[0], AsmNodeOperands.size());
2570  Flag = Chain.getValue(1);
2571
2572  // If this asm returns a register value, copy the result from that register
2573  // and set it as the value of the call.
2574  if (!RetValRegs.Regs.empty())
2575    setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2576
2577  std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2578
2579  // Process indirect outputs, first output all of the flagged copies out of
2580  // physregs.
2581  for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2582    RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2583    Value *Ptr = IndirectStoresToEmit[i].second;
2584    SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2585    StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2586  }
2587
2588  // Emit the non-flagged stores from the physregs.
2589  SmallVector<SDOperand, 8> OutChains;
2590  for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2591    OutChains.push_back(DAG.getStore(Chain,  StoresToEmit[i].first,
2592                                    getValue(StoresToEmit[i].second),
2593                                    StoresToEmit[i].second, 0));
2594  if (!OutChains.empty())
2595    Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2596                        &OutChains[0], OutChains.size());
2597  DAG.setRoot(Chain);
2598}
2599
2600
2601void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2602  SDOperand Src = getValue(I.getOperand(0));
2603
2604  MVT::ValueType IntPtr = TLI.getPointerTy();
2605
2606  if (IntPtr < Src.getValueType())
2607    Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2608  else if (IntPtr > Src.getValueType())
2609    Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2610
2611  // Scale the source by the type size.
2612  uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2613  Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2614                    Src, getIntPtrConstant(ElementSize));
2615
2616  std::vector<std::pair<SDOperand, const Type*> > Args;
2617  Args.push_back(std::make_pair(Src, TLI.getTargetData()->getIntPtrType()));
2618
2619  std::pair<SDOperand,SDOperand> Result =
2620    TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2621                    DAG.getExternalSymbol("malloc", IntPtr),
2622                    Args, DAG);
2623  setValue(&I, Result.first);  // Pointers always fit in registers
2624  DAG.setRoot(Result.second);
2625}
2626
2627void SelectionDAGLowering::visitFree(FreeInst &I) {
2628  std::vector<std::pair<SDOperand, const Type*> > Args;
2629  Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2630                                TLI.getTargetData()->getIntPtrType()));
2631  MVT::ValueType IntPtr = TLI.getPointerTy();
2632  std::pair<SDOperand,SDOperand> Result =
2633    TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2634                    DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2635  DAG.setRoot(Result.second);
2636}
2637
2638// InsertAtEndOfBasicBlock - This method should be implemented by targets that
2639// mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
2640// instructions are special in various ways, which require special support to
2641// insert.  The specified MachineInstr is created but not inserted into any
2642// basic blocks, and the scheduler passes ownership of it to this method.
2643MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2644                                                       MachineBasicBlock *MBB) {
2645  std::cerr << "If a target marks an instruction with "
2646               "'usesCustomDAGSchedInserter', it must implement "
2647               "TargetLowering::InsertAtEndOfBasicBlock!\n";
2648  abort();
2649  return 0;
2650}
2651
2652void SelectionDAGLowering::visitVAStart(CallInst &I) {
2653  DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
2654                          getValue(I.getOperand(1)),
2655                          DAG.getSrcValue(I.getOperand(1))));
2656}
2657
2658void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2659  SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2660                             getValue(I.getOperand(0)),
2661                             DAG.getSrcValue(I.getOperand(0)));
2662  setValue(&I, V);
2663  DAG.setRoot(V.getValue(1));
2664}
2665
2666void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2667  DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2668                          getValue(I.getOperand(1)),
2669                          DAG.getSrcValue(I.getOperand(1))));
2670}
2671
2672void SelectionDAGLowering::visitVACopy(CallInst &I) {
2673  DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
2674                          getValue(I.getOperand(1)),
2675                          getValue(I.getOperand(2)),
2676                          DAG.getSrcValue(I.getOperand(1)),
2677                          DAG.getSrcValue(I.getOperand(2))));
2678}
2679
2680/// TargetLowering::LowerArguments - This is the default LowerArguments
2681/// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
2682/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
2683/// integrated into SDISel.
2684std::vector<SDOperand>
2685TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2686  // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2687  std::vector<SDOperand> Ops;
2688  Ops.push_back(DAG.getRoot());
2689  Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2690  Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2691
2692  // Add one result value for each formal argument.
2693  std::vector<MVT::ValueType> RetVals;
2694  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2695    MVT::ValueType VT = getValueType(I->getType());
2696
2697    switch (getTypeAction(VT)) {
2698    default: assert(0 && "Unknown type action!");
2699    case Legal:
2700      RetVals.push_back(VT);
2701      break;
2702    case Promote:
2703      RetVals.push_back(getTypeToTransformTo(VT));
2704      break;
2705    case Expand:
2706      if (VT != MVT::Vector) {
2707        // If this is a large integer, it needs to be broken up into small
2708        // integers.  Figure out what the destination type is and how many small
2709        // integers it turns into.
2710        MVT::ValueType NVT = getTypeToTransformTo(VT);
2711        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2712        for (unsigned i = 0; i != NumVals; ++i)
2713          RetVals.push_back(NVT);
2714      } else {
2715        // Otherwise, this is a vector type.  We only support legal vectors
2716        // right now.
2717        unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2718        const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2719
2720        // Figure out if there is a Packed type corresponding to this Vector
2721        // type.  If so, convert to the packed type.
2722        MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2723        if (TVT != MVT::Other && isTypeLegal(TVT)) {
2724          RetVals.push_back(TVT);
2725        } else {
2726          assert(0 && "Don't support illegal by-val vector arguments yet!");
2727        }
2728      }
2729      break;
2730    }
2731  }
2732
2733  RetVals.push_back(MVT::Other);
2734
2735  // Create the node.
2736  SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2737                               DAG.getNodeValueTypes(RetVals), RetVals.size(),
2738                               &Ops[0], Ops.size()).Val;
2739
2740  DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
2741
2742  // Set up the return result vector.
2743  Ops.clear();
2744  unsigned i = 0;
2745  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2746    MVT::ValueType VT = getValueType(I->getType());
2747
2748    switch (getTypeAction(VT)) {
2749    default: assert(0 && "Unknown type action!");
2750    case Legal:
2751      Ops.push_back(SDOperand(Result, i++));
2752      break;
2753    case Promote: {
2754      SDOperand Op(Result, i++);
2755      if (MVT::isInteger(VT)) {
2756        unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext
2757                                                     : ISD::AssertZext;
2758        Op = DAG.getNode(AssertOp, Op.getValueType(), Op, DAG.getValueType(VT));
2759        Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2760      } else {
2761        assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2762        Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2763      }
2764      Ops.push_back(Op);
2765      break;
2766    }
2767    case Expand:
2768      if (VT != MVT::Vector) {
2769        // If this is a large integer, it needs to be reassembled from small
2770        // integers.  Figure out what the source elt type is and how many small
2771        // integers it is.
2772        MVT::ValueType NVT = getTypeToTransformTo(VT);
2773        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2774        if (NumVals == 2) {
2775          SDOperand Lo = SDOperand(Result, i++);
2776          SDOperand Hi = SDOperand(Result, i++);
2777
2778          if (!isLittleEndian())
2779            std::swap(Lo, Hi);
2780
2781          Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi));
2782        } else {
2783          // Value scalarized into many values.  Unimp for now.
2784          assert(0 && "Cannot expand i64 -> i16 yet!");
2785        }
2786      } else {
2787        // Otherwise, this is a vector type.  We only support legal vectors
2788        // right now.
2789        const PackedType *PTy = cast<PackedType>(I->getType());
2790        unsigned NumElems = PTy->getNumElements();
2791        const Type *EltTy = PTy->getElementType();
2792
2793        // Figure out if there is a Packed type corresponding to this Vector
2794        // type.  If so, convert to the packed type.
2795        MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2796        if (TVT != MVT::Other && isTypeLegal(TVT)) {
2797          SDOperand N = SDOperand(Result, i++);
2798          // Handle copies from generic vectors to registers.
2799          N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2800                          DAG.getConstant(NumElems, MVT::i32),
2801                          DAG.getValueType(getValueType(EltTy)));
2802          Ops.push_back(N);
2803        } else {
2804          assert(0 && "Don't support illegal by-val vector arguments yet!");
2805          abort();
2806        }
2807      }
2808      break;
2809    }
2810  }
2811  return Ops;
2812}
2813
2814
2815/// TargetLowering::LowerCallTo - This is the default LowerCallTo
2816/// implementation, which just inserts an ISD::CALL node, which is later custom
2817/// lowered by the target to something concrete.  FIXME: When all targets are
2818/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
2819std::pair<SDOperand, SDOperand>
2820TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
2821                            unsigned CallingConv, bool isTailCall,
2822                            SDOperand Callee,
2823                            ArgListTy &Args, SelectionDAG &DAG) {
2824  SmallVector<SDOperand, 32> Ops;
2825  Ops.push_back(Chain);   // Op#0 - Chain
2826  Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
2827  Ops.push_back(DAG.getConstant(isVarArg, getPointerTy()));    // Op#2 - VarArg
2828  Ops.push_back(DAG.getConstant(isTailCall, getPointerTy()));  // Op#3 - Tail
2829  Ops.push_back(Callee);
2830
2831  // Handle all of the outgoing arguments.
2832  for (unsigned i = 0, e = Args.size(); i != e; ++i) {
2833    MVT::ValueType VT = getValueType(Args[i].second);
2834    SDOperand Op = Args[i].first;
2835    bool isSigned = Args[i].second->isSigned();
2836    switch (getTypeAction(VT)) {
2837    default: assert(0 && "Unknown type action!");
2838    case Legal:
2839      Ops.push_back(Op);
2840      Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2841      break;
2842    case Promote:
2843      if (MVT::isInteger(VT)) {
2844        unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2845        Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
2846      } else {
2847        assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2848        Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
2849      }
2850      Ops.push_back(Op);
2851      Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2852      break;
2853    case Expand:
2854      if (VT != MVT::Vector) {
2855        // If this is a large integer, it needs to be broken down into small
2856        // integers.  Figure out what the source elt type is and how many small
2857        // integers it is.
2858        MVT::ValueType NVT = getTypeToTransformTo(VT);
2859        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2860        if (NumVals == 2) {
2861          SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2862                                     DAG.getConstant(0, getPointerTy()));
2863          SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, NVT, Op,
2864                                     DAG.getConstant(1, getPointerTy()));
2865          if (!isLittleEndian())
2866            std::swap(Lo, Hi);
2867
2868          Ops.push_back(Lo);
2869          Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2870          Ops.push_back(Hi);
2871          Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2872        } else {
2873          // Value scalarized into many values.  Unimp for now.
2874          assert(0 && "Cannot expand i64 -> i16 yet!");
2875        }
2876      } else {
2877        // Otherwise, this is a vector type.  We only support legal vectors
2878        // right now.
2879        const PackedType *PTy = cast<PackedType>(Args[i].second);
2880        unsigned NumElems = PTy->getNumElements();
2881        const Type *EltTy = PTy->getElementType();
2882
2883        // Figure out if there is a Packed type corresponding to this Vector
2884        // type.  If so, convert to the packed type.
2885        MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2886        if (TVT != MVT::Other && isTypeLegal(TVT)) {
2887          // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
2888          Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
2889          Ops.push_back(Op);
2890          Ops.push_back(DAG.getConstant(isSigned, MVT::i32));
2891        } else {
2892          assert(0 && "Don't support illegal by-val vector call args yet!");
2893          abort();
2894        }
2895      }
2896      break;
2897    }
2898  }
2899
2900  // Figure out the result value types.
2901  SmallVector<MVT::ValueType, 4> RetTys;
2902
2903  if (RetTy != Type::VoidTy) {
2904    MVT::ValueType VT = getValueType(RetTy);
2905    switch (getTypeAction(VT)) {
2906    default: assert(0 && "Unknown type action!");
2907    case Legal:
2908      RetTys.push_back(VT);
2909      break;
2910    case Promote:
2911      RetTys.push_back(getTypeToTransformTo(VT));
2912      break;
2913    case Expand:
2914      if (VT != MVT::Vector) {
2915        // If this is a large integer, it needs to be reassembled from small
2916        // integers.  Figure out what the source elt type is and how many small
2917        // integers it is.
2918        MVT::ValueType NVT = getTypeToTransformTo(VT);
2919        unsigned NumVals = MVT::getSizeInBits(VT)/MVT::getSizeInBits(NVT);
2920        for (unsigned i = 0; i != NumVals; ++i)
2921          RetTys.push_back(NVT);
2922      } else {
2923        // Otherwise, this is a vector type.  We only support legal vectors
2924        // right now.
2925        const PackedType *PTy = cast<PackedType>(RetTy);
2926        unsigned NumElems = PTy->getNumElements();
2927        const Type *EltTy = PTy->getElementType();
2928
2929        // Figure out if there is a Packed type corresponding to this Vector
2930        // type.  If so, convert to the packed type.
2931        MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2932        if (TVT != MVT::Other && isTypeLegal(TVT)) {
2933          RetTys.push_back(TVT);
2934        } else {
2935          assert(0 && "Don't support illegal by-val vector call results yet!");
2936          abort();
2937        }
2938      }
2939    }
2940  }
2941
2942  RetTys.push_back(MVT::Other);  // Always has a chain.
2943
2944  // Finally, create the CALL node.
2945  SDOperand Res = DAG.getNode(ISD::CALL,
2946                              DAG.getVTList(&RetTys[0], RetTys.size()),
2947                              &Ops[0], Ops.size());
2948
2949  // This returns a pair of operands.  The first element is the
2950  // return value for the function (if RetTy is not VoidTy).  The second
2951  // element is the outgoing token chain.
2952  SDOperand ResVal;
2953  if (RetTys.size() != 1) {
2954    MVT::ValueType VT = getValueType(RetTy);
2955    if (RetTys.size() == 2) {
2956      ResVal = Res;
2957
2958      // If this value was promoted, truncate it down.
2959      if (ResVal.getValueType() != VT) {
2960        if (VT == MVT::Vector) {
2961          // Insert a VBITCONVERT to convert from the packed result type to the
2962          // MVT::Vector type.
2963          unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
2964          const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
2965
2966          // Figure out if there is a Packed type corresponding to this Vector
2967          // type.  If so, convert to the packed type.
2968          MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2969          if (TVT != MVT::Other && isTypeLegal(TVT)) {
2970            // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
2971            // "N x PTyElementVT" MVT::Vector type.
2972            ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
2973                                 DAG.getConstant(NumElems, MVT::i32),
2974                                 DAG.getValueType(getValueType(EltTy)));
2975          } else {
2976            abort();
2977          }
2978        } else if (MVT::isInteger(VT)) {
2979          unsigned AssertOp = RetTy->isSigned() ?
2980                                  ISD::AssertSext : ISD::AssertZext;
2981          ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal,
2982                               DAG.getValueType(VT));
2983          ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
2984        } else {
2985          assert(MVT::isFloatingPoint(VT));
2986          ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
2987        }
2988      }
2989    } else if (RetTys.size() == 3) {
2990      ResVal = DAG.getNode(ISD::BUILD_PAIR, VT,
2991                           Res.getValue(0), Res.getValue(1));
2992
2993    } else {
2994      assert(0 && "Case not handled yet!");
2995    }
2996  }
2997
2998  return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
2999}
3000
3001
3002
3003// It is always conservatively correct for llvm.returnaddress and
3004// llvm.frameaddress to return 0.
3005//
3006// FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3007// expanded to 0 if the target wants.
3008std::pair<SDOperand, SDOperand>
3009TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3010                                        unsigned Depth, SelectionDAG &DAG) {
3011  return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
3012}
3013
3014SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3015  assert(0 && "LowerOperation not implemented for this target!");
3016  abort();
3017  return SDOperand();
3018}
3019
3020SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3021                                                 SelectionDAG &DAG) {
3022  assert(0 && "CustomPromoteOperation not implemented for this target!");
3023  abort();
3024  return SDOperand();
3025}
3026
3027void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
3028  unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
3029  std::pair<SDOperand,SDOperand> Result =
3030    TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
3031  setValue(&I, Result.first);
3032  DAG.setRoot(Result.second);
3033}
3034
3035/// getMemsetValue - Vectorized representation of the memset value
3036/// operand.
3037static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
3038                                SelectionDAG &DAG) {
3039  MVT::ValueType CurVT = VT;
3040  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3041    uint64_t Val   = C->getValue() & 255;
3042    unsigned Shift = 8;
3043    while (CurVT != MVT::i8) {
3044      Val = (Val << Shift) | Val;
3045      Shift <<= 1;
3046      CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3047    }
3048    return DAG.getConstant(Val, VT);
3049  } else {
3050    Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3051    unsigned Shift = 8;
3052    while (CurVT != MVT::i8) {
3053      Value =
3054        DAG.getNode(ISD::OR, VT,
3055                    DAG.getNode(ISD::SHL, VT, Value,
3056                                DAG.getConstant(Shift, MVT::i8)), Value);
3057      Shift <<= 1;
3058      CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3059    }
3060
3061    return Value;
3062  }
3063}
3064
3065/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3066/// used when a memcpy is turned into a memset when the source is a constant
3067/// string ptr.
3068static SDOperand getMemsetStringVal(MVT::ValueType VT,
3069                                    SelectionDAG &DAG, TargetLowering &TLI,
3070                                    std::string &Str, unsigned Offset) {
3071  MVT::ValueType CurVT = VT;
3072  uint64_t Val = 0;
3073  unsigned MSB = getSizeInBits(VT) / 8;
3074  if (TLI.isLittleEndian())
3075    Offset = Offset + MSB - 1;
3076  for (unsigned i = 0; i != MSB; ++i) {
3077    Val = (Val << 8) | Str[Offset];
3078    Offset += TLI.isLittleEndian() ? -1 : 1;
3079  }
3080  return DAG.getConstant(Val, VT);
3081}
3082
3083/// getMemBasePlusOffset - Returns base and offset node for the
3084static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3085                                      SelectionDAG &DAG, TargetLowering &TLI) {
3086  MVT::ValueType VT = Base.getValueType();
3087  return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3088}
3089
3090/// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3091/// to replace the memset / memcpy is below the threshold. It also returns the
3092/// types of the sequence of  memory ops to perform memset / memcpy.
3093static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3094                                     unsigned Limit, uint64_t Size,
3095                                     unsigned Align, TargetLowering &TLI) {
3096  MVT::ValueType VT;
3097
3098  if (TLI.allowsUnalignedMemoryAccesses()) {
3099    VT = MVT::i64;
3100  } else {
3101    switch (Align & 7) {
3102    case 0:
3103      VT = MVT::i64;
3104      break;
3105    case 4:
3106      VT = MVT::i32;
3107      break;
3108    case 2:
3109      VT = MVT::i16;
3110      break;
3111    default:
3112      VT = MVT::i8;
3113      break;
3114    }
3115  }
3116
3117  MVT::ValueType LVT = MVT::i64;
3118  while (!TLI.isTypeLegal(LVT))
3119    LVT = (MVT::ValueType)((unsigned)LVT - 1);
3120  assert(MVT::isInteger(LVT));
3121
3122  if (VT > LVT)
3123    VT = LVT;
3124
3125  unsigned NumMemOps = 0;
3126  while (Size != 0) {
3127    unsigned VTSize = getSizeInBits(VT) / 8;
3128    while (VTSize > Size) {
3129      VT = (MVT::ValueType)((unsigned)VT - 1);
3130      VTSize >>= 1;
3131    }
3132    assert(MVT::isInteger(VT));
3133
3134    if (++NumMemOps > Limit)
3135      return false;
3136    MemOps.push_back(VT);
3137    Size -= VTSize;
3138  }
3139
3140  return true;
3141}
3142
3143void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
3144  SDOperand Op1 = getValue(I.getOperand(1));
3145  SDOperand Op2 = getValue(I.getOperand(2));
3146  SDOperand Op3 = getValue(I.getOperand(3));
3147  SDOperand Op4 = getValue(I.getOperand(4));
3148  unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3149  if (Align == 0) Align = 1;
3150
3151  if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3152    std::vector<MVT::ValueType> MemOps;
3153
3154    // Expand memset / memcpy to a series of load / store ops
3155    // if the size operand falls below a certain threshold.
3156    SmallVector<SDOperand, 8> OutChains;
3157    switch (Op) {
3158    default: break;  // Do nothing for now.
3159    case ISD::MEMSET: {
3160      if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3161                                   Size->getValue(), Align, TLI)) {
3162        unsigned NumMemOps = MemOps.size();
3163        unsigned Offset = 0;
3164        for (unsigned i = 0; i < NumMemOps; i++) {
3165          MVT::ValueType VT = MemOps[i];
3166          unsigned VTSize = getSizeInBits(VT) / 8;
3167          SDOperand Value = getMemsetValue(Op2, VT, DAG);
3168          SDOperand Store = DAG.getStore(getRoot(), Value,
3169                                    getMemBasePlusOffset(Op1, Offset, DAG, TLI),
3170                                         I.getOperand(1), Offset);
3171          OutChains.push_back(Store);
3172          Offset += VTSize;
3173        }
3174      }
3175      break;
3176    }
3177    case ISD::MEMCPY: {
3178      if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3179                                   Size->getValue(), Align, TLI)) {
3180        unsigned NumMemOps = MemOps.size();
3181        unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
3182        GlobalAddressSDNode *G = NULL;
3183        std::string Str;
3184        bool CopyFromStr = false;
3185
3186        if (Op2.getOpcode() == ISD::GlobalAddress)
3187          G = cast<GlobalAddressSDNode>(Op2);
3188        else if (Op2.getOpcode() == ISD::ADD &&
3189                 Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3190                 Op2.getOperand(1).getOpcode() == ISD::Constant) {
3191          G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
3192          SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
3193        }
3194        if (G) {
3195          GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3196          if (GV) {
3197            Str = GV->getStringValue(false);
3198            if (!Str.empty()) {
3199              CopyFromStr = true;
3200              SrcOff += SrcDelta;
3201            }
3202          }
3203        }
3204
3205        for (unsigned i = 0; i < NumMemOps; i++) {
3206          MVT::ValueType VT = MemOps[i];
3207          unsigned VTSize = getSizeInBits(VT) / 8;
3208          SDOperand Value, Chain, Store;
3209
3210          if (CopyFromStr) {
3211            Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3212            Chain = getRoot();
3213            Store =
3214              DAG.getStore(Chain, Value,
3215                           getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3216                           I.getOperand(1), DstOff);
3217          } else {
3218            Value = DAG.getLoad(VT, getRoot(),
3219                        getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
3220                        I.getOperand(2), SrcOff);
3221            Chain = Value.getValue(1);
3222            Store =
3223              DAG.getStore(Chain, Value,
3224                           getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3225                           I.getOperand(1), DstOff);
3226          }
3227          OutChains.push_back(Store);
3228          SrcOff += VTSize;
3229          DstOff += VTSize;
3230        }
3231      }
3232      break;
3233    }
3234    }
3235
3236    if (!OutChains.empty()) {
3237      DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3238                  &OutChains[0], OutChains.size()));
3239      return;
3240    }
3241  }
3242
3243  DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
3244}
3245
3246//===----------------------------------------------------------------------===//
3247// SelectionDAGISel code
3248//===----------------------------------------------------------------------===//
3249
3250unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3251  return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3252}
3253
3254void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
3255  // FIXME: we only modify the CFG to split critical edges.  This
3256  // updates dom and loop info.
3257  AU.addRequired<AliasAnalysis>();
3258}
3259
3260
3261/// OptimizeNoopCopyExpression - We have determined that the specified cast
3262/// instruction is a noop copy (e.g. it's casting from one pointer type to
3263/// another, int->uint, or int->sbyte on PPC.
3264///
3265/// Return true if any changes are made.
3266static bool OptimizeNoopCopyExpression(CastInst *CI) {
3267  BasicBlock *DefBB = CI->getParent();
3268
3269  /// InsertedCasts - Only insert a cast in each block once.
3270  std::map<BasicBlock*, CastInst*> InsertedCasts;
3271
3272  bool MadeChange = false;
3273  for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
3274       UI != E; ) {
3275    Use &TheUse = UI.getUse();
3276    Instruction *User = cast<Instruction>(*UI);
3277
3278    // Figure out which BB this cast is used in.  For PHI's this is the
3279    // appropriate predecessor block.
3280    BasicBlock *UserBB = User->getParent();
3281    if (PHINode *PN = dyn_cast<PHINode>(User)) {
3282      unsigned OpVal = UI.getOperandNo()/2;
3283      UserBB = PN->getIncomingBlock(OpVal);
3284    }
3285
3286    // Preincrement use iterator so we don't invalidate it.
3287    ++UI;
3288
3289    // If this user is in the same block as the cast, don't change the cast.
3290    if (UserBB == DefBB) continue;
3291
3292    // If we have already inserted a cast into this block, use it.
3293    CastInst *&InsertedCast = InsertedCasts[UserBB];
3294
3295    if (!InsertedCast) {
3296      BasicBlock::iterator InsertPt = UserBB->begin();
3297      while (isa<PHINode>(InsertPt)) ++InsertPt;
3298
3299      InsertedCast =
3300        new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3301      MadeChange = true;
3302    }
3303
3304    // Replace a use of the cast with a use of the new casat.
3305    TheUse = InsertedCast;
3306  }
3307
3308  // If we removed all uses, nuke the cast.
3309  if (CI->use_empty())
3310    CI->eraseFromParent();
3311
3312  return MadeChange;
3313}
3314
3315/// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3316/// casting to the type of GEPI.
3317static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3318                                         Instruction *GEPI, Value *Ptr,
3319                                         Value *PtrOffset) {
3320  if (V) return V;   // Already computed.
3321
3322  BasicBlock::iterator InsertPt;
3323  if (BB == GEPI->getParent()) {
3324    // If insert into the GEP's block, insert right after the GEP.
3325    InsertPt = GEPI;
3326    ++InsertPt;
3327  } else {
3328    // Otherwise, insert at the top of BB, after any PHI nodes
3329    InsertPt = BB->begin();
3330    while (isa<PHINode>(InsertPt)) ++InsertPt;
3331  }
3332
3333  // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3334  // BB so that there is only one value live across basic blocks (the cast
3335  // operand).
3336  if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3337    if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3338      Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
3339
3340  // Add the offset, cast it to the right type.
3341  Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3342  return V = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
3343}
3344
3345/// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3346/// compute its value.  The RepPtr value can be computed with Ptr+PtrOffset. One
3347/// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3348/// block, then ReplaceAllUsesWith'ing everything.  However, we would prefer to
3349/// sink PtrOffset into user blocks where doing so will likely allow us to fold
3350/// the constant add into a load or store instruction.  Additionally, if a user
3351/// is a pointer-pointer cast, we look through it to find its users.
3352static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr,
3353                                 Constant *PtrOffset, BasicBlock *DefBB,
3354                                 GetElementPtrInst *GEPI,
3355                           std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3356  while (!RepPtr->use_empty()) {
3357    Instruction *User = cast<Instruction>(RepPtr->use_back());
3358
3359    // If the user is a Pointer-Pointer cast, recurse.
3360    if (isa<CastInst>(User) && isa<PointerType>(User->getType())) {
3361      ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3362
3363      // Drop the use of RepPtr. The cast is dead.  Don't delete it now, else we
3364      // could invalidate an iterator.
3365      User->setOperand(0, UndefValue::get(RepPtr->getType()));
3366      continue;
3367    }
3368
3369    // If this is a load of the pointer, or a store through the pointer, emit
3370    // the increment into the load/store block.
3371    Instruction *NewVal;
3372    if (isa<LoadInst>(User) ||
3373        (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3374      NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()],
3375                                    User->getParent(), GEPI,
3376                                    Ptr, PtrOffset);
3377    } else {
3378      // If this use is not foldable into the addressing mode, use a version
3379      // emitted in the GEP block.
3380      NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI,
3381                                    Ptr, PtrOffset);
3382    }
3383
3384    if (GEPI->getType() != RepPtr->getType()) {
3385      BasicBlock::iterator IP = NewVal;
3386      ++IP;
3387      NewVal = new CastInst(NewVal, RepPtr->getType(), "", IP);
3388    }
3389    User->replaceUsesOfWith(RepPtr, NewVal);
3390  }
3391}
3392
3393
3394/// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3395/// selection, we want to be a bit careful about some things.  In particular, if
3396/// we have a GEP instruction that is used in a different block than it is
3397/// defined, the addressing expression of the GEP cannot be folded into loads or
3398/// stores that use it.  In this case, decompose the GEP and move constant
3399/// indices into blocks that use it.
3400static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3401                                  const TargetData *TD) {
3402  // If this GEP is only used inside the block it is defined in, there is no
3403  // need to rewrite it.
3404  bool isUsedOutsideDefBB = false;
3405  BasicBlock *DefBB = GEPI->getParent();
3406  for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end();
3407       UI != E; ++UI) {
3408    if (cast<Instruction>(*UI)->getParent() != DefBB) {
3409      isUsedOutsideDefBB = true;
3410      break;
3411    }
3412  }
3413  if (!isUsedOutsideDefBB) return false;
3414
3415  // If this GEP has no non-zero constant indices, there is nothing we can do,
3416  // ignore it.
3417  bool hasConstantIndex = false;
3418  bool hasVariableIndex = false;
3419  for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3420       E = GEPI->op_end(); OI != E; ++OI) {
3421    if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3422      if (CI->getZExtValue()) {
3423        hasConstantIndex = true;
3424        break;
3425      }
3426    } else {
3427      hasVariableIndex = true;
3428    }
3429  }
3430
3431  // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3432  if (!hasConstantIndex && !hasVariableIndex) {
3433    Value *NC = new CastInst(GEPI->getOperand(0), GEPI->getType(),
3434                             GEPI->getName(), GEPI);
3435    GEPI->replaceAllUsesWith(NC);
3436    GEPI->eraseFromParent();
3437    return true;
3438  }
3439
3440  // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3441  if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3442    return false;
3443
3444  // Otherwise, decompose the GEP instruction into multiplies and adds.  Sum the
3445  // constant offset (which we now know is non-zero) and deal with it later.
3446  uint64_t ConstantOffset = 0;
3447  const Type *UIntPtrTy = TD->getIntPtrType();
3448  Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3449  const Type *Ty = GEPI->getOperand(0)->getType();
3450
3451  for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3452       E = GEPI->op_end(); OI != E; ++OI) {
3453    Value *Idx = *OI;
3454    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3455      unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3456      if (Field)
3457        ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
3458      Ty = StTy->getElementType(Field);
3459    } else {
3460      Ty = cast<SequentialType>(Ty)->getElementType();
3461
3462      // Handle constant subscripts.
3463      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3464        if (CI->getZExtValue() == 0) continue;
3465        if (CI->getType()->isSigned())
3466          ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
3467        else
3468          ConstantOffset += TD->getTypeSize(Ty)*CI->getZExtValue();
3469        continue;
3470      }
3471
3472      // Ptr = Ptr + Idx * ElementSize;
3473
3474      // Cast Idx to UIntPtrTy if needed.
3475      Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
3476
3477      uint64_t ElementSize = TD->getTypeSize(Ty);
3478      // Mask off bits that should not be set.
3479      ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3480      Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
3481
3482      // Multiply by the element size and add to the base.
3483      Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3484      Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3485    }
3486  }
3487
3488  // Make sure that the offset fits in uintptr_t.
3489  ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3490  Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
3491
3492  // Okay, we have now emitted all of the variable index parts to the BB that
3493  // the GEP is defined in.  Loop over all of the using instructions, inserting
3494  // an "add Ptr, ConstantOffset" into each block that uses it and update the
3495  // instruction to use the newly computed value, making GEPI dead.  When the
3496  // user is a load or store instruction address, we emit the add into the user
3497  // block, otherwise we use a canonical version right next to the gep (these
3498  // won't be foldable as addresses, so we might as well share the computation).
3499
3500  std::map<BasicBlock*,Instruction*> InsertedExprs;
3501  ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3502
3503  // Finally, the GEP is dead, remove it.
3504  GEPI->eraseFromParent();
3505
3506  return true;
3507}
3508
3509
3510/// SplitEdgeNicely - Split the critical edge from TI to it's specified
3511/// successor if it will improve codegen.  We only do this if the successor has
3512/// phi nodes (otherwise critical edges are ok).  If there is already another
3513/// predecessor of the succ that is empty (and thus has no phi nodes), use it
3514/// instead of introducing a new block.
3515static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3516  BasicBlock *TIBB = TI->getParent();
3517  BasicBlock *Dest = TI->getSuccessor(SuccNum);
3518  assert(isa<PHINode>(Dest->begin()) &&
3519         "This should only be called if Dest has a PHI!");
3520
3521  /// TIPHIValues - This array is lazily computed to determine the values of
3522  /// PHIs in Dest that TI would provide.
3523  std::vector<Value*> TIPHIValues;
3524
3525  // Check to see if Dest has any blocks that can be used as a split edge for
3526  // this terminator.
3527  for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3528    BasicBlock *Pred = *PI;
3529    // To be usable, the pred has to end with an uncond branch to the dest.
3530    BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3531    if (!PredBr || !PredBr->isUnconditional() ||
3532        // Must be empty other than the branch.
3533        &Pred->front() != PredBr)
3534      continue;
3535
3536    // Finally, since we know that Dest has phi nodes in it, we have to make
3537    // sure that jumping to Pred will have the same affect as going to Dest in
3538    // terms of PHI values.
3539    PHINode *PN;
3540    unsigned PHINo = 0;
3541    bool FoundMatch = true;
3542    for (BasicBlock::iterator I = Dest->begin();
3543         (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3544      if (PHINo == TIPHIValues.size())
3545        TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3546
3547      // If the PHI entry doesn't work, we can't use this pred.
3548      if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3549        FoundMatch = false;
3550        break;
3551      }
3552    }
3553
3554    // If we found a workable predecessor, change TI to branch to Succ.
3555    if (FoundMatch) {
3556      Dest->removePredecessor(TIBB);
3557      TI->setSuccessor(SuccNum, Pred);
3558      return;
3559    }
3560  }
3561
3562  SplitCriticalEdge(TI, SuccNum, P, true);
3563}
3564
3565
3566bool SelectionDAGISel::runOnFunction(Function &Fn) {
3567  MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3568  RegMap = MF.getSSARegMap();
3569  DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
3570
3571  // First, split all critical edges.
3572  //
3573  // In this pass we also look for GEP and cast instructions that are used
3574  // across basic blocks and rewrite them to improve basic-block-at-a-time
3575  // selection.
3576  //
3577  bool MadeChange = true;
3578  while (MadeChange) {
3579    MadeChange = false;
3580  for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3581    // Split all critical edges where the dest block has a PHI.
3582    TerminatorInst *BBTI = BB->getTerminator();
3583    if (BBTI->getNumSuccessors() > 1) {
3584      for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
3585        if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3586            isCriticalEdge(BBTI, i, true))
3587          SplitEdgeNicely(BBTI, i, this);
3588    }
3589
3590
3591    for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3592      Instruction *I = BBI++;
3593      if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3594        MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3595      } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3596        // If the source of the cast is a constant, then this should have
3597        // already been constant folded.  The only reason NOT to constant fold
3598        // it is if something (e.g. LSR) was careful to place the constant
3599        // evaluation in a block other than then one that uses it (e.g. to hoist
3600        // the address of globals out of a loop).  If this is the case, we don't
3601        // want to forward-subst the cast.
3602        if (isa<Constant>(CI->getOperand(0)))
3603          continue;
3604
3605        // If this is a noop copy, sink it into user blocks to reduce the number
3606        // of virtual registers that must be created and coallesced.
3607        MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3608        MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3609
3610        // This is an fp<->int conversion?
3611        if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3612          continue;
3613
3614        // If this is an extension, it will be a zero or sign extension, which
3615        // isn't a noop.
3616        if (SrcVT < DstVT) continue;
3617
3618        // If these values will be promoted, find out what they will be promoted
3619        // to.  This helps us consider truncates on PPC as noop copies when they
3620        // are.
3621        if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3622          SrcVT = TLI.getTypeToTransformTo(SrcVT);
3623        if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3624          DstVT = TLI.getTypeToTransformTo(DstVT);
3625
3626        // If, after promotion, these are the same types, this is a noop copy.
3627        if (SrcVT == DstVT)
3628          MadeChange |= OptimizeNoopCopyExpression(CI);
3629      }
3630    }
3631  }
3632  }
3633
3634  FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3635
3636  for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3637    SelectBasicBlock(I, MF, FuncInfo);
3638
3639  return true;
3640}
3641
3642SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V,
3643                                                           unsigned Reg) {
3644  SDOperand Op = getValue(V);
3645  assert((Op.getOpcode() != ISD::CopyFromReg ||
3646          cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3647         "Copy from a reg to the same reg!");
3648
3649  // If this type is not legal, we must make sure to not create an invalid
3650  // register use.
3651  MVT::ValueType SrcVT = Op.getValueType();
3652  MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3653  if (SrcVT == DestVT) {
3654    return DAG.getCopyToReg(getRoot(), Reg, Op);
3655  } else if (SrcVT == MVT::Vector) {
3656    // Handle copies from generic vectors to registers.
3657    MVT::ValueType PTyElementVT, PTyLegalElementVT;
3658    unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3659                                             PTyElementVT, PTyLegalElementVT);
3660
3661    // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT"
3662    // MVT::Vector type.
3663    Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3664                     DAG.getConstant(NE, MVT::i32),
3665                     DAG.getValueType(PTyElementVT));
3666
3667    // Loop over all of the elements of the resultant vector,
3668    // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3669    // copying them into output registers.
3670    SmallVector<SDOperand, 8> OutChains;
3671    SDOperand Root = getRoot();
3672    for (unsigned i = 0; i != NE; ++i) {
3673      SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3674                                  Op, DAG.getConstant(i, TLI.getPointerTy()));
3675      if (PTyElementVT == PTyLegalElementVT) {
3676        // Elements are legal.
3677        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3678      } else if (PTyLegalElementVT > PTyElementVT) {
3679        // Elements are promoted.
3680        if (MVT::isFloatingPoint(PTyLegalElementVT))
3681          Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3682        else
3683          Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3684        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3685      } else {
3686        // Elements are expanded.
3687        // The src value is expanded into multiple registers.
3688        SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3689                                   Elt, DAG.getConstant(0, TLI.getPointerTy()));
3690        SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3691                                   Elt, DAG.getConstant(1, TLI.getPointerTy()));
3692        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3693        OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3694      }
3695    }
3696    return DAG.getNode(ISD::TokenFactor, MVT::Other,
3697                       &OutChains[0], OutChains.size());
3698  } else if (SrcVT < DestVT) {
3699    // The src value is promoted to the register.
3700    if (MVT::isFloatingPoint(SrcVT))
3701      Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3702    else
3703      Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3704    return DAG.getCopyToReg(getRoot(), Reg, Op);
3705  } else  {
3706    // The src value is expanded into multiple registers.
3707    SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3708                               Op, DAG.getConstant(0, TLI.getPointerTy()));
3709    SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3710                               Op, DAG.getConstant(1, TLI.getPointerTy()));
3711    Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
3712    return DAG.getCopyToReg(Op, Reg+1, Hi);
3713  }
3714}
3715
3716void SelectionDAGISel::
3717LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3718               std::vector<SDOperand> &UnorderedChains) {
3719  // If this is the entry block, emit arguments.
3720  Function &F = *BB->getParent();
3721  FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3722  SDOperand OldRoot = SDL.DAG.getRoot();
3723  std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3724
3725  unsigned a = 0;
3726  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3727       AI != E; ++AI, ++a)
3728    if (!AI->use_empty()) {
3729      SDL.setValue(AI, Args[a]);
3730
3731      // If this argument is live outside of the entry block, insert a copy from
3732      // whereever we got it to the vreg that other BB's will reference it as.
3733      if (FuncInfo.ValueMap.count(AI)) {
3734        SDOperand Copy =
3735          SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
3736        UnorderedChains.push_back(Copy);
3737      }
3738    }
3739
3740  // Finally, if the target has anything special to do, allow it to do so.
3741  // FIXME: this should insert code into the DAG!
3742  EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3743}
3744
3745void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3746       std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3747                                         FunctionLoweringInfo &FuncInfo) {
3748  SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3749
3750  std::vector<SDOperand> UnorderedChains;
3751
3752  // Lower any arguments needed in this block if this is the entry block.
3753  if (LLVMBB == &LLVMBB->getParent()->front())
3754    LowerArguments(LLVMBB, SDL, UnorderedChains);
3755
3756  BB = FuncInfo.MBBMap[LLVMBB];
3757  SDL.setCurrentBasicBlock(BB);
3758
3759  // Lower all of the non-terminator instructions.
3760  for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3761       I != E; ++I)
3762    SDL.visit(*I);
3763
3764  // Ensure that all instructions which are used outside of their defining
3765  // blocks are available as virtual registers.
3766  for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3767    if (!I->use_empty() && !isa<PHINode>(I)) {
3768      std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3769      if (VMI != FuncInfo.ValueMap.end())
3770        UnorderedChains.push_back(
3771                                SDL.CopyValueToVirtualRegister(I, VMI->second));
3772    }
3773
3774  // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
3775  // ensure constants are generated when needed.  Remember the virtual registers
3776  // that need to be added to the Machine PHI nodes as input.  We cannot just
3777  // directly add them, because expansion might result in multiple MBB's for one
3778  // BB.  As such, the start of the BB might correspond to a different MBB than
3779  // the end.
3780  //
3781  TerminatorInst *TI = LLVMBB->getTerminator();
3782
3783  // Emit constants only once even if used by multiple PHI nodes.
3784  std::map<Constant*, unsigned> ConstantsOut;
3785
3786  // Vector bool would be better, but vector<bool> is really slow.
3787  std::vector<unsigned char> SuccsHandled;
3788  if (TI->getNumSuccessors())
3789    SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
3790
3791  // Check successor nodes PHI nodes that expect a constant to be available from
3792  // this block.
3793  for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
3794    BasicBlock *SuccBB = TI->getSuccessor(succ);
3795    if (!isa<PHINode>(SuccBB->begin())) continue;
3796    MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
3797
3798    // If this terminator has multiple identical successors (common for
3799    // switches), only handle each succ once.
3800    unsigned SuccMBBNo = SuccMBB->getNumber();
3801    if (SuccsHandled[SuccMBBNo]) continue;
3802    SuccsHandled[SuccMBBNo] = true;
3803
3804    MachineBasicBlock::iterator MBBI = SuccMBB->begin();
3805    PHINode *PN;
3806
3807    // At this point we know that there is a 1-1 correspondence between LLVM PHI
3808    // nodes and Machine PHI nodes, but the incoming operands have not been
3809    // emitted yet.
3810    for (BasicBlock::iterator I = SuccBB->begin();
3811         (PN = dyn_cast<PHINode>(I)); ++I) {
3812      // Ignore dead phi's.
3813      if (PN->use_empty()) continue;
3814
3815      unsigned Reg;
3816      Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
3817      if (Constant *C = dyn_cast<Constant>(PHIOp)) {
3818        unsigned &RegOut = ConstantsOut[C];
3819        if (RegOut == 0) {
3820          RegOut = FuncInfo.CreateRegForValue(C);
3821          UnorderedChains.push_back(
3822                           SDL.CopyValueToVirtualRegister(C, RegOut));
3823        }
3824        Reg = RegOut;
3825      } else {
3826        Reg = FuncInfo.ValueMap[PHIOp];
3827        if (Reg == 0) {
3828          assert(isa<AllocaInst>(PHIOp) &&
3829                 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
3830                 "Didn't codegen value into a register!??");
3831          Reg = FuncInfo.CreateRegForValue(PHIOp);
3832          UnorderedChains.push_back(
3833                           SDL.CopyValueToVirtualRegister(PHIOp, Reg));
3834        }
3835      }
3836
3837      // Remember that this register needs to added to the machine PHI node as
3838      // the input for this MBB.
3839      MVT::ValueType VT = TLI.getValueType(PN->getType());
3840      unsigned NumElements;
3841      if (VT != MVT::Vector)
3842        NumElements = TLI.getNumElements(VT);
3843      else {
3844        MVT::ValueType VT1,VT2;
3845        NumElements =
3846          TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
3847                                     VT1, VT2);
3848      }
3849      for (unsigned i = 0, e = NumElements; i != e; ++i)
3850        PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
3851    }
3852  }
3853  ConstantsOut.clear();
3854
3855  // Turn all of the unordered chains into one factored node.
3856  if (!UnorderedChains.empty()) {
3857    SDOperand Root = SDL.getRoot();
3858    if (Root.getOpcode() != ISD::EntryToken) {
3859      unsigned i = 0, e = UnorderedChains.size();
3860      for (; i != e; ++i) {
3861        assert(UnorderedChains[i].Val->getNumOperands() > 1);
3862        if (UnorderedChains[i].Val->getOperand(0) == Root)
3863          break;  // Don't add the root if we already indirectly depend on it.
3864      }
3865
3866      if (i == e)
3867        UnorderedChains.push_back(Root);
3868    }
3869    DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3870                            &UnorderedChains[0], UnorderedChains.size()));
3871  }
3872
3873  // Lower the terminator after the copies are emitted.
3874  SDL.visit(*LLVMBB->getTerminator());
3875
3876  // Copy over any CaseBlock records that may now exist due to SwitchInst
3877  // lowering, as well as any jump table information.
3878  SwitchCases.clear();
3879  SwitchCases = SDL.SwitchCases;
3880  JT = SDL.JT;
3881
3882  // Make sure the root of the DAG is up-to-date.
3883  DAG.setRoot(SDL.getRoot());
3884}
3885
3886void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
3887  // Get alias analysis for load/store combining.
3888  AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
3889
3890  // Run the DAG combiner in pre-legalize mode.
3891  DAG.Combine(false, AA);
3892
3893  DEBUG(std::cerr << "Lowered selection DAG:\n");
3894  DEBUG(DAG.dump());
3895
3896  // Second step, hack on the DAG until it only uses operations and types that
3897  // the target supports.
3898  DAG.Legalize();
3899
3900  DEBUG(std::cerr << "Legalized selection DAG:\n");
3901  DEBUG(DAG.dump());
3902
3903  // Run the DAG combiner in post-legalize mode.
3904  DAG.Combine(true, AA);
3905
3906  if (ViewISelDAGs) DAG.viewGraph();
3907
3908  // Third, instruction select all of the operations to machine code, adding the
3909  // code to the MachineBasicBlock.
3910  InstructionSelectBasicBlock(DAG);
3911
3912  DEBUG(std::cerr << "Selected machine code:\n");
3913  DEBUG(BB->dump());
3914}
3915
3916void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
3917                                        FunctionLoweringInfo &FuncInfo) {
3918  std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
3919  {
3920    SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3921    CurDAG = &DAG;
3922
3923    // First step, lower LLVM code to some DAG.  This DAG may use operations and
3924    // types that are not supported by the target.
3925    BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
3926
3927    // Second step, emit the lowered DAG as machine code.
3928    CodeGenAndEmitDAG(DAG);
3929  }
3930
3931  // Next, now that we know what the last MBB the LLVM BB expanded is, update
3932  // PHI nodes in successors.
3933  if (SwitchCases.empty() && JT.Reg == 0) {
3934    for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3935      MachineInstr *PHI = PHINodesToUpdate[i].first;
3936      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3937             "This is not a machine PHI node that we are updating!");
3938      PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3939      PHI->addMachineBasicBlockOperand(BB);
3940    }
3941    return;
3942  }
3943
3944  // If the JumpTable record is filled in, then we need to emit a jump table.
3945  // Updating the PHI nodes is tricky in this case, since we need to determine
3946  // whether the PHI is a successor of the range check MBB or the jump table MBB
3947  if (JT.Reg) {
3948    assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
3949    SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3950    CurDAG = &SDAG;
3951    SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3952    MachineBasicBlock *RangeBB = BB;
3953    // Set the current basic block to the mbb we wish to insert the code into
3954    BB = JT.MBB;
3955    SDL.setCurrentBasicBlock(BB);
3956    // Emit the code
3957    SDL.visitJumpTable(JT);
3958    SDAG.setRoot(SDL.getRoot());
3959    CodeGenAndEmitDAG(SDAG);
3960    // Update PHI Nodes
3961    for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
3962      MachineInstr *PHI = PHINodesToUpdate[pi].first;
3963      MachineBasicBlock *PHIBB = PHI->getParent();
3964      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3965             "This is not a machine PHI node that we are updating!");
3966      if (PHIBB == JT.Default) {
3967        PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
3968        PHI->addMachineBasicBlockOperand(RangeBB);
3969      }
3970      if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
3971        PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
3972        PHI->addMachineBasicBlockOperand(BB);
3973      }
3974    }
3975    return;
3976  }
3977
3978  // If the switch block involved a branch to one of the actual successors, we
3979  // need to update PHI nodes in that block.
3980  for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
3981    MachineInstr *PHI = PHINodesToUpdate[i].first;
3982    assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
3983           "This is not a machine PHI node that we are updating!");
3984    if (BB->isSuccessor(PHI->getParent())) {
3985      PHI->addRegOperand(PHINodesToUpdate[i].second, false);
3986      PHI->addMachineBasicBlockOperand(BB);
3987    }
3988  }
3989
3990  // If we generated any switch lowering information, build and codegen any
3991  // additional DAGs necessary.
3992  for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
3993    SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
3994    CurDAG = &SDAG;
3995    SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
3996
3997    // Set the current basic block to the mbb we wish to insert the code into
3998    BB = SwitchCases[i].ThisBB;
3999    SDL.setCurrentBasicBlock(BB);
4000
4001    // Emit the code
4002    SDL.visitSwitchCase(SwitchCases[i]);
4003    SDAG.setRoot(SDL.getRoot());
4004    CodeGenAndEmitDAG(SDAG);
4005
4006    // Handle any PHI nodes in successors of this chunk, as if we were coming
4007    // from the original BB before switch expansion.  Note that PHI nodes can
4008    // occur multiple times in PHINodesToUpdate.  We have to be very careful to
4009    // handle them the right number of times.
4010    while ((BB = SwitchCases[i].TrueBB)) {  // Handle LHS and RHS.
4011      for (MachineBasicBlock::iterator Phi = BB->begin();
4012           Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4013        // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4014        for (unsigned pn = 0; ; ++pn) {
4015          assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4016          if (PHINodesToUpdate[pn].first == Phi) {
4017            Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4018            Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4019            break;
4020          }
4021        }
4022      }
4023
4024      // Don't process RHS if same block as LHS.
4025      if (BB == SwitchCases[i].FalseBB)
4026        SwitchCases[i].FalseBB = 0;
4027
4028      // If we haven't handled the RHS, do so now.  Otherwise, we're done.
4029      SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4030      SwitchCases[i].FalseBB = 0;
4031    }
4032    assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4033  }
4034}
4035
4036
4037//===----------------------------------------------------------------------===//
4038/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4039/// target node in the graph.
4040void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4041  if (ViewSchedDAGs) DAG.viewGraph();
4042
4043  RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4044
4045  if (!Ctor) {
4046    Ctor = ISHeuristic;
4047    RegisterScheduler::setDefault(Ctor);
4048  }
4049
4050  ScheduleDAG *SL = Ctor(this, &DAG, BB);
4051  BB = SL->Run();
4052  delete SL;
4053}
4054
4055
4056HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4057  return new HazardRecognizer();
4058}
4059
4060//===----------------------------------------------------------------------===//
4061// Helper functions used by the generated instruction selector.
4062//===----------------------------------------------------------------------===//
4063// Calls to these methods are generated by tblgen.
4064
4065/// CheckAndMask - The isel is trying to match something like (and X, 255).  If
4066/// the dag combiner simplified the 255, we still want to match.  RHS is the
4067/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4068/// specified in the .td file (e.g. 255).
4069bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
4070                                    int64_t DesiredMaskS) {
4071  uint64_t ActualMask = RHS->getValue();
4072  uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4073
4074  // If the actual mask exactly matches, success!
4075  if (ActualMask == DesiredMask)
4076    return true;
4077
4078  // If the actual AND mask is allowing unallowed bits, this doesn't match.
4079  if (ActualMask & ~DesiredMask)
4080    return false;
4081
4082  // Otherwise, the DAG Combiner may have proven that the value coming in is
4083  // either already zero or is not demanded.  Check for known zero input bits.
4084  uint64_t NeededMask = DesiredMask & ~ActualMask;
4085  if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4086    return true;
4087
4088  // TODO: check to see if missing bits are just not demanded.
4089
4090  // Otherwise, this pattern doesn't match.
4091  return false;
4092}
4093
4094/// CheckOrMask - The isel is trying to match something like (or X, 255).  If
4095/// the dag combiner simplified the 255, we still want to match.  RHS is the
4096/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4097/// specified in the .td file (e.g. 255).
4098bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
4099                                    int64_t DesiredMaskS) {
4100  uint64_t ActualMask = RHS->getValue();
4101  uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4102
4103  // If the actual mask exactly matches, success!
4104  if (ActualMask == DesiredMask)
4105    return true;
4106
4107  // If the actual AND mask is allowing unallowed bits, this doesn't match.
4108  if (ActualMask & ~DesiredMask)
4109    return false;
4110
4111  // Otherwise, the DAG Combiner may have proven that the value coming in is
4112  // either already zero or is not demanded.  Check for known zero input bits.
4113  uint64_t NeededMask = DesiredMask & ~ActualMask;
4114
4115  uint64_t KnownZero, KnownOne;
4116  getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4117
4118  // If all the missing bits in the or are already known to be set, match!
4119  if ((NeededMask & KnownOne) == NeededMask)
4120    return true;
4121
4122  // TODO: check to see if missing bits are just not demanded.
4123
4124  // Otherwise, this pattern doesn't match.
4125  return false;
4126}
4127
4128
4129/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4130/// by tblgen.  Others should not call it.
4131void SelectionDAGISel::
4132SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4133  std::vector<SDOperand> InOps;
4134  std::swap(InOps, Ops);
4135
4136  Ops.push_back(InOps[0]);  // input chain.
4137  Ops.push_back(InOps[1]);  // input asm string.
4138
4139  unsigned i = 2, e = InOps.size();
4140  if (InOps[e-1].getValueType() == MVT::Flag)
4141    --e;  // Don't process a flag operand if it is here.
4142
4143  while (i != e) {
4144    unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4145    if ((Flags & 7) != 4 /*MEM*/) {
4146      // Just skip over this operand, copying the operands verbatim.
4147      Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4148      i += (Flags >> 3) + 1;
4149    } else {
4150      assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4151      // Otherwise, this is a memory operand.  Ask the target to select it.
4152      std::vector<SDOperand> SelOps;
4153      if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4154        std::cerr << "Could not match memory address.  Inline asm failure!\n";
4155        exit(1);
4156      }
4157
4158      // Add this to the output node.
4159      Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
4160      Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4161      i += 2;
4162    }
4163  }
4164
4165  // Add the flag input back if present.
4166  if (e != InOps.size())
4167    Ops.push_back(InOps.back());
4168}
4169