SelectionDAGISel.cpp revision 9b77cae1df76d8be0771563f55dc72b1cdab648c
1//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "llvm/ADT/BitVector.h"
16#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/CodeGen/SelectionDAGISel.h"
18#include "llvm/CodeGen/ScheduleDAG.h"
19#include "llvm/Constants.h"
20#include "llvm/CallingConv.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/InlineAsm.h"
25#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/IntrinsicInst.h"
28#include "llvm/ParameterAttributes.h"
29#include "llvm/CodeGen/Collector.h"
30#include "llvm/CodeGen/MachineDebugInfoDesc.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineFrameInfo.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
34#include "llvm/CodeGen/MachineJumpTableInfo.h"
35#include "llvm/CodeGen/MachineModuleInfo.h"
36#include "llvm/CodeGen/MachineRegisterInfo.h"
37#include "llvm/CodeGen/SchedulerRegistry.h"
38#include "llvm/CodeGen/SelectionDAG.h"
39#include "llvm/Target/TargetRegisterInfo.h"
40#include "llvm/Target/TargetData.h"
41#include "llvm/Target/TargetFrameInfo.h"
42#include "llvm/Target/TargetInstrInfo.h"
43#include "llvm/Target/TargetLowering.h"
44#include "llvm/Target/TargetMachine.h"
45#include "llvm/Target/TargetOptions.h"
46#include "llvm/Support/Compiler.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/MathExtras.h"
49#include "llvm/Support/Timer.h"
50#include <algorithm>
51using namespace llvm;
52
53static cl::opt<bool>
54EnableValueProp("enable-value-prop", cl::Hidden, cl::init(false));
55
56
57#ifndef NDEBUG
58static cl::opt<bool>
59ViewISelDAGs("view-isel-dags", cl::Hidden,
60          cl::desc("Pop up a window to show isel dags as they are selected"));
61static cl::opt<bool>
62ViewSchedDAGs("view-sched-dags", cl::Hidden,
63          cl::desc("Pop up a window to show sched dags as they are processed"));
64static cl::opt<bool>
65ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
66      cl::desc("Pop up a window to show SUnit dags after they are processed"));
67#else
68static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0, ViewSUnitDAGs = 0;
69#endif
70
71//===---------------------------------------------------------------------===//
72///
73/// RegisterScheduler class - Track the registration of instruction schedulers.
74///
75//===---------------------------------------------------------------------===//
76MachinePassRegistry RegisterScheduler::Registry;
77
78//===---------------------------------------------------------------------===//
79///
80/// ISHeuristic command line option for instruction schedulers.
81///
82//===---------------------------------------------------------------------===//
83static cl::opt<RegisterScheduler::FunctionPassCtor, false,
84               RegisterPassParser<RegisterScheduler> >
85ISHeuristic("pre-RA-sched",
86            cl::init(&createDefaultScheduler),
87            cl::desc("Instruction schedulers available (before register"
88                     " allocation):"));
89
90static RegisterScheduler
91defaultListDAGScheduler("default", "  Best scheduler for the target",
92                        createDefaultScheduler);
93
94namespace { struct SDISelAsmOperandInfo; }
95
96/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
97/// insertvalue or extractvalue indices that identify a member, return
98/// the linearized index of the start of the member.
99///
100static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
101                                   const unsigned *Indices,
102                                   const unsigned *IndicesEnd,
103                                   unsigned CurIndex = 0) {
104  // Base case: We're done.
105  if (Indices && Indices == IndicesEnd)
106    return CurIndex;
107
108  // Given a struct type, recursively traverse the elements.
109  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
110    for (StructType::element_iterator EB = STy->element_begin(),
111                                      EI = EB,
112                                      EE = STy->element_end();
113        EI != EE; ++EI) {
114      if (Indices && *Indices == unsigned(EI - EB))
115        return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
116      CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
117    }
118  }
119  // Given an array type, recursively traverse the elements.
120  else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
121    const Type *EltTy = ATy->getElementType();
122    for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
123      if (Indices && *Indices == i)
124        return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
125      CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
126    }
127  }
128  // We haven't found the type we're looking for, so keep searching.
129  return CurIndex + 1;
130}
131
132/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
133/// MVTs that represent all the individual underlying
134/// non-aggregate types that comprise it.
135///
136/// If Offsets is non-null, it points to a vector to be filled in
137/// with the in-memory offsets of each of the individual values.
138///
139static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
140                            SmallVectorImpl<MVT> &ValueVTs,
141                            SmallVectorImpl<uint64_t> *Offsets = 0,
142                            uint64_t StartingOffset = 0) {
143  // Given a struct type, recursively traverse the elements.
144  if (const StructType *STy = dyn_cast<StructType>(Ty)) {
145    const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
146    for (StructType::element_iterator EB = STy->element_begin(),
147                                      EI = EB,
148                                      EE = STy->element_end();
149         EI != EE; ++EI)
150      ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
151                      StartingOffset + SL->getElementOffset(EI - EB));
152    return;
153  }
154  // Given an array type, recursively traverse the elements.
155  if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
156    const Type *EltTy = ATy->getElementType();
157    uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
158    for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
159      ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
160                      StartingOffset + i * EltSize);
161    return;
162  }
163  // Base case: we can get an MVT for this LLVM IR type.
164  ValueVTs.push_back(TLI.getValueType(Ty));
165  if (Offsets)
166    Offsets->push_back(StartingOffset);
167}
168
169namespace {
170  /// RegsForValue - This struct represents the registers (physical or virtual)
171  /// that a particular set of values is assigned, and the type information about
172  /// the value. The most common situation is to represent one value at a time,
173  /// but struct or array values are handled element-wise as multiple values.
174  /// The splitting of aggregates is performed recursively, so that we never
175  /// have aggregate-typed registers. The values at this point do not necessarily
176  /// have legal types, so each value may require one or more registers of some
177  /// legal type.
178  ///
179  struct VISIBILITY_HIDDEN RegsForValue {
180    /// TLI - The TargetLowering object.
181    ///
182    const TargetLowering *TLI;
183
184    /// ValueVTs - The value types of the values, which may not be legal, and
185    /// may need be promoted or synthesized from one or more registers.
186    ///
187    SmallVector<MVT, 4> ValueVTs;
188
189    /// RegVTs - The value types of the registers. This is the same size as
190    /// ValueVTs and it records, for each value, what the type of the assigned
191    /// register or registers are. (Individual values are never synthesized
192    /// from more than one type of register.)
193    ///
194    /// With virtual registers, the contents of RegVTs is redundant with TLI's
195    /// getRegisterType member function, however when with physical registers
196    /// it is necessary to have a separate record of the types.
197    ///
198    SmallVector<MVT, 4> RegVTs;
199
200    /// Regs - This list holds the registers assigned to the values.
201    /// Each legal or promoted value requires one register, and each
202    /// expanded value requires multiple registers.
203    ///
204    SmallVector<unsigned, 4> Regs;
205
206    RegsForValue() : TLI(0) {}
207
208    RegsForValue(const TargetLowering &tli,
209                 const SmallVector<unsigned, 4> &regs,
210                 MVT regvt, MVT valuevt)
211      : TLI(&tli),  ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
212    RegsForValue(const TargetLowering &tli,
213                 const SmallVector<unsigned, 4> &regs,
214                 const SmallVector<MVT, 4> &regvts,
215                 const SmallVector<MVT, 4> &valuevts)
216      : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
217    RegsForValue(const TargetLowering &tli,
218                 unsigned Reg, const Type *Ty) : TLI(&tli) {
219      ComputeValueVTs(tli, Ty, ValueVTs);
220
221      for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
222        MVT ValueVT = ValueVTs[Value];
223        unsigned NumRegs = TLI->getNumRegisters(ValueVT);
224        MVT RegisterVT = TLI->getRegisterType(ValueVT);
225        for (unsigned i = 0; i != NumRegs; ++i)
226          Regs.push_back(Reg + i);
227        RegVTs.push_back(RegisterVT);
228        Reg += NumRegs;
229      }
230    }
231
232    /// append - Add the specified values to this one.
233    void append(const RegsForValue &RHS) {
234      TLI = RHS.TLI;
235      ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
236      RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
237      Regs.append(RHS.Regs.begin(), RHS.Regs.end());
238    }
239
240
241    /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
242    /// this value and returns the result as a ValueVTs value.  This uses
243    /// Chain/Flag as the input and updates them for the output Chain/Flag.
244    /// If the Flag pointer is NULL, no flag is used.
245    SDOperand getCopyFromRegs(SelectionDAG &DAG,
246                              SDOperand &Chain, SDOperand *Flag) const;
247
248    /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
249    /// specified value into the registers specified by this object.  This uses
250    /// Chain/Flag as the input and updates them for the output Chain/Flag.
251    /// If the Flag pointer is NULL, no flag is used.
252    void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
253                       SDOperand &Chain, SDOperand *Flag) const;
254
255    /// AddInlineAsmOperands - Add this value to the specified inlineasm node
256    /// operand list.  This adds the code marker and includes the number of
257    /// values added into it.
258    void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
259                              std::vector<SDOperand> &Ops) const;
260  };
261}
262
263namespace llvm {
264  //===--------------------------------------------------------------------===//
265  /// createDefaultScheduler - This creates an instruction scheduler appropriate
266  /// for the target.
267  ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
268                                      SelectionDAG *DAG,
269                                      MachineBasicBlock *BB,
270                                      bool Fast) {
271    TargetLowering &TLI = IS->getTargetLowering();
272
273    if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
274      return createTDListDAGScheduler(IS, DAG, BB, Fast);
275    } else {
276      assert(TLI.getSchedulingPreference() ==
277           TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
278      return createBURRListDAGScheduler(IS, DAG, BB, Fast);
279    }
280  }
281
282
283  //===--------------------------------------------------------------------===//
284  /// FunctionLoweringInfo - This contains information that is global to a
285  /// function that is used when lowering a region of the function.
286  class FunctionLoweringInfo {
287  public:
288    TargetLowering &TLI;
289    Function &Fn;
290    MachineFunction &MF;
291    MachineRegisterInfo &RegInfo;
292
293    FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
294
295    /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
296    std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
297
298    /// ValueMap - Since we emit code for the function a basic block at a time,
299    /// we must remember which virtual registers hold the values for
300    /// cross-basic-block values.
301    DenseMap<const Value*, unsigned> ValueMap;
302
303    /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
304    /// the entry block.  This allows the allocas to be efficiently referenced
305    /// anywhere in the function.
306    std::map<const AllocaInst*, int> StaticAllocaMap;
307
308#ifndef NDEBUG
309    SmallSet<Instruction*, 8> CatchInfoLost;
310    SmallSet<Instruction*, 8> CatchInfoFound;
311#endif
312
313    unsigned MakeReg(MVT VT) {
314      return RegInfo.createVirtualRegister(TLI.getRegClassFor(VT));
315    }
316
317    /// isExportedInst - Return true if the specified value is an instruction
318    /// exported from its block.
319    bool isExportedInst(const Value *V) {
320      return ValueMap.count(V);
321    }
322
323    unsigned CreateRegForValue(const Value *V);
324
325    unsigned InitializeRegForValue(const Value *V) {
326      unsigned &R = ValueMap[V];
327      assert(R == 0 && "Already initialized this value register!");
328      return R = CreateRegForValue(V);
329    }
330
331    struct LiveOutInfo {
332      unsigned NumSignBits;
333      APInt KnownOne, KnownZero;
334      LiveOutInfo() : NumSignBits(0) {}
335    };
336
337    /// LiveOutRegInfo - Information about live out vregs, indexed by their
338    /// register number offset by 'FirstVirtualRegister'.
339    std::vector<LiveOutInfo> LiveOutRegInfo;
340  };
341}
342
343/// isSelector - Return true if this instruction is a call to the
344/// eh.selector intrinsic.
345static bool isSelector(Instruction *I) {
346  if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
347    return (II->getIntrinsicID() == Intrinsic::eh_selector_i32 ||
348            II->getIntrinsicID() == Intrinsic::eh_selector_i64);
349  return false;
350}
351
352/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
353/// PHI nodes or outside of the basic block that defines it, or used by a
354/// switch or atomic instruction, which may expand to multiple basic blocks.
355static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
356  if (isa<PHINode>(I)) return true;
357  BasicBlock *BB = I->getParent();
358  for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
359    if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
360        // FIXME: Remove switchinst special case.
361        isa<SwitchInst>(*UI))
362      return true;
363  return false;
364}
365
366/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
367/// entry block, return true.  This includes arguments used by switches, since
368/// the switch may expand into multiple basic blocks.
369static bool isOnlyUsedInEntryBlock(Argument *A) {
370  BasicBlock *Entry = A->getParent()->begin();
371  for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
372    if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
373      return false;  // Use not in entry block.
374  return true;
375}
376
377FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
378                                           Function &fn, MachineFunction &mf)
379    : TLI(tli), Fn(fn), MF(mf), RegInfo(MF.getRegInfo()) {
380
381  // Create a vreg for each argument register that is not dead and is used
382  // outside of the entry block for the function.
383  for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
384       AI != E; ++AI)
385    if (!isOnlyUsedInEntryBlock(AI))
386      InitializeRegForValue(AI);
387
388  // Initialize the mapping of values to registers.  This is only set up for
389  // instruction values that are used outside of the block that defines
390  // them.
391  Function::iterator BB = Fn.begin(), EB = Fn.end();
392  for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
393    if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
394      if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
395        const Type *Ty = AI->getAllocatedType();
396        uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
397        unsigned Align =
398          std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
399                   AI->getAlignment());
400
401        TySize *= CUI->getZExtValue();   // Get total allocated size.
402        if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
403        StaticAllocaMap[AI] =
404          MF.getFrameInfo()->CreateStackObject(TySize, Align);
405      }
406
407  for (; BB != EB; ++BB)
408    for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
409      if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
410        if (!isa<AllocaInst>(I) ||
411            !StaticAllocaMap.count(cast<AllocaInst>(I)))
412          InitializeRegForValue(I);
413
414  // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
415  // also creates the initial PHI MachineInstrs, though none of the input
416  // operands are populated.
417  for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
418    MachineBasicBlock *MBB = new MachineBasicBlock(BB);
419    MBBMap[BB] = MBB;
420    MF.getBasicBlockList().push_back(MBB);
421
422    // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
423    // appropriate.
424    PHINode *PN;
425    for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
426      if (PN->use_empty()) continue;
427
428      MVT VT = TLI.getValueType(PN->getType());
429      unsigned NumRegisters = TLI.getNumRegisters(VT);
430      unsigned PHIReg = ValueMap[PN];
431      assert(PHIReg && "PHI node does not have an assigned virtual register!");
432      const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
433      for (unsigned i = 0; i != NumRegisters; ++i)
434        BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
435    }
436  }
437}
438
439/// CreateRegForValue - Allocate the appropriate number of virtual registers of
440/// the correctly promoted or expanded types.  Assign these registers
441/// consecutive vreg numbers and return the first assigned number.
442///
443/// In the case that the given value has struct or array type, this function
444/// will assign registers for each member or element.
445///
446unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
447  SmallVector<MVT, 4> ValueVTs;
448  ComputeValueVTs(TLI, V->getType(), ValueVTs);
449
450  unsigned FirstReg = 0;
451  for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
452    MVT ValueVT = ValueVTs[Value];
453    MVT RegisterVT = TLI.getRegisterType(ValueVT);
454
455    unsigned NumRegs = TLI.getNumRegisters(ValueVT);
456    for (unsigned i = 0; i != NumRegs; ++i) {
457      unsigned R = MakeReg(RegisterVT);
458      if (!FirstReg) FirstReg = R;
459    }
460  }
461  return FirstReg;
462}
463
464//===----------------------------------------------------------------------===//
465/// SelectionDAGLowering - This is the common target-independent lowering
466/// implementation that is parameterized by a TargetLowering object.
467/// Also, targets can overload any lowering method.
468///
469namespace llvm {
470class SelectionDAGLowering {
471  MachineBasicBlock *CurMBB;
472
473  DenseMap<const Value*, SDOperand> NodeMap;
474
475  /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
476  /// them up and then emit token factor nodes when possible.  This allows us to
477  /// get simple disambiguation between loads without worrying about alias
478  /// analysis.
479  SmallVector<SDOperand, 8> PendingLoads;
480
481  /// PendingExports - CopyToReg nodes that copy values to virtual registers
482  /// for export to other blocks need to be emitted before any terminator
483  /// instruction, but they have no other ordering requirements. We bunch them
484  /// up and the emit a single tokenfactor for them just before terminator
485  /// instructions.
486  std::vector<SDOperand> PendingExports;
487
488  /// Case - A struct to record the Value for a switch case, and the
489  /// case's target basic block.
490  struct Case {
491    Constant* Low;
492    Constant* High;
493    MachineBasicBlock* BB;
494
495    Case() : Low(0), High(0), BB(0) { }
496    Case(Constant* low, Constant* high, MachineBasicBlock* bb) :
497      Low(low), High(high), BB(bb) { }
498    uint64_t size() const {
499      uint64_t rHigh = cast<ConstantInt>(High)->getSExtValue();
500      uint64_t rLow  = cast<ConstantInt>(Low)->getSExtValue();
501      return (rHigh - rLow + 1ULL);
502    }
503  };
504
505  struct CaseBits {
506    uint64_t Mask;
507    MachineBasicBlock* BB;
508    unsigned Bits;
509
510    CaseBits(uint64_t mask, MachineBasicBlock* bb, unsigned bits):
511      Mask(mask), BB(bb), Bits(bits) { }
512  };
513
514  typedef std::vector<Case>           CaseVector;
515  typedef std::vector<CaseBits>       CaseBitsVector;
516  typedef CaseVector::iterator        CaseItr;
517  typedef std::pair<CaseItr, CaseItr> CaseRange;
518
519  /// CaseRec - A struct with ctor used in lowering switches to a binary tree
520  /// of conditional branches.
521  struct CaseRec {
522    CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
523    CaseBB(bb), LT(lt), GE(ge), Range(r) {}
524
525    /// CaseBB - The MBB in which to emit the compare and branch
526    MachineBasicBlock *CaseBB;
527    /// LT, GE - If nonzero, we know the current case value must be less-than or
528    /// greater-than-or-equal-to these Constants.
529    Constant *LT;
530    Constant *GE;
531    /// Range - A pair of iterators representing the range of case values to be
532    /// processed at this point in the binary search tree.
533    CaseRange Range;
534  };
535
536  typedef std::vector<CaseRec> CaseRecVector;
537
538  /// The comparison function for sorting the switch case values in the vector.
539  /// WARNING: Case ranges should be disjoint!
540  struct CaseCmp {
541    bool operator () (const Case& C1, const Case& C2) {
542      assert(isa<ConstantInt>(C1.Low) && isa<ConstantInt>(C2.High));
543      const ConstantInt* CI1 = cast<const ConstantInt>(C1.Low);
544      const ConstantInt* CI2 = cast<const ConstantInt>(C2.High);
545      return CI1->getValue().slt(CI2->getValue());
546    }
547  };
548
549  struct CaseBitsCmp {
550    bool operator () (const CaseBits& C1, const CaseBits& C2) {
551      return C1.Bits > C2.Bits;
552    }
553  };
554
555  unsigned Clusterify(CaseVector& Cases, const SwitchInst &SI);
556
557public:
558  // TLI - This is information that describes the available target features we
559  // need for lowering.  This indicates when operations are unavailable,
560  // implemented with a libcall, etc.
561  TargetLowering &TLI;
562  SelectionDAG &DAG;
563  const TargetData *TD;
564  AliasAnalysis &AA;
565
566  /// SwitchCases - Vector of CaseBlock structures used to communicate
567  /// SwitchInst code generation information.
568  std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
569  /// JTCases - Vector of JumpTable structures used to communicate
570  /// SwitchInst code generation information.
571  std::vector<SelectionDAGISel::JumpTableBlock> JTCases;
572  std::vector<SelectionDAGISel::BitTestBlock> BitTestCases;
573
574  /// FuncInfo - Information about the function as a whole.
575  ///
576  FunctionLoweringInfo &FuncInfo;
577
578  /// GCI - Garbage collection metadata for the function.
579  CollectorMetadata *GCI;
580
581  SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
582                       AliasAnalysis &aa,
583                       FunctionLoweringInfo &funcinfo,
584                       CollectorMetadata *gci)
585    : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()), AA(aa),
586      FuncInfo(funcinfo), GCI(gci) {
587  }
588
589  /// getRoot - Return the current virtual root of the Selection DAG,
590  /// flushing any PendingLoad items. This must be done before emitting
591  /// a store or any other node that may need to be ordered after any
592  /// prior load instructions.
593  ///
594  SDOperand getRoot() {
595    if (PendingLoads.empty())
596      return DAG.getRoot();
597
598    if (PendingLoads.size() == 1) {
599      SDOperand Root = PendingLoads[0];
600      DAG.setRoot(Root);
601      PendingLoads.clear();
602      return Root;
603    }
604
605    // Otherwise, we have to make a token factor node.
606    SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
607                                 &PendingLoads[0], PendingLoads.size());
608    PendingLoads.clear();
609    DAG.setRoot(Root);
610    return Root;
611  }
612
613  /// getControlRoot - Similar to getRoot, but instead of flushing all the
614  /// PendingLoad items, flush all the PendingExports items. It is necessary
615  /// to do this before emitting a terminator instruction.
616  ///
617  SDOperand getControlRoot() {
618    SDOperand Root = DAG.getRoot();
619
620    if (PendingExports.empty())
621      return Root;
622
623    // Turn all of the CopyToReg chains into one factored node.
624    if (Root.getOpcode() != ISD::EntryToken) {
625      unsigned i = 0, e = PendingExports.size();
626      for (; i != e; ++i) {
627        assert(PendingExports[i].Val->getNumOperands() > 1);
628        if (PendingExports[i].Val->getOperand(0) == Root)
629          break;  // Don't add the root if we already indirectly depend on it.
630      }
631
632      if (i == e)
633        PendingExports.push_back(Root);
634    }
635
636    Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
637                       &PendingExports[0],
638                       PendingExports.size());
639    PendingExports.clear();
640    DAG.setRoot(Root);
641    return Root;
642  }
643
644  void CopyValueToVirtualRegister(Value *V, unsigned Reg);
645
646  void visit(Instruction &I) { visit(I.getOpcode(), I); }
647
648  void visit(unsigned Opcode, User &I) {
649    // Note: this doesn't use InstVisitor, because it has to work with
650    // ConstantExpr's in addition to instructions.
651    switch (Opcode) {
652    default: assert(0 && "Unknown instruction type encountered!");
653             abort();
654      // Build the switch statement using the Instruction.def file.
655#define HANDLE_INST(NUM, OPCODE, CLASS) \
656    case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
657#include "llvm/Instruction.def"
658    }
659  }
660
661  void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
662
663  SDOperand getValue(const Value *V);
664
665  void setValue(const Value *V, SDOperand NewN) {
666    SDOperand &N = NodeMap[V];
667    assert(N.Val == 0 && "Already set a value for this node!");
668    N = NewN;
669  }
670
671  void GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
672                            std::set<unsigned> &OutputRegs,
673                            std::set<unsigned> &InputRegs);
674
675  void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
676                            MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
677                            unsigned Opc);
678  bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
679  void ExportFromCurrentBlock(Value *V);
680  void LowerCallTo(CallSite CS, SDOperand Callee, bool IsTailCall,
681                   MachineBasicBlock *LandingPad = NULL);
682
683  // Terminator instructions.
684  void visitRet(ReturnInst &I);
685  void visitBr(BranchInst &I);
686  void visitSwitch(SwitchInst &I);
687  void visitUnreachable(UnreachableInst &I) { /* noop */ }
688
689  // Helpers for visitSwitch
690  bool handleSmallSwitchRange(CaseRec& CR,
691                              CaseRecVector& WorkList,
692                              Value* SV,
693                              MachineBasicBlock* Default);
694  bool handleJTSwitchCase(CaseRec& CR,
695                          CaseRecVector& WorkList,
696                          Value* SV,
697                          MachineBasicBlock* Default);
698  bool handleBTSplitSwitchCase(CaseRec& CR,
699                               CaseRecVector& WorkList,
700                               Value* SV,
701                               MachineBasicBlock* Default);
702  bool handleBitTestsSwitchCase(CaseRec& CR,
703                                CaseRecVector& WorkList,
704                                Value* SV,
705                                MachineBasicBlock* Default);
706  void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
707  void visitBitTestHeader(SelectionDAGISel::BitTestBlock &B);
708  void visitBitTestCase(MachineBasicBlock* NextMBB,
709                        unsigned Reg,
710                        SelectionDAGISel::BitTestCase &B);
711  void visitJumpTable(SelectionDAGISel::JumpTable &JT);
712  void visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
713                            SelectionDAGISel::JumpTableHeader &JTH);
714
715  // These all get lowered before this pass.
716  void visitInvoke(InvokeInst &I);
717  void visitUnwind(UnwindInst &I);
718
719  void visitBinary(User &I, unsigned OpCode);
720  void visitShift(User &I, unsigned Opcode);
721  void visitAdd(User &I) {
722    if (I.getType()->isFPOrFPVector())
723      visitBinary(I, ISD::FADD);
724    else
725      visitBinary(I, ISD::ADD);
726  }
727  void visitSub(User &I);
728  void visitMul(User &I) {
729    if (I.getType()->isFPOrFPVector())
730      visitBinary(I, ISD::FMUL);
731    else
732      visitBinary(I, ISD::MUL);
733  }
734  void visitURem(User &I) { visitBinary(I, ISD::UREM); }
735  void visitSRem(User &I) { visitBinary(I, ISD::SREM); }
736  void visitFRem(User &I) { visitBinary(I, ISD::FREM); }
737  void visitUDiv(User &I) { visitBinary(I, ISD::UDIV); }
738  void visitSDiv(User &I) { visitBinary(I, ISD::SDIV); }
739  void visitFDiv(User &I) { visitBinary(I, ISD::FDIV); }
740  void visitAnd (User &I) { visitBinary(I, ISD::AND); }
741  void visitOr  (User &I) { visitBinary(I, ISD::OR); }
742  void visitXor (User &I) { visitBinary(I, ISD::XOR); }
743  void visitShl (User &I) { visitShift(I, ISD::SHL); }
744  void visitLShr(User &I) { visitShift(I, ISD::SRL); }
745  void visitAShr(User &I) { visitShift(I, ISD::SRA); }
746  void visitICmp(User &I);
747  void visitFCmp(User &I);
748  void visitVICmp(User &I);
749  void visitVFCmp(User &I);
750  // Visit the conversion instructions
751  void visitTrunc(User &I);
752  void visitZExt(User &I);
753  void visitSExt(User &I);
754  void visitFPTrunc(User &I);
755  void visitFPExt(User &I);
756  void visitFPToUI(User &I);
757  void visitFPToSI(User &I);
758  void visitUIToFP(User &I);
759  void visitSIToFP(User &I);
760  void visitPtrToInt(User &I);
761  void visitIntToPtr(User &I);
762  void visitBitCast(User &I);
763
764  void visitExtractElement(User &I);
765  void visitInsertElement(User &I);
766  void visitShuffleVector(User &I);
767
768  void visitExtractValue(ExtractValueInst &I);
769  void visitInsertValue(InsertValueInst &I);
770
771  void visitGetElementPtr(User &I);
772  void visitSelect(User &I);
773
774  void visitMalloc(MallocInst &I);
775  void visitFree(FreeInst &I);
776  void visitAlloca(AllocaInst &I);
777  void visitLoad(LoadInst &I);
778  void visitStore(StoreInst &I);
779  void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
780  void visitCall(CallInst &I);
781  void visitInlineAsm(CallSite CS);
782  const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
783  void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
784
785  void visitVAStart(CallInst &I);
786  void visitVAArg(VAArgInst &I);
787  void visitVAEnd(CallInst &I);
788  void visitVACopy(CallInst &I);
789
790  void visitGetResult(GetResultInst &I);
791
792  void visitUserOp1(Instruction &I) {
793    assert(0 && "UserOp1 should not exist at instruction selection time!");
794    abort();
795  }
796  void visitUserOp2(Instruction &I) {
797    assert(0 && "UserOp2 should not exist at instruction selection time!");
798    abort();
799  }
800
801private:
802  inline const char *implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op);
803
804};
805} // end namespace llvm
806
807
808/// getCopyFromParts - Create a value that contains the specified legal parts
809/// combined into the value they represent.  If the parts combine to a type
810/// larger then ValueVT then AssertOp can be used to specify whether the extra
811/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
812/// (ISD::AssertSext).
813static SDOperand getCopyFromParts(SelectionDAG &DAG,
814                                  const SDOperand *Parts,
815                                  unsigned NumParts,
816                                  MVT PartVT,
817                                  MVT ValueVT,
818                                  ISD::NodeType AssertOp = ISD::DELETED_NODE) {
819  assert(NumParts > 0 && "No parts to assemble!");
820  TargetLowering &TLI = DAG.getTargetLoweringInfo();
821  SDOperand Val = Parts[0];
822
823  if (NumParts > 1) {
824    // Assemble the value from multiple parts.
825    if (!ValueVT.isVector()) {
826      unsigned PartBits = PartVT.getSizeInBits();
827      unsigned ValueBits = ValueVT.getSizeInBits();
828
829      // Assemble the power of 2 part.
830      unsigned RoundParts = NumParts & (NumParts - 1) ?
831        1 << Log2_32(NumParts) : NumParts;
832      unsigned RoundBits = PartBits * RoundParts;
833      MVT RoundVT = RoundBits == ValueBits ?
834        ValueVT : MVT::getIntegerVT(RoundBits);
835      SDOperand Lo, Hi;
836
837      if (RoundParts > 2) {
838        MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
839        Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
840        Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
841                              PartVT, HalfVT);
842      } else {
843        Lo = Parts[0];
844        Hi = Parts[1];
845      }
846      if (TLI.isBigEndian())
847        std::swap(Lo, Hi);
848      Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
849
850      if (RoundParts < NumParts) {
851        // Assemble the trailing non-power-of-2 part.
852        unsigned OddParts = NumParts - RoundParts;
853        MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
854        Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
855
856        // Combine the round and odd parts.
857        Lo = Val;
858        if (TLI.isBigEndian())
859          std::swap(Lo, Hi);
860        MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
861        Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
862        Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
863                         DAG.getConstant(Lo.getValueType().getSizeInBits(),
864                                         TLI.getShiftAmountTy()));
865        Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
866        Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
867      }
868    } else {
869      // Handle a multi-element vector.
870      MVT IntermediateVT, RegisterVT;
871      unsigned NumIntermediates;
872      unsigned NumRegs =
873        TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
874                                   RegisterVT);
875      assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
876      NumParts = NumRegs; // Silence a compiler warning.
877      assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
878      assert(RegisterVT == Parts[0].getValueType() &&
879             "Part type doesn't match part!");
880
881      // Assemble the parts into intermediate operands.
882      SmallVector<SDOperand, 8> Ops(NumIntermediates);
883      if (NumIntermediates == NumParts) {
884        // If the register was not expanded, truncate or copy the value,
885        // as appropriate.
886        for (unsigned i = 0; i != NumParts; ++i)
887          Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
888                                    PartVT, IntermediateVT);
889      } else if (NumParts > 0) {
890        // If the intermediate type was expanded, build the intermediate operands
891        // from the parts.
892        assert(NumParts % NumIntermediates == 0 &&
893               "Must expand into a divisible number of parts!");
894        unsigned Factor = NumParts / NumIntermediates;
895        for (unsigned i = 0; i != NumIntermediates; ++i)
896          Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
897                                    PartVT, IntermediateVT);
898      }
899
900      // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
901      // operands.
902      Val = DAG.getNode(IntermediateVT.isVector() ?
903                        ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
904                        ValueVT, &Ops[0], NumIntermediates);
905    }
906  }
907
908  // There is now one part, held in Val.  Correct it to match ValueVT.
909  PartVT = Val.getValueType();
910
911  if (PartVT == ValueVT)
912    return Val;
913
914  if (PartVT.isVector()) {
915    assert(ValueVT.isVector() && "Unknown vector conversion!");
916    return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
917  }
918
919  if (ValueVT.isVector()) {
920    assert(ValueVT.getVectorElementType() == PartVT &&
921           ValueVT.getVectorNumElements() == 1 &&
922           "Only trivial scalar-to-vector conversions should get here!");
923    return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
924  }
925
926  if (PartVT.isInteger() &&
927      ValueVT.isInteger()) {
928    if (ValueVT.bitsLT(PartVT)) {
929      // For a truncate, see if we have any information to
930      // indicate whether the truncated bits will always be
931      // zero or sign-extension.
932      if (AssertOp != ISD::DELETED_NODE)
933        Val = DAG.getNode(AssertOp, PartVT, Val,
934                          DAG.getValueType(ValueVT));
935      return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
936    } else {
937      return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
938    }
939  }
940
941  if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
942    if (ValueVT.bitsLT(Val.getValueType()))
943      // FP_ROUND's are always exact here.
944      return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
945                         DAG.getIntPtrConstant(1));
946    return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
947  }
948
949  if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
950    return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
951
952  assert(0 && "Unknown mismatch!");
953  return SDOperand();
954}
955
956/// getCopyToParts - Create a series of nodes that contain the specified value
957/// split into legal parts.  If the parts contain more bits than Val, then, for
958/// integers, ExtendKind can be used to specify how to generate the extra bits.
959static void getCopyToParts(SelectionDAG &DAG,
960                           SDOperand Val,
961                           SDOperand *Parts,
962                           unsigned NumParts,
963                           MVT PartVT,
964                           ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
965  TargetLowering &TLI = DAG.getTargetLoweringInfo();
966  MVT PtrVT = TLI.getPointerTy();
967  MVT ValueVT = Val.getValueType();
968  unsigned PartBits = PartVT.getSizeInBits();
969  assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
970
971  if (!NumParts)
972    return;
973
974  if (!ValueVT.isVector()) {
975    if (PartVT == ValueVT) {
976      assert(NumParts == 1 && "No-op copy with multiple parts!");
977      Parts[0] = Val;
978      return;
979    }
980
981    if (NumParts * PartBits > ValueVT.getSizeInBits()) {
982      // If the parts cover more bits than the value has, promote the value.
983      if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
984        assert(NumParts == 1 && "Do not know what to promote to!");
985        Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
986      } else if (PartVT.isInteger() && ValueVT.isInteger()) {
987        ValueVT = MVT::getIntegerVT(NumParts * PartBits);
988        Val = DAG.getNode(ExtendKind, ValueVT, Val);
989      } else {
990        assert(0 && "Unknown mismatch!");
991      }
992    } else if (PartBits == ValueVT.getSizeInBits()) {
993      // Different types of the same size.
994      assert(NumParts == 1 && PartVT != ValueVT);
995      Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
996    } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
997      // If the parts cover less bits than value has, truncate the value.
998      if (PartVT.isInteger() && ValueVT.isInteger()) {
999        ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1000        Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1001      } else {
1002        assert(0 && "Unknown mismatch!");
1003      }
1004    }
1005
1006    // The value may have changed - recompute ValueVT.
1007    ValueVT = Val.getValueType();
1008    assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
1009           "Failed to tile the value with PartVT!");
1010
1011    if (NumParts == 1) {
1012      assert(PartVT == ValueVT && "Type conversion failed!");
1013      Parts[0] = Val;
1014      return;
1015    }
1016
1017    // Expand the value into multiple parts.
1018    if (NumParts & (NumParts - 1)) {
1019      // The number of parts is not a power of 2.  Split off and copy the tail.
1020      assert(PartVT.isInteger() && ValueVT.isInteger() &&
1021             "Do not know what to expand to!");
1022      unsigned RoundParts = 1 << Log2_32(NumParts);
1023      unsigned RoundBits = RoundParts * PartBits;
1024      unsigned OddParts = NumParts - RoundParts;
1025      SDOperand OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
1026                                     DAG.getConstant(RoundBits,
1027                                                     TLI.getShiftAmountTy()));
1028      getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
1029      if (TLI.isBigEndian())
1030        // The odd parts were reversed by getCopyToParts - unreverse them.
1031        std::reverse(Parts + RoundParts, Parts + NumParts);
1032      NumParts = RoundParts;
1033      ValueVT = MVT::getIntegerVT(NumParts * PartBits);
1034      Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1035    }
1036
1037    // The number of parts is a power of 2.  Repeatedly bisect the value using
1038    // EXTRACT_ELEMENT.
1039    Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
1040                           MVT::getIntegerVT(ValueVT.getSizeInBits()),
1041                           Val);
1042    for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
1043      for (unsigned i = 0; i < NumParts; i += StepSize) {
1044        unsigned ThisBits = StepSize * PartBits / 2;
1045        MVT ThisVT = MVT::getIntegerVT (ThisBits);
1046        SDOperand &Part0 = Parts[i];
1047        SDOperand &Part1 = Parts[i+StepSize/2];
1048
1049        Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1050                            DAG.getConstant(1, PtrVT));
1051        Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
1052                            DAG.getConstant(0, PtrVT));
1053
1054        if (ThisBits == PartBits && ThisVT != PartVT) {
1055          Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
1056          Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
1057        }
1058      }
1059    }
1060
1061    if (TLI.isBigEndian())
1062      std::reverse(Parts, Parts + NumParts);
1063
1064    return;
1065  }
1066
1067  // Vector ValueVT.
1068  if (NumParts == 1) {
1069    if (PartVT != ValueVT) {
1070      if (PartVT.isVector()) {
1071        Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
1072      } else {
1073        assert(ValueVT.getVectorElementType() == PartVT &&
1074               ValueVT.getVectorNumElements() == 1 &&
1075               "Only trivial vector-to-scalar conversions should get here!");
1076        Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
1077                          DAG.getConstant(0, PtrVT));
1078      }
1079    }
1080
1081    Parts[0] = Val;
1082    return;
1083  }
1084
1085  // Handle a multi-element vector.
1086  MVT IntermediateVT, RegisterVT;
1087  unsigned NumIntermediates;
1088  unsigned NumRegs =
1089    DAG.getTargetLoweringInfo()
1090      .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
1091                              RegisterVT);
1092  unsigned NumElements = ValueVT.getVectorNumElements();
1093
1094  assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
1095  NumParts = NumRegs; // Silence a compiler warning.
1096  assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
1097
1098  // Split the vector into intermediate operands.
1099  SmallVector<SDOperand, 8> Ops(NumIntermediates);
1100  for (unsigned i = 0; i != NumIntermediates; ++i)
1101    if (IntermediateVT.isVector())
1102      Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
1103                           IntermediateVT, Val,
1104                           DAG.getConstant(i * (NumElements / NumIntermediates),
1105                                           PtrVT));
1106    else
1107      Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
1108                           IntermediateVT, Val,
1109                           DAG.getConstant(i, PtrVT));
1110
1111  // Split the intermediate operands into legal parts.
1112  if (NumParts == NumIntermediates) {
1113    // If the register was not expanded, promote or copy the value,
1114    // as appropriate.
1115    for (unsigned i = 0; i != NumParts; ++i)
1116      getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
1117  } else if (NumParts > 0) {
1118    // If the intermediate type was expanded, split each the value into
1119    // legal parts.
1120    assert(NumParts % NumIntermediates == 0 &&
1121           "Must expand into a divisible number of parts!");
1122    unsigned Factor = NumParts / NumIntermediates;
1123    for (unsigned i = 0; i != NumIntermediates; ++i)
1124      getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
1125  }
1126}
1127
1128
1129SDOperand SelectionDAGLowering::getValue(const Value *V) {
1130  SDOperand &N = NodeMap[V];
1131  if (N.Val) return N;
1132
1133  if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
1134    MVT VT = TLI.getValueType(V->getType(), true);
1135
1136    if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1137      return N = DAG.getConstant(CI->getValue(), VT);
1138
1139    if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
1140      return N = DAG.getGlobalAddress(GV, VT);
1141
1142    if (isa<ConstantPointerNull>(C))
1143      return N = DAG.getConstant(0, TLI.getPointerTy());
1144
1145    if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1146      return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
1147
1148    if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
1149        !V->getType()->isAggregateType())
1150      return N = DAG.getNode(ISD::UNDEF, VT);
1151
1152    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1153      visit(CE->getOpcode(), *CE);
1154      SDOperand N1 = NodeMap[V];
1155      assert(N1.Val && "visit didn't populate the ValueMap!");
1156      return N1;
1157    }
1158
1159    if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1160      SmallVector<SDOperand, 4> Constants;
1161      SmallVector<MVT, 4> ValueVTs;
1162      for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1163           OI != OE; ++OI) {
1164        SDNode *Val = getValue(*OI).Val;
1165        for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i) {
1166          Constants.push_back(SDOperand(Val, i));
1167          ValueVTs.push_back(Val->getValueType(i));
1168        }
1169      }
1170      return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1171                                &Constants[0], Constants.size());
1172    }
1173
1174    if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
1175      assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1176             "Unknown array constant!");
1177      unsigned NumElts = ATy->getNumElements();
1178      if (NumElts == 0)
1179        return SDOperand(); // empty array
1180      MVT EltVT = TLI.getValueType(ATy->getElementType());
1181      SmallVector<SDOperand, 4> Constants(NumElts);
1182      SmallVector<MVT, 4> ValueVTs(NumElts, EltVT);
1183      for (unsigned i = 0, e = NumElts; i != e; ++i) {
1184        if (isa<UndefValue>(C))
1185          Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1186        else if (EltVT.isFloatingPoint())
1187          Constants[i] = DAG.getConstantFP(0, EltVT);
1188        else
1189          Constants[i] = DAG.getConstant(0, EltVT);
1190      }
1191      return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1192                                &Constants[0], Constants.size());
1193    }
1194
1195    if (const StructType *STy = dyn_cast<StructType>(C->getType())) {
1196      assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1197             "Unknown struct constant!");
1198      unsigned NumElts = STy->getNumElements();
1199      if (NumElts == 0)
1200        return SDOperand(); // empty struct
1201      SmallVector<SDOperand, 4> Constants(NumElts);
1202      SmallVector<MVT, 4> ValueVTs(NumElts);
1203      for (unsigned i = 0, e = NumElts; i != e; ++i) {
1204        MVT EltVT = TLI.getValueType(STy->getElementType(i));
1205        ValueVTs[i] = EltVT;
1206        if (isa<UndefValue>(C))
1207          Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
1208        else if (EltVT.isFloatingPoint())
1209          Constants[i] = DAG.getConstantFP(0, EltVT);
1210        else
1211          Constants[i] = DAG.getConstant(0, EltVT);
1212      }
1213      return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1214                                &Constants[0], Constants.size());
1215    }
1216
1217    const VectorType *VecTy = cast<VectorType>(V->getType());
1218    unsigned NumElements = VecTy->getNumElements();
1219
1220    // Now that we know the number and type of the elements, get that number of
1221    // elements into the Ops array based on what kind of constant it is.
1222    SmallVector<SDOperand, 16> Ops;
1223    if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1224      for (unsigned i = 0; i != NumElements; ++i)
1225        Ops.push_back(getValue(CP->getOperand(i)));
1226    } else {
1227      assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1228             "Unknown vector constant!");
1229      MVT EltVT = TLI.getValueType(VecTy->getElementType());
1230
1231      SDOperand Op;
1232      if (isa<UndefValue>(C))
1233        Op = DAG.getNode(ISD::UNDEF, EltVT);
1234      else if (EltVT.isFloatingPoint())
1235        Op = DAG.getConstantFP(0, EltVT);
1236      else
1237        Op = DAG.getConstant(0, EltVT);
1238      Ops.assign(NumElements, Op);
1239    }
1240
1241    // Create a BUILD_VECTOR node.
1242    return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
1243  }
1244
1245  // If this is a static alloca, generate it as the frameindex instead of
1246  // computation.
1247  if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1248    std::map<const AllocaInst*, int>::iterator SI =
1249      FuncInfo.StaticAllocaMap.find(AI);
1250    if (SI != FuncInfo.StaticAllocaMap.end())
1251      return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1252  }
1253
1254  unsigned InReg = FuncInfo.ValueMap[V];
1255  assert(InReg && "Value not in map!");
1256
1257  RegsForValue RFV(TLI, InReg, V->getType());
1258  SDOperand Chain = DAG.getEntryNode();
1259  return RFV.getCopyFromRegs(DAG, Chain, NULL);
1260}
1261
1262
1263void SelectionDAGLowering::visitRet(ReturnInst &I) {
1264  if (I.getNumOperands() == 0) {
1265    DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
1266    return;
1267  }
1268
1269  SmallVector<SDOperand, 8> NewValues;
1270  NewValues.push_back(getControlRoot());
1271  for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1272    SDOperand RetOp = getValue(I.getOperand(i));
1273
1274    SmallVector<MVT, 4> ValueVTs;
1275    ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1276    for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
1277      MVT VT = ValueVTs[j];
1278
1279      // FIXME: C calling convention requires the return type to be promoted to
1280      // at least 32-bit. But this is not necessary for non-C calling conventions.
1281      if (VT.isInteger()) {
1282        MVT MinVT = TLI.getRegisterType(MVT::i32);
1283        if (VT.bitsLT(MinVT))
1284          VT = MinVT;
1285      }
1286
1287      unsigned NumParts = TLI.getNumRegisters(VT);
1288      MVT PartVT = TLI.getRegisterType(VT);
1289      SmallVector<SDOperand, 4> Parts(NumParts);
1290      ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1291
1292      const Function *F = I.getParent()->getParent();
1293      if (F->paramHasAttr(0, ParamAttr::SExt))
1294        ExtendKind = ISD::SIGN_EXTEND;
1295      else if (F->paramHasAttr(0, ParamAttr::ZExt))
1296        ExtendKind = ISD::ZERO_EXTEND;
1297
1298      getCopyToParts(DAG, SDOperand(RetOp.Val, RetOp.ResNo + j),
1299                     &Parts[0], NumParts, PartVT, ExtendKind);
1300
1301      for (unsigned i = 0; i < NumParts; ++i) {
1302        NewValues.push_back(Parts[i]);
1303        NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
1304      }
1305    }
1306  }
1307  DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
1308                          &NewValues[0], NewValues.size()));
1309}
1310
1311/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1312/// the current basic block, add it to ValueMap now so that we'll get a
1313/// CopyTo/FromReg.
1314void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1315  // No need to export constants.
1316  if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1317
1318  // Already exported?
1319  if (FuncInfo.isExportedInst(V)) return;
1320
1321  unsigned Reg = FuncInfo.InitializeRegForValue(V);
1322  CopyValueToVirtualRegister(V, Reg);
1323}
1324
1325bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1326                                                    const BasicBlock *FromBB) {
1327  // The operands of the setcc have to be in this block.  We don't know
1328  // how to export them from some other block.
1329  if (Instruction *VI = dyn_cast<Instruction>(V)) {
1330    // Can export from current BB.
1331    if (VI->getParent() == FromBB)
1332      return true;
1333
1334    // Is already exported, noop.
1335    return FuncInfo.isExportedInst(V);
1336  }
1337
1338  // If this is an argument, we can export it if the BB is the entry block or
1339  // if it is already exported.
1340  if (isa<Argument>(V)) {
1341    if (FromBB == &FromBB->getParent()->getEntryBlock())
1342      return true;
1343
1344    // Otherwise, can only export this if it is already exported.
1345    return FuncInfo.isExportedInst(V);
1346  }
1347
1348  // Otherwise, constants can always be exported.
1349  return true;
1350}
1351
1352static bool InBlock(const Value *V, const BasicBlock *BB) {
1353  if (const Instruction *I = dyn_cast<Instruction>(V))
1354    return I->getParent() == BB;
1355  return true;
1356}
1357
1358/// FindMergedConditions - If Cond is an expression like
1359void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1360                                                MachineBasicBlock *TBB,
1361                                                MachineBasicBlock *FBB,
1362                                                MachineBasicBlock *CurBB,
1363                                                unsigned Opc) {
1364  // If this node is not part of the or/and tree, emit it as a branch.
1365  Instruction *BOp = dyn_cast<Instruction>(Cond);
1366
1367  if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1368      (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1369      BOp->getParent() != CurBB->getBasicBlock() ||
1370      !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1371      !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1372    const BasicBlock *BB = CurBB->getBasicBlock();
1373
1374    // If the leaf of the tree is a comparison, merge the condition into
1375    // the caseblock.
1376    if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1377        // The operands of the cmp have to be in this block.  We don't know
1378        // how to export them from some other block.  If this is the first block
1379        // of the sequence, no exporting is needed.
1380        (CurBB == CurMBB ||
1381         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1382          isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1383      BOp = cast<Instruction>(Cond);
1384      ISD::CondCode Condition;
1385      if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1386        switch (IC->getPredicate()) {
1387        default: assert(0 && "Unknown icmp predicate opcode!");
1388        case ICmpInst::ICMP_EQ:  Condition = ISD::SETEQ;  break;
1389        case ICmpInst::ICMP_NE:  Condition = ISD::SETNE;  break;
1390        case ICmpInst::ICMP_SLE: Condition = ISD::SETLE;  break;
1391        case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1392        case ICmpInst::ICMP_SGE: Condition = ISD::SETGE;  break;
1393        case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1394        case ICmpInst::ICMP_SLT: Condition = ISD::SETLT;  break;
1395        case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1396        case ICmpInst::ICMP_SGT: Condition = ISD::SETGT;  break;
1397        case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1398        }
1399      } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1400        ISD::CondCode FPC, FOC;
1401        switch (FC->getPredicate()) {
1402        default: assert(0 && "Unknown fcmp predicate opcode!");
1403        case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1404        case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1405        case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1406        case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1407        case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1408        case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1409        case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1410        case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
1411        case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
1412        case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1413        case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1414        case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1415        case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1416        case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1417        case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1418        case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
1419        }
1420        if (FiniteOnlyFPMath())
1421          Condition = FOC;
1422        else
1423          Condition = FPC;
1424      } else {
1425        Condition = ISD::SETEQ; // silence warning.
1426        assert(0 && "Unknown compare instruction");
1427      }
1428
1429      SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0),
1430                                     BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1431      SwitchCases.push_back(CB);
1432      return;
1433    }
1434
1435    // Create a CaseBlock record representing this branch.
1436    SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1437                                   NULL, TBB, FBB, CurBB);
1438    SwitchCases.push_back(CB);
1439    return;
1440  }
1441
1442
1443  //  Create TmpBB after CurBB.
1444  MachineFunction::iterator BBI = CurBB;
1445  MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
1446  CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
1447
1448  if (Opc == Instruction::Or) {
1449    // Codegen X | Y as:
1450    //   jmp_if_X TBB
1451    //   jmp TmpBB
1452    // TmpBB:
1453    //   jmp_if_Y TBB
1454    //   jmp FBB
1455    //
1456
1457    // Emit the LHS condition.
1458    FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1459
1460    // Emit the RHS condition into TmpBB.
1461    FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1462  } else {
1463    assert(Opc == Instruction::And && "Unknown merge op!");
1464    // Codegen X & Y as:
1465    //   jmp_if_X TmpBB
1466    //   jmp FBB
1467    // TmpBB:
1468    //   jmp_if_Y TBB
1469    //   jmp FBB
1470    //
1471    //  This requires creation of TmpBB after CurBB.
1472
1473    // Emit the LHS condition.
1474    FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1475
1476    // Emit the RHS condition into TmpBB.
1477    FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1478  }
1479}
1480
1481/// If the set of cases should be emitted as a series of branches, return true.
1482/// If we should emit this as a bunch of and/or'd together conditions, return
1483/// false.
1484static bool
1485ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
1486  if (Cases.size() != 2) return true;
1487
1488  // If this is two comparisons of the same values or'd or and'd together, they
1489  // will get folded into a single comparison, so don't emit two blocks.
1490  if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1491       Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1492      (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1493       Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1494    return false;
1495  }
1496
1497  return true;
1498}
1499
1500void SelectionDAGLowering::visitBr(BranchInst &I) {
1501  // Update machine-CFG edges.
1502  MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1503
1504  // Figure out which block is immediately after the current one.
1505  MachineBasicBlock *NextBlock = 0;
1506  MachineFunction::iterator BBI = CurMBB;
1507  if (++BBI != CurMBB->getParent()->end())
1508    NextBlock = BBI;
1509
1510  if (I.isUnconditional()) {
1511    // Update machine-CFG edges.
1512    CurMBB->addSuccessor(Succ0MBB);
1513
1514    // If this is not a fall-through branch, emit the branch.
1515    if (Succ0MBB != NextBlock)
1516      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1517                              DAG.getBasicBlock(Succ0MBB)));
1518    return;
1519  }
1520
1521  // If this condition is one of the special cases we handle, do special stuff
1522  // now.
1523  Value *CondVal = I.getCondition();
1524  MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1525
1526  // If this is a series of conditions that are or'd or and'd together, emit
1527  // this as a sequence of branches instead of setcc's with and/or operations.
1528  // For example, instead of something like:
1529  //     cmp A, B
1530  //     C = seteq
1531  //     cmp D, E
1532  //     F = setle
1533  //     or C, F
1534  //     jnz foo
1535  // Emit:
1536  //     cmp A, B
1537  //     je foo
1538  //     cmp D, E
1539  //     jle foo
1540  //
1541  if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1542    if (BOp->hasOneUse() &&
1543        (BOp->getOpcode() == Instruction::And ||
1544         BOp->getOpcode() == Instruction::Or)) {
1545      FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1546      // If the compares in later blocks need to use values not currently
1547      // exported from this block, export them now.  This block should always
1548      // be the first entry.
1549      assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1550
1551      // Allow some cases to be rejected.
1552      if (ShouldEmitAsBranches(SwitchCases)) {
1553        for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1554          ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1555          ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1556        }
1557
1558        // Emit the branch for this block.
1559        visitSwitchCase(SwitchCases[0]);
1560        SwitchCases.erase(SwitchCases.begin());
1561        return;
1562      }
1563
1564      // Okay, we decided not to do this, remove any inserted MBB's and clear
1565      // SwitchCases.
1566      for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1567        CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1568
1569      SwitchCases.clear();
1570    }
1571  }
1572
1573  // Create a CaseBlock record representing this branch.
1574  SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1575                                 NULL, Succ0MBB, Succ1MBB, CurMBB);
1576  // Use visitSwitchCase to actually insert the fast branch sequence for this
1577  // cond branch.
1578  visitSwitchCase(CB);
1579}
1580
1581/// visitSwitchCase - Emits the necessary code to represent a single node in
1582/// the binary search tree resulting from lowering a switch instruction.
1583void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1584  SDOperand Cond;
1585  SDOperand CondLHS = getValue(CB.CmpLHS);
1586
1587  // Build the setcc now.
1588  if (CB.CmpMHS == NULL) {
1589    // Fold "(X == true)" to X and "(X == false)" to !X to
1590    // handle common cases produced by branch lowering.
1591    if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1592      Cond = CondLHS;
1593    else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1594      SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1595      Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1596    } else
1597      Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1598  } else {
1599    assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1600
1601    uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1602    uint64_t High  = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1603
1604    SDOperand CmpOp = getValue(CB.CmpMHS);
1605    MVT VT = CmpOp.getValueType();
1606
1607    if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1608      Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1609    } else {
1610      SDOperand SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1611      Cond = DAG.getSetCC(MVT::i1, SUB,
1612                          DAG.getConstant(High-Low, VT), ISD::SETULE);
1613    }
1614  }
1615
1616  // Update successor info
1617  CurMBB->addSuccessor(CB.TrueBB);
1618  CurMBB->addSuccessor(CB.FalseBB);
1619
1620  // Set NextBlock to be the MBB immediately after the current one, if any.
1621  // This is used to avoid emitting unnecessary branches to the next block.
1622  MachineBasicBlock *NextBlock = 0;
1623  MachineFunction::iterator BBI = CurMBB;
1624  if (++BBI != CurMBB->getParent()->end())
1625    NextBlock = BBI;
1626
1627  // If the lhs block is the next block, invert the condition so that we can
1628  // fall through to the lhs instead of the rhs block.
1629  if (CB.TrueBB == NextBlock) {
1630    std::swap(CB.TrueBB, CB.FalseBB);
1631    SDOperand True = DAG.getConstant(1, Cond.getValueType());
1632    Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1633  }
1634  SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1635                                 DAG.getBasicBlock(CB.TrueBB));
1636  if (CB.FalseBB == NextBlock)
1637    DAG.setRoot(BrCond);
1638  else
1639    DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1640                            DAG.getBasicBlock(CB.FalseBB)));
1641}
1642
1643/// visitJumpTable - Emit JumpTable node in the current MBB
1644void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1645  // Emit the code for the jump table
1646  assert(JT.Reg != -1U && "Should lower JT Header first!");
1647  MVT PTy = TLI.getPointerTy();
1648  SDOperand Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1649  SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1650  DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1651                          Table, Index));
1652  return;
1653}
1654
1655/// visitJumpTableHeader - This function emits necessary code to produce index
1656/// in the JumpTable from switch case.
1657void SelectionDAGLowering::visitJumpTableHeader(SelectionDAGISel::JumpTable &JT,
1658                                         SelectionDAGISel::JumpTableHeader &JTH) {
1659  // Subtract the lowest switch case value from the value being switched on
1660  // and conditional branch to default mbb if the result is greater than the
1661  // difference between smallest and largest cases.
1662  SDOperand SwitchOp = getValue(JTH.SValue);
1663  MVT VT = SwitchOp.getValueType();
1664  SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1665                              DAG.getConstant(JTH.First, VT));
1666
1667  // The SDNode we just created, which holds the value being switched on
1668  // minus the the smallest case value, needs to be copied to a virtual
1669  // register so it can be used as an index into the jump table in a
1670  // subsequent basic block.  This value may be smaller or larger than the
1671  // target's pointer type, and therefore require extension or truncating.
1672  if (VT.bitsGT(TLI.getPointerTy()))
1673    SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1674  else
1675    SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1676
1677  unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1678  SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1679  JT.Reg = JumpTableReg;
1680
1681  // Emit the range check for the jump table, and branch to the default
1682  // block for the switch statement if the value being switched on exceeds
1683  // the largest case in the switch.
1684  SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1685                               DAG.getConstant(JTH.Last-JTH.First,VT),
1686                               ISD::SETUGT);
1687
1688  // Set NextBlock to be the MBB immediately after the current one, if any.
1689  // This is used to avoid emitting unnecessary branches to the next block.
1690  MachineBasicBlock *NextBlock = 0;
1691  MachineFunction::iterator BBI = CurMBB;
1692  if (++BBI != CurMBB->getParent()->end())
1693    NextBlock = BBI;
1694
1695  SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1696                                 DAG.getBasicBlock(JT.Default));
1697
1698  if (JT.MBB == NextBlock)
1699    DAG.setRoot(BrCond);
1700  else
1701    DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1702                            DAG.getBasicBlock(JT.MBB)));
1703
1704  return;
1705}
1706
1707/// visitBitTestHeader - This function emits necessary code to produce value
1708/// suitable for "bit tests"
1709void SelectionDAGLowering::visitBitTestHeader(SelectionDAGISel::BitTestBlock &B) {
1710  // Subtract the minimum value
1711  SDOperand SwitchOp = getValue(B.SValue);
1712  MVT VT = SwitchOp.getValueType();
1713  SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1714                              DAG.getConstant(B.First, VT));
1715
1716  // Check range
1717  SDOperand RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1718                                    DAG.getConstant(B.Range, VT),
1719                                    ISD::SETUGT);
1720
1721  SDOperand ShiftOp;
1722  if (VT.bitsGT(TLI.getShiftAmountTy()))
1723    ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1724  else
1725    ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1726
1727  // Make desired shift
1728  SDOperand SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1729                                    DAG.getConstant(1, TLI.getPointerTy()),
1730                                    ShiftOp);
1731
1732  unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1733  SDOperand CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1734  B.Reg = SwitchReg;
1735
1736  // Set NextBlock to be the MBB immediately after the current one, if any.
1737  // This is used to avoid emitting unnecessary branches to the next block.
1738  MachineBasicBlock *NextBlock = 0;
1739  MachineFunction::iterator BBI = CurMBB;
1740  if (++BBI != CurMBB->getParent()->end())
1741    NextBlock = BBI;
1742
1743  MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1744
1745  CurMBB->addSuccessor(B.Default);
1746  CurMBB->addSuccessor(MBB);
1747
1748  SDOperand BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1749                                  DAG.getBasicBlock(B.Default));
1750
1751  if (MBB == NextBlock)
1752    DAG.setRoot(BrRange);
1753  else
1754    DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1755                            DAG.getBasicBlock(MBB)));
1756
1757  return;
1758}
1759
1760/// visitBitTestCase - this function produces one "bit test"
1761void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1762                                            unsigned Reg,
1763                                            SelectionDAGISel::BitTestCase &B) {
1764  // Emit bit tests and jumps
1765  SDOperand SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1766                                           TLI.getPointerTy());
1767
1768  SDOperand AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1769                                DAG.getConstant(B.Mask, TLI.getPointerTy()));
1770  SDOperand AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1771                                  DAG.getConstant(0, TLI.getPointerTy()),
1772                                  ISD::SETNE);
1773
1774  CurMBB->addSuccessor(B.TargetBB);
1775  CurMBB->addSuccessor(NextMBB);
1776
1777  SDOperand BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1778                                AndCmp, DAG.getBasicBlock(B.TargetBB));
1779
1780  // Set NextBlock to be the MBB immediately after the current one, if any.
1781  // This is used to avoid emitting unnecessary branches to the next block.
1782  MachineBasicBlock *NextBlock = 0;
1783  MachineFunction::iterator BBI = CurMBB;
1784  if (++BBI != CurMBB->getParent()->end())
1785    NextBlock = BBI;
1786
1787  if (NextMBB == NextBlock)
1788    DAG.setRoot(BrAnd);
1789  else
1790    DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1791                            DAG.getBasicBlock(NextMBB)));
1792
1793  return;
1794}
1795
1796void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1797  // Retrieve successors.
1798  MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1799  MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1800
1801  if (isa<InlineAsm>(I.getCalledValue()))
1802    visitInlineAsm(&I);
1803  else
1804    LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1805
1806  // If the value of the invoke is used outside of its defining block, make it
1807  // available as a virtual register.
1808  if (!I.use_empty()) {
1809    DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1810    if (VMI != FuncInfo.ValueMap.end())
1811      CopyValueToVirtualRegister(&I, VMI->second);
1812  }
1813
1814  // Update successor info
1815  CurMBB->addSuccessor(Return);
1816  CurMBB->addSuccessor(LandingPad);
1817
1818  // Drop into normal successor.
1819  DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1820                          DAG.getBasicBlock(Return)));
1821}
1822
1823void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1824}
1825
1826/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1827/// small case ranges).
1828bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1829                                                  CaseRecVector& WorkList,
1830                                                  Value* SV,
1831                                                  MachineBasicBlock* Default) {
1832  Case& BackCase  = *(CR.Range.second-1);
1833
1834  // Size is the number of Cases represented by this range.
1835  unsigned Size = CR.Range.second - CR.Range.first;
1836  if (Size > 3)
1837    return false;
1838
1839  // Get the MachineFunction which holds the current MBB.  This is used when
1840  // inserting any additional MBBs necessary to represent the switch.
1841  MachineFunction *CurMF = CurMBB->getParent();
1842
1843  // Figure out which block is immediately after the current one.
1844  MachineBasicBlock *NextBlock = 0;
1845  MachineFunction::iterator BBI = CR.CaseBB;
1846
1847  if (++BBI != CurMBB->getParent()->end())
1848    NextBlock = BBI;
1849
1850  // TODO: If any two of the cases has the same destination, and if one value
1851  // is the same as the other, but has one bit unset that the other has set,
1852  // use bit manipulation to do two compares at once.  For example:
1853  // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1854
1855  // Rearrange the case blocks so that the last one falls through if possible.
1856  if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1857    // The last case block won't fall through into 'NextBlock' if we emit the
1858    // branches in this order.  See if rearranging a case value would help.
1859    for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1860      if (I->BB == NextBlock) {
1861        std::swap(*I, BackCase);
1862        break;
1863      }
1864    }
1865  }
1866
1867  // Create a CaseBlock record representing a conditional branch to
1868  // the Case's target mbb if the value being switched on SV is equal
1869  // to C.
1870  MachineBasicBlock *CurBlock = CR.CaseBB;
1871  for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1872    MachineBasicBlock *FallThrough;
1873    if (I != E-1) {
1874      FallThrough = new MachineBasicBlock(CurBlock->getBasicBlock());
1875      CurMF->getBasicBlockList().insert(BBI, FallThrough);
1876    } else {
1877      // If the last case doesn't match, go to the default block.
1878      FallThrough = Default;
1879    }
1880
1881    Value *RHS, *LHS, *MHS;
1882    ISD::CondCode CC;
1883    if (I->High == I->Low) {
1884      // This is just small small case range :) containing exactly 1 case
1885      CC = ISD::SETEQ;
1886      LHS = SV; RHS = I->High; MHS = NULL;
1887    } else {
1888      CC = ISD::SETLE;
1889      LHS = I->Low; MHS = SV; RHS = I->High;
1890    }
1891    SelectionDAGISel::CaseBlock CB(CC, LHS, RHS, MHS,
1892                                   I->BB, FallThrough, CurBlock);
1893
1894    // If emitting the first comparison, just call visitSwitchCase to emit the
1895    // code into the current block.  Otherwise, push the CaseBlock onto the
1896    // vector to be later processed by SDISel, and insert the node's MBB
1897    // before the next MBB.
1898    if (CurBlock == CurMBB)
1899      visitSwitchCase(CB);
1900    else
1901      SwitchCases.push_back(CB);
1902
1903    CurBlock = FallThrough;
1904  }
1905
1906  return true;
1907}
1908
1909static inline bool areJTsAllowed(const TargetLowering &TLI) {
1910  return (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1911          TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1912}
1913
1914/// handleJTSwitchCase - Emit jumptable for current switch case range
1915bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1916                                              CaseRecVector& WorkList,
1917                                              Value* SV,
1918                                              MachineBasicBlock* Default) {
1919  Case& FrontCase = *CR.Range.first;
1920  Case& BackCase  = *(CR.Range.second-1);
1921
1922  int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1923  int64_t Last  = cast<ConstantInt>(BackCase.High)->getSExtValue();
1924
1925  uint64_t TSize = 0;
1926  for (CaseItr I = CR.Range.first, E = CR.Range.second;
1927       I!=E; ++I)
1928    TSize += I->size();
1929
1930  if (!areJTsAllowed(TLI) || TSize <= 3)
1931    return false;
1932
1933  double Density = (double)TSize / (double)((Last - First) + 1ULL);
1934  if (Density < 0.4)
1935    return false;
1936
1937  DOUT << "Lowering jump table\n"
1938       << "First entry: " << First << ". Last entry: " << Last << "\n"
1939       << "Size: " << TSize << ". Density: " << Density << "\n\n";
1940
1941  // Get the MachineFunction which holds the current MBB.  This is used when
1942  // inserting any additional MBBs necessary to represent the switch.
1943  MachineFunction *CurMF = CurMBB->getParent();
1944
1945  // Figure out which block is immediately after the current one.
1946  MachineBasicBlock *NextBlock = 0;
1947  MachineFunction::iterator BBI = CR.CaseBB;
1948
1949  if (++BBI != CurMBB->getParent()->end())
1950    NextBlock = BBI;
1951
1952  const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1953
1954  // Create a new basic block to hold the code for loading the address
1955  // of the jump table, and jumping to it.  Update successor information;
1956  // we will either branch to the default case for the switch, or the jump
1957  // table.
1958  MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1959  CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1960  CR.CaseBB->addSuccessor(Default);
1961  CR.CaseBB->addSuccessor(JumpTableBB);
1962
1963  // Build a vector of destination BBs, corresponding to each target
1964  // of the jump table. If the value of the jump table slot corresponds to
1965  // a case statement, push the case's BB onto the vector, otherwise, push
1966  // the default BB.
1967  std::vector<MachineBasicBlock*> DestBBs;
1968  int64_t TEI = First;
1969  for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1970    int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1971    int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1972
1973    if ((Low <= TEI) && (TEI <= High)) {
1974      DestBBs.push_back(I->BB);
1975      if (TEI==High)
1976        ++I;
1977    } else {
1978      DestBBs.push_back(Default);
1979    }
1980  }
1981
1982  // Update successor info. Add one edge to each unique successor.
1983  BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1984  for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1985         E = DestBBs.end(); I != E; ++I) {
1986    if (!SuccsHandled[(*I)->getNumber()]) {
1987      SuccsHandled[(*I)->getNumber()] = true;
1988      JumpTableBB->addSuccessor(*I);
1989    }
1990  }
1991
1992  // Create a jump table index for this jump table, or return an existing
1993  // one.
1994  unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1995
1996  // Set the jump table information so that we can codegen it as a second
1997  // MachineBasicBlock
1998  SelectionDAGISel::JumpTable JT(-1U, JTI, JumpTableBB, Default);
1999  SelectionDAGISel::JumpTableHeader JTH(First, Last, SV, CR.CaseBB,
2000                                        (CR.CaseBB == CurMBB));
2001  if (CR.CaseBB == CurMBB)
2002    visitJumpTableHeader(JT, JTH);
2003
2004  JTCases.push_back(SelectionDAGISel::JumpTableBlock(JTH, JT));
2005
2006  return true;
2007}
2008
2009/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2010/// 2 subtrees.
2011bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
2012                                                   CaseRecVector& WorkList,
2013                                                   Value* SV,
2014                                                   MachineBasicBlock* Default) {
2015  // Get the MachineFunction which holds the current MBB.  This is used when
2016  // inserting any additional MBBs necessary to represent the switch.
2017  MachineFunction *CurMF = CurMBB->getParent();
2018
2019  // Figure out which block is immediately after the current one.
2020  MachineBasicBlock *NextBlock = 0;
2021  MachineFunction::iterator BBI = CR.CaseBB;
2022
2023  if (++BBI != CurMBB->getParent()->end())
2024    NextBlock = BBI;
2025
2026  Case& FrontCase = *CR.Range.first;
2027  Case& BackCase  = *(CR.Range.second-1);
2028  const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2029
2030  // Size is the number of Cases represented by this range.
2031  unsigned Size = CR.Range.second - CR.Range.first;
2032
2033  int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
2034  int64_t Last  = cast<ConstantInt>(BackCase.High)->getSExtValue();
2035  double FMetric = 0;
2036  CaseItr Pivot = CR.Range.first + Size/2;
2037
2038  // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2039  // (heuristically) allow us to emit JumpTable's later.
2040  uint64_t TSize = 0;
2041  for (CaseItr I = CR.Range.first, E = CR.Range.second;
2042       I!=E; ++I)
2043    TSize += I->size();
2044
2045  uint64_t LSize = FrontCase.size();
2046  uint64_t RSize = TSize-LSize;
2047  DOUT << "Selecting best pivot: \n"
2048       << "First: " << First << ", Last: " << Last <<"\n"
2049       << "LSize: " << LSize << ", RSize: " << RSize << "\n";
2050  for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2051       J!=E; ++I, ++J) {
2052    int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
2053    int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
2054    assert((RBegin-LEnd>=1) && "Invalid case distance");
2055    double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
2056    double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
2057    double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
2058    // Should always split in some non-trivial place
2059    DOUT <<"=>Step\n"
2060         << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
2061         << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
2062         << "Metric: " << Metric << "\n";
2063    if (FMetric < Metric) {
2064      Pivot = J;
2065      FMetric = Metric;
2066      DOUT << "Current metric set to: " << FMetric << "\n";
2067    }
2068
2069    LSize += J->size();
2070    RSize -= J->size();
2071  }
2072  if (areJTsAllowed(TLI)) {
2073    // If our case is dense we *really* should handle it earlier!
2074    assert((FMetric > 0) && "Should handle dense range earlier!");
2075  } else {
2076    Pivot = CR.Range.first + Size/2;
2077  }
2078
2079  CaseRange LHSR(CR.Range.first, Pivot);
2080  CaseRange RHSR(Pivot, CR.Range.second);
2081  Constant *C = Pivot->Low;
2082  MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2083
2084  // We know that we branch to the LHS if the Value being switched on is
2085  // less than the Pivot value, C.  We use this to optimize our binary
2086  // tree a bit, by recognizing that if SV is greater than or equal to the
2087  // LHS's Case Value, and that Case Value is exactly one less than the
2088  // Pivot's Value, then we can branch directly to the LHS's Target,
2089  // rather than creating a leaf node for it.
2090  if ((LHSR.second - LHSR.first) == 1 &&
2091      LHSR.first->High == CR.GE &&
2092      cast<ConstantInt>(C)->getSExtValue() ==
2093      (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
2094    TrueBB = LHSR.first->BB;
2095  } else {
2096    TrueBB = new MachineBasicBlock(LLVMBB);
2097    CurMF->getBasicBlockList().insert(BBI, TrueBB);
2098    WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2099  }
2100
2101  // Similar to the optimization above, if the Value being switched on is
2102  // known to be less than the Constant CR.LT, and the current Case Value
2103  // is CR.LT - 1, then we can branch directly to the target block for
2104  // the current Case Value, rather than emitting a RHS leaf node for it.
2105  if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2106      cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
2107      (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
2108    FalseBB = RHSR.first->BB;
2109  } else {
2110    FalseBB = new MachineBasicBlock(LLVMBB);
2111    CurMF->getBasicBlockList().insert(BBI, FalseBB);
2112    WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2113  }
2114
2115  // Create a CaseBlock record representing a conditional branch to
2116  // the LHS node if the value being switched on SV is less than C.
2117  // Otherwise, branch to LHS.
2118  SelectionDAGISel::CaseBlock CB(ISD::SETLT, SV, C, NULL,
2119                                 TrueBB, FalseBB, CR.CaseBB);
2120
2121  if (CR.CaseBB == CurMBB)
2122    visitSwitchCase(CB);
2123  else
2124    SwitchCases.push_back(CB);
2125
2126  return true;
2127}
2128
2129/// handleBitTestsSwitchCase - if current case range has few destination and
2130/// range span less, than machine word bitwidth, encode case range into series
2131/// of masks and emit bit tests with these masks.
2132bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
2133                                                    CaseRecVector& WorkList,
2134                                                    Value* SV,
2135                                                    MachineBasicBlock* Default){
2136  unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
2137
2138  Case& FrontCase = *CR.Range.first;
2139  Case& BackCase  = *(CR.Range.second-1);
2140
2141  // Get the MachineFunction which holds the current MBB.  This is used when
2142  // inserting any additional MBBs necessary to represent the switch.
2143  MachineFunction *CurMF = CurMBB->getParent();
2144
2145  unsigned numCmps = 0;
2146  for (CaseItr I = CR.Range.first, E = CR.Range.second;
2147       I!=E; ++I) {
2148    // Single case counts one, case range - two.
2149    if (I->Low == I->High)
2150      numCmps +=1;
2151    else
2152      numCmps +=2;
2153  }
2154
2155  // Count unique destinations
2156  SmallSet<MachineBasicBlock*, 4> Dests;
2157  for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2158    Dests.insert(I->BB);
2159    if (Dests.size() > 3)
2160      // Don't bother the code below, if there are too much unique destinations
2161      return false;
2162  }
2163  DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
2164       << "Total number of comparisons: " << numCmps << "\n";
2165
2166  // Compute span of values.
2167  Constant* minValue = FrontCase.Low;
2168  Constant* maxValue = BackCase.High;
2169  uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
2170                   cast<ConstantInt>(minValue)->getSExtValue();
2171  DOUT << "Compare range: " << range << "\n"
2172       << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
2173       << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
2174
2175  if (range>=IntPtrBits ||
2176      (!(Dests.size() == 1 && numCmps >= 3) &&
2177       !(Dests.size() == 2 && numCmps >= 5) &&
2178       !(Dests.size() >= 3 && numCmps >= 6)))
2179    return false;
2180
2181  DOUT << "Emitting bit tests\n";
2182  int64_t lowBound = 0;
2183
2184  // Optimize the case where all the case values fit in a
2185  // word without having to subtract minValue. In this case,
2186  // we can optimize away the subtraction.
2187  if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
2188      cast<ConstantInt>(maxValue)->getSExtValue() <  IntPtrBits) {
2189    range = cast<ConstantInt>(maxValue)->getSExtValue();
2190  } else {
2191    lowBound = cast<ConstantInt>(minValue)->getSExtValue();
2192  }
2193
2194  CaseBitsVector CasesBits;
2195  unsigned i, count = 0;
2196
2197  for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2198    MachineBasicBlock* Dest = I->BB;
2199    for (i = 0; i < count; ++i)
2200      if (Dest == CasesBits[i].BB)
2201        break;
2202
2203    if (i == count) {
2204      assert((count < 3) && "Too much destinations to test!");
2205      CasesBits.push_back(CaseBits(0, Dest, 0));
2206      count++;
2207    }
2208
2209    uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
2210    uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
2211
2212    for (uint64_t j = lo; j <= hi; j++) {
2213      CasesBits[i].Mask |=  1ULL << j;
2214      CasesBits[i].Bits++;
2215    }
2216
2217  }
2218  std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2219
2220  SelectionDAGISel::BitTestInfo BTC;
2221
2222  // Figure out which block is immediately after the current one.
2223  MachineFunction::iterator BBI = CR.CaseBB;
2224  ++BBI;
2225
2226  const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2227
2228  DOUT << "Cases:\n";
2229  for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2230    DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
2231         << ", BB: " << CasesBits[i].BB << "\n";
2232
2233    MachineBasicBlock *CaseBB = new MachineBasicBlock(LLVMBB);
2234    CurMF->getBasicBlockList().insert(BBI, CaseBB);
2235    BTC.push_back(SelectionDAGISel::BitTestCase(CasesBits[i].Mask,
2236                                                CaseBB,
2237                                                CasesBits[i].BB));
2238  }
2239
2240  SelectionDAGISel::BitTestBlock BTB(lowBound, range, SV,
2241                                     -1U, (CR.CaseBB == CurMBB),
2242                                     CR.CaseBB, Default, BTC);
2243
2244  if (CR.CaseBB == CurMBB)
2245    visitBitTestHeader(BTB);
2246
2247  BitTestCases.push_back(BTB);
2248
2249  return true;
2250}
2251
2252
2253/// Clusterify - Transform simple list of Cases into list of CaseRange's
2254unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
2255                                          const SwitchInst& SI) {
2256  unsigned numCmps = 0;
2257
2258  // Start with "simple" cases
2259  for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
2260    MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2261    Cases.push_back(Case(SI.getSuccessorValue(i),
2262                         SI.getSuccessorValue(i),
2263                         SMBB));
2264  }
2265  std::sort(Cases.begin(), Cases.end(), CaseCmp());
2266
2267  // Merge case into clusters
2268  if (Cases.size()>=2)
2269    // Must recompute end() each iteration because it may be
2270    // invalidated by erase if we hold on to it
2271    for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
2272      int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
2273      int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
2274      MachineBasicBlock* nextBB = J->BB;
2275      MachineBasicBlock* currentBB = I->BB;
2276
2277      // If the two neighboring cases go to the same destination, merge them
2278      // into a single case.
2279      if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
2280        I->High = J->High;
2281        J = Cases.erase(J);
2282      } else {
2283        I = J++;
2284      }
2285    }
2286
2287  for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2288    if (I->Low != I->High)
2289      // A range counts double, since it requires two compares.
2290      ++numCmps;
2291  }
2292
2293  return numCmps;
2294}
2295
2296void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2297  // Figure out which block is immediately after the current one.
2298  MachineBasicBlock *NextBlock = 0;
2299  MachineFunction::iterator BBI = CurMBB;
2300
2301  MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2302
2303  // If there is only the default destination, branch to it if it is not the
2304  // next basic block.  Otherwise, just fall through.
2305  if (SI.getNumOperands() == 2) {
2306    // Update machine-CFG edges.
2307
2308    // If this is not a fall-through branch, emit the branch.
2309    CurMBB->addSuccessor(Default);
2310    if (Default != NextBlock)
2311      DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2312                              DAG.getBasicBlock(Default)));
2313
2314    return;
2315  }
2316
2317  // If there are any non-default case statements, create a vector of Cases
2318  // representing each one, and sort the vector so that we can efficiently
2319  // create a binary search tree from them.
2320  CaseVector Cases;
2321  unsigned numCmps = Clusterify(Cases, SI);
2322  DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2323       << ". Total compares: " << numCmps << "\n";
2324
2325  // Get the Value to be switched on and default basic blocks, which will be
2326  // inserted into CaseBlock records, representing basic blocks in the binary
2327  // search tree.
2328  Value *SV = SI.getOperand(0);
2329
2330  // Push the initial CaseRec onto the worklist
2331  CaseRecVector WorkList;
2332  WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2333
2334  while (!WorkList.empty()) {
2335    // Grab a record representing a case range to process off the worklist
2336    CaseRec CR = WorkList.back();
2337    WorkList.pop_back();
2338
2339    if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2340      continue;
2341
2342    // If the range has few cases (two or less) emit a series of specific
2343    // tests.
2344    if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2345      continue;
2346
2347    // If the switch has more than 5 blocks, and at least 40% dense, and the
2348    // target supports indirect branches, then emit a jump table rather than
2349    // lowering the switch to a binary tree of conditional branches.
2350    if (handleJTSwitchCase(CR, WorkList, SV, Default))
2351      continue;
2352
2353    // Emit binary tree. We need to pick a pivot, and push left and right ranges
2354    // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2355    handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2356  }
2357}
2358
2359
2360void SelectionDAGLowering::visitSub(User &I) {
2361  // -0.0 - X --> fneg
2362  const Type *Ty = I.getType();
2363  if (isa<VectorType>(Ty)) {
2364    if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2365      const VectorType *DestTy = cast<VectorType>(I.getType());
2366      const Type *ElTy = DestTy->getElementType();
2367      if (ElTy->isFloatingPoint()) {
2368        unsigned VL = DestTy->getNumElements();
2369        std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2370        Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2371        if (CV == CNZ) {
2372          SDOperand Op2 = getValue(I.getOperand(1));
2373          setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2374          return;
2375        }
2376      }
2377    }
2378  }
2379  if (Ty->isFloatingPoint()) {
2380    if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2381      if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2382        SDOperand Op2 = getValue(I.getOperand(1));
2383        setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2384        return;
2385      }
2386  }
2387
2388  visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2389}
2390
2391void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2392  SDOperand Op1 = getValue(I.getOperand(0));
2393  SDOperand Op2 = getValue(I.getOperand(1));
2394
2395  setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2396}
2397
2398void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2399  SDOperand Op1 = getValue(I.getOperand(0));
2400  SDOperand Op2 = getValue(I.getOperand(1));
2401
2402  if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2403    Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2404  else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2405    Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2406
2407  setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2408}
2409
2410void SelectionDAGLowering::visitICmp(User &I) {
2411  ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2412  if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2413    predicate = IC->getPredicate();
2414  else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2415    predicate = ICmpInst::Predicate(IC->getPredicate());
2416  SDOperand Op1 = getValue(I.getOperand(0));
2417  SDOperand Op2 = getValue(I.getOperand(1));
2418  ISD::CondCode Opcode;
2419  switch (predicate) {
2420    case ICmpInst::ICMP_EQ  : Opcode = ISD::SETEQ; break;
2421    case ICmpInst::ICMP_NE  : Opcode = ISD::SETNE; break;
2422    case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2423    case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2424    case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2425    case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2426    case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2427    case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2428    case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2429    case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2430    default:
2431      assert(!"Invalid ICmp predicate value");
2432      Opcode = ISD::SETEQ;
2433      break;
2434  }
2435  setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2436}
2437
2438void SelectionDAGLowering::visitFCmp(User &I) {
2439  FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2440  if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2441    predicate = FC->getPredicate();
2442  else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2443    predicate = FCmpInst::Predicate(FC->getPredicate());
2444  SDOperand Op1 = getValue(I.getOperand(0));
2445  SDOperand Op2 = getValue(I.getOperand(1));
2446  ISD::CondCode Condition, FOC, FPC;
2447  switch (predicate) {
2448    case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2449    case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2450    case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2451    case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2452    case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2453    case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2454    case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2455    case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
2456    case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
2457    case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2458    case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2459    case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2460    case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2461    case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2462    case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2463    case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
2464    default:
2465      assert(!"Invalid FCmp predicate value");
2466      FOC = FPC = ISD::SETFALSE;
2467      break;
2468  }
2469  if (FiniteOnlyFPMath())
2470    Condition = FOC;
2471  else
2472    Condition = FPC;
2473  setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2474}
2475
2476void SelectionDAGLowering::visitVICmp(User &I) {
2477  ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2478  if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2479    predicate = IC->getPredicate();
2480  else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2481    predicate = ICmpInst::Predicate(IC->getPredicate());
2482  SDOperand Op1 = getValue(I.getOperand(0));
2483  SDOperand Op2 = getValue(I.getOperand(1));
2484  ISD::CondCode Opcode;
2485  switch (predicate) {
2486    case ICmpInst::ICMP_EQ  : Opcode = ISD::SETEQ; break;
2487    case ICmpInst::ICMP_NE  : Opcode = ISD::SETNE; break;
2488    case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2489    case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2490    case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2491    case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2492    case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2493    case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2494    case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2495    case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2496    default:
2497      assert(!"Invalid ICmp predicate value");
2498      Opcode = ISD::SETEQ;
2499      break;
2500  }
2501  setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2502}
2503
2504void SelectionDAGLowering::visitVFCmp(User &I) {
2505  FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2506  if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2507    predicate = FC->getPredicate();
2508  else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2509    predicate = FCmpInst::Predicate(FC->getPredicate());
2510  SDOperand Op1 = getValue(I.getOperand(0));
2511  SDOperand Op2 = getValue(I.getOperand(1));
2512  ISD::CondCode Condition, FOC, FPC;
2513  switch (predicate) {
2514    case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2515    case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2516    case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2517    case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2518    case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2519    case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2520    case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2521    case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
2522    case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
2523    case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2524    case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2525    case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2526    case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2527    case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2528    case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2529    case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
2530    default:
2531      assert(!"Invalid VFCmp predicate value");
2532      FOC = FPC = ISD::SETFALSE;
2533      break;
2534  }
2535  if (FiniteOnlyFPMath())
2536    Condition = FOC;
2537  else
2538    Condition = FPC;
2539
2540  MVT DestVT = TLI.getValueType(I.getType());
2541
2542  setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2543}
2544
2545void SelectionDAGLowering::visitSelect(User &I) {
2546  SDOperand Cond     = getValue(I.getOperand(0));
2547  SDOperand TrueVal  = getValue(I.getOperand(1));
2548  SDOperand FalseVal = getValue(I.getOperand(2));
2549  setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2550                           TrueVal, FalseVal));
2551}
2552
2553
2554void SelectionDAGLowering::visitTrunc(User &I) {
2555  // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2556  SDOperand N = getValue(I.getOperand(0));
2557  MVT DestVT = TLI.getValueType(I.getType());
2558  setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2559}
2560
2561void SelectionDAGLowering::visitZExt(User &I) {
2562  // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2563  // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2564  SDOperand N = getValue(I.getOperand(0));
2565  MVT DestVT = TLI.getValueType(I.getType());
2566  setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2567}
2568
2569void SelectionDAGLowering::visitSExt(User &I) {
2570  // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2571  // SExt also can't be a cast to bool for same reason. So, nothing much to do
2572  SDOperand N = getValue(I.getOperand(0));
2573  MVT DestVT = TLI.getValueType(I.getType());
2574  setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2575}
2576
2577void SelectionDAGLowering::visitFPTrunc(User &I) {
2578  // FPTrunc is never a no-op cast, no need to check
2579  SDOperand N = getValue(I.getOperand(0));
2580  MVT DestVT = TLI.getValueType(I.getType());
2581  setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2582}
2583
2584void SelectionDAGLowering::visitFPExt(User &I){
2585  // FPTrunc is never a no-op cast, no need to check
2586  SDOperand N = getValue(I.getOperand(0));
2587  MVT DestVT = TLI.getValueType(I.getType());
2588  setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2589}
2590
2591void SelectionDAGLowering::visitFPToUI(User &I) {
2592  // FPToUI is never a no-op cast, no need to check
2593  SDOperand N = getValue(I.getOperand(0));
2594  MVT DestVT = TLI.getValueType(I.getType());
2595  setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2596}
2597
2598void SelectionDAGLowering::visitFPToSI(User &I) {
2599  // FPToSI is never a no-op cast, no need to check
2600  SDOperand N = getValue(I.getOperand(0));
2601  MVT DestVT = TLI.getValueType(I.getType());
2602  setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2603}
2604
2605void SelectionDAGLowering::visitUIToFP(User &I) {
2606  // UIToFP is never a no-op cast, no need to check
2607  SDOperand N = getValue(I.getOperand(0));
2608  MVT DestVT = TLI.getValueType(I.getType());
2609  setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2610}
2611
2612void SelectionDAGLowering::visitSIToFP(User &I){
2613  // UIToFP is never a no-op cast, no need to check
2614  SDOperand N = getValue(I.getOperand(0));
2615  MVT DestVT = TLI.getValueType(I.getType());
2616  setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2617}
2618
2619void SelectionDAGLowering::visitPtrToInt(User &I) {
2620  // What to do depends on the size of the integer and the size of the pointer.
2621  // We can either truncate, zero extend, or no-op, accordingly.
2622  SDOperand N = getValue(I.getOperand(0));
2623  MVT SrcVT = N.getValueType();
2624  MVT DestVT = TLI.getValueType(I.getType());
2625  SDOperand Result;
2626  if (DestVT.bitsLT(SrcVT))
2627    Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2628  else
2629    // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2630    Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2631  setValue(&I, Result);
2632}
2633
2634void SelectionDAGLowering::visitIntToPtr(User &I) {
2635  // What to do depends on the size of the integer and the size of the pointer.
2636  // We can either truncate, zero extend, or no-op, accordingly.
2637  SDOperand N = getValue(I.getOperand(0));
2638  MVT SrcVT = N.getValueType();
2639  MVT DestVT = TLI.getValueType(I.getType());
2640  if (DestVT.bitsLT(SrcVT))
2641    setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2642  else
2643    // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2644    setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2645}
2646
2647void SelectionDAGLowering::visitBitCast(User &I) {
2648  SDOperand N = getValue(I.getOperand(0));
2649  MVT DestVT = TLI.getValueType(I.getType());
2650
2651  // BitCast assures us that source and destination are the same size so this
2652  // is either a BIT_CONVERT or a no-op.
2653  if (DestVT != N.getValueType())
2654    setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2655  else
2656    setValue(&I, N); // noop cast.
2657}
2658
2659void SelectionDAGLowering::visitInsertElement(User &I) {
2660  SDOperand InVec = getValue(I.getOperand(0));
2661  SDOperand InVal = getValue(I.getOperand(1));
2662  SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2663                                getValue(I.getOperand(2)));
2664
2665  setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2666                           TLI.getValueType(I.getType()),
2667                           InVec, InVal, InIdx));
2668}
2669
2670void SelectionDAGLowering::visitExtractElement(User &I) {
2671  SDOperand InVec = getValue(I.getOperand(0));
2672  SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2673                                getValue(I.getOperand(1)));
2674  setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2675                           TLI.getValueType(I.getType()), InVec, InIdx));
2676}
2677
2678void SelectionDAGLowering::visitShuffleVector(User &I) {
2679  SDOperand V1   = getValue(I.getOperand(0));
2680  SDOperand V2   = getValue(I.getOperand(1));
2681  SDOperand Mask = getValue(I.getOperand(2));
2682
2683  setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2684                           TLI.getValueType(I.getType()),
2685                           V1, V2, Mask));
2686}
2687
2688void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2689  const Value *Op0 = I.getOperand(0);
2690  const Value *Op1 = I.getOperand(1);
2691  const Type *AggTy = I.getType();
2692  const Type *ValTy = Op1->getType();
2693  bool IntoUndef = isa<UndefValue>(Op0);
2694  bool FromUndef = isa<UndefValue>(Op1);
2695
2696  unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2697                                            I.idx_begin(), I.idx_end());
2698
2699  SmallVector<MVT, 4> AggValueVTs;
2700  ComputeValueVTs(TLI, AggTy, AggValueVTs);
2701  SmallVector<MVT, 4> ValValueVTs;
2702  ComputeValueVTs(TLI, ValTy, ValValueVTs);
2703
2704  unsigned NumAggValues = AggValueVTs.size();
2705  unsigned NumValValues = ValValueVTs.size();
2706  SmallVector<SDOperand, 4> Values(NumAggValues);
2707
2708  SDOperand Agg = getValue(Op0);
2709  SDOperand Val = getValue(Op1);
2710  unsigned i = 0;
2711  // Copy the beginning value(s) from the original aggregate.
2712  for (; i != LinearIndex; ++i)
2713    Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2714                SDOperand(Agg.Val, Agg.ResNo + i);
2715  // Copy values from the inserted value(s).
2716  for (; i != LinearIndex + NumValValues; ++i)
2717    Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2718                SDOperand(Val.Val, Val.ResNo + i - LinearIndex);
2719  // Copy remaining value(s) from the original aggregate.
2720  for (; i != NumAggValues; ++i)
2721    Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2722                SDOperand(Agg.Val, Agg.ResNo + i);
2723
2724  setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2725                                  &Values[0], NumAggValues));
2726}
2727
2728void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2729  const Value *Op0 = I.getOperand(0);
2730  const Type *AggTy = Op0->getType();
2731  const Type *ValTy = I.getType();
2732  bool OutOfUndef = isa<UndefValue>(Op0);
2733
2734  unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2735                                            I.idx_begin(), I.idx_end());
2736
2737  SmallVector<MVT, 4> ValValueVTs;
2738  ComputeValueVTs(TLI, ValTy, ValValueVTs);
2739
2740  unsigned NumValValues = ValValueVTs.size();
2741  SmallVector<SDOperand, 4> Values(NumValValues);
2742
2743  SDOperand Agg = getValue(Op0);
2744  // Copy out the selected value(s).
2745  for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2746    Values[i - LinearIndex] =
2747      OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.Val->getValueType(Agg.ResNo + i)) :
2748                   SDOperand(Agg.Val, Agg.ResNo + i);
2749
2750  setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2751                                  &Values[0], NumValValues));
2752}
2753
2754
2755void SelectionDAGLowering::visitGetElementPtr(User &I) {
2756  SDOperand N = getValue(I.getOperand(0));
2757  const Type *Ty = I.getOperand(0)->getType();
2758
2759  for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2760       OI != E; ++OI) {
2761    Value *Idx = *OI;
2762    if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2763      unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2764      if (Field) {
2765        // N = N + Offset
2766        uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2767        N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2768                        DAG.getIntPtrConstant(Offset));
2769      }
2770      Ty = StTy->getElementType(Field);
2771    } else {
2772      Ty = cast<SequentialType>(Ty)->getElementType();
2773
2774      // If this is a constant subscript, handle it quickly.
2775      if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2776        if (CI->getZExtValue() == 0) continue;
2777        uint64_t Offs =
2778            TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2779        N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2780                        DAG.getIntPtrConstant(Offs));
2781        continue;
2782      }
2783
2784      // N = N + Idx * ElementSize;
2785      uint64_t ElementSize = TD->getABITypeSize(Ty);
2786      SDOperand IdxN = getValue(Idx);
2787
2788      // If the index is smaller or larger than intptr_t, truncate or extend
2789      // it.
2790      if (IdxN.getValueType().bitsLT(N.getValueType())) {
2791        IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2792      } else if (IdxN.getValueType().bitsGT(N.getValueType()))
2793        IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2794
2795      // If this is a multiply by a power of two, turn it into a shl
2796      // immediately.  This is a very common case.
2797      if (isPowerOf2_64(ElementSize)) {
2798        unsigned Amt = Log2_64(ElementSize);
2799        IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2800                           DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2801        N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2802        continue;
2803      }
2804
2805      SDOperand Scale = DAG.getIntPtrConstant(ElementSize);
2806      IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2807      N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2808    }
2809  }
2810  setValue(&I, N);
2811}
2812
2813void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2814  // If this is a fixed sized alloca in the entry block of the function,
2815  // allocate it statically on the stack.
2816  if (FuncInfo.StaticAllocaMap.count(&I))
2817    return;   // getValue will auto-populate this.
2818
2819  const Type *Ty = I.getAllocatedType();
2820  uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2821  unsigned Align =
2822    std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2823             I.getAlignment());
2824
2825  SDOperand AllocSize = getValue(I.getArraySize());
2826  MVT IntPtr = TLI.getPointerTy();
2827  if (IntPtr.bitsLT(AllocSize.getValueType()))
2828    AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2829  else if (IntPtr.bitsGT(AllocSize.getValueType()))
2830    AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2831
2832  AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2833                          DAG.getIntPtrConstant(TySize));
2834
2835  // Handle alignment.  If the requested alignment is less than or equal to
2836  // the stack alignment, ignore it.  If the size is greater than or equal to
2837  // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2838  unsigned StackAlign =
2839    TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2840  if (Align <= StackAlign)
2841    Align = 0;
2842
2843  // Round the size of the allocation up to the stack alignment size
2844  // by add SA-1 to the size.
2845  AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2846                          DAG.getIntPtrConstant(StackAlign-1));
2847  // Mask out the low bits for alignment purposes.
2848  AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2849                          DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2850
2851  SDOperand Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2852  const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2853                                                    MVT::Other);
2854  SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2855  setValue(&I, DSA);
2856  DAG.setRoot(DSA.getValue(1));
2857
2858  // Inform the Frame Information that we have just allocated a variable-sized
2859  // object.
2860  CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2861}
2862
2863void SelectionDAGLowering::visitLoad(LoadInst &I) {
2864  const Value *SV = I.getOperand(0);
2865  SDOperand Ptr = getValue(SV);
2866
2867  const Type *Ty = I.getType();
2868  bool isVolatile = I.isVolatile();
2869  unsigned Alignment = I.getAlignment();
2870
2871  SmallVector<MVT, 4> ValueVTs;
2872  SmallVector<uint64_t, 4> Offsets;
2873  ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2874  unsigned NumValues = ValueVTs.size();
2875  if (NumValues == 0)
2876    return;
2877
2878  SDOperand Root;
2879  if (I.isVolatile())
2880    Root = getRoot();
2881  else {
2882    // Do not serialize non-volatile loads against each other.
2883    Root = DAG.getRoot();
2884  }
2885
2886  SmallVector<SDOperand, 4> Values(NumValues);
2887  SmallVector<SDOperand, 4> Chains(NumValues);
2888  MVT PtrVT = Ptr.getValueType();
2889  for (unsigned i = 0; i != NumValues; ++i) {
2890    SDOperand L = DAG.getLoad(ValueVTs[i], Root,
2891                              DAG.getNode(ISD::ADD, PtrVT, Ptr,
2892                                          DAG.getConstant(Offsets[i], PtrVT)),
2893                              SV, Offsets[i],
2894                              isVolatile, Alignment);
2895    Values[i] = L;
2896    Chains[i] = L.getValue(1);
2897  }
2898
2899  SDOperand Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2900                                &Chains[0], NumValues);
2901  if (isVolatile)
2902    DAG.setRoot(Chain);
2903  else
2904    PendingLoads.push_back(Chain);
2905
2906  setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2907                                  &Values[0], NumValues));
2908}
2909
2910
2911void SelectionDAGLowering::visitStore(StoreInst &I) {
2912  Value *SrcV = I.getOperand(0);
2913  SDOperand Src = getValue(SrcV);
2914  Value *PtrV = I.getOperand(1);
2915  SDOperand Ptr = getValue(PtrV);
2916
2917  SmallVector<MVT, 4> ValueVTs;
2918  SmallVector<uint64_t, 4> Offsets;
2919  ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2920  unsigned NumValues = ValueVTs.size();
2921  if (NumValues == 0)
2922    return;
2923
2924  SDOperand Root = getRoot();
2925  SmallVector<SDOperand, 4> Chains(NumValues);
2926  MVT PtrVT = Ptr.getValueType();
2927  bool isVolatile = I.isVolatile();
2928  unsigned Alignment = I.getAlignment();
2929  for (unsigned i = 0; i != NumValues; ++i)
2930    Chains[i] = DAG.getStore(Root, SDOperand(Src.Val, Src.ResNo + i),
2931                             DAG.getNode(ISD::ADD, PtrVT, Ptr,
2932                                         DAG.getConstant(Offsets[i], PtrVT)),
2933                             PtrV, Offsets[i],
2934                             isVolatile, Alignment);
2935
2936  DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2937}
2938
2939/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2940/// node.
2941void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2942                                                unsigned Intrinsic) {
2943  bool HasChain = !I.doesNotAccessMemory();
2944  bool OnlyLoad = HasChain && I.onlyReadsMemory();
2945
2946  // Build the operand list.
2947  SmallVector<SDOperand, 8> Ops;
2948  if (HasChain) {  // If this intrinsic has side-effects, chainify it.
2949    if (OnlyLoad) {
2950      // We don't need to serialize loads against other loads.
2951      Ops.push_back(DAG.getRoot());
2952    } else {
2953      Ops.push_back(getRoot());
2954    }
2955  }
2956
2957  // Add the intrinsic ID as an integer operand.
2958  Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2959
2960  // Add all operands of the call to the operand list.
2961  for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2962    SDOperand Op = getValue(I.getOperand(i));
2963    assert(TLI.isTypeLegal(Op.getValueType()) &&
2964           "Intrinsic uses a non-legal type?");
2965    Ops.push_back(Op);
2966  }
2967
2968  std::vector<MVT> VTs;
2969  if (I.getType() != Type::VoidTy) {
2970    MVT VT = TLI.getValueType(I.getType());
2971    if (VT.isVector()) {
2972      const VectorType *DestTy = cast<VectorType>(I.getType());
2973      MVT EltVT = TLI.getValueType(DestTy->getElementType());
2974
2975      VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2976      assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2977    }
2978
2979    assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2980    VTs.push_back(VT);
2981  }
2982  if (HasChain)
2983    VTs.push_back(MVT::Other);
2984
2985  const MVT *VTList = DAG.getNodeValueTypes(VTs);
2986
2987  // Create the node.
2988  SDOperand Result;
2989  if (!HasChain)
2990    Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2991                         &Ops[0], Ops.size());
2992  else if (I.getType() != Type::VoidTy)
2993    Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2994                         &Ops[0], Ops.size());
2995  else
2996    Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2997                         &Ops[0], Ops.size());
2998
2999  if (HasChain) {
3000    SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
3001    if (OnlyLoad)
3002      PendingLoads.push_back(Chain);
3003    else
3004      DAG.setRoot(Chain);
3005  }
3006  if (I.getType() != Type::VoidTy) {
3007    if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3008      MVT VT = TLI.getValueType(PTy);
3009      Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
3010    }
3011    setValue(&I, Result);
3012  }
3013}
3014
3015/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3016static GlobalVariable *ExtractTypeInfo (Value *V) {
3017  V = V->stripPointerCasts();
3018  GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3019  assert ((GV || isa<ConstantPointerNull>(V)) &&
3020          "TypeInfo must be a global variable or NULL");
3021  return GV;
3022}
3023
3024/// addCatchInfo - Extract the personality and type infos from an eh.selector
3025/// call, and add them to the specified machine basic block.
3026static void addCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3027                         MachineBasicBlock *MBB) {
3028  // Inform the MachineModuleInfo of the personality for this landing pad.
3029  ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3030  assert(CE->getOpcode() == Instruction::BitCast &&
3031         isa<Function>(CE->getOperand(0)) &&
3032         "Personality should be a function");
3033  MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3034
3035  // Gather all the type infos for this landing pad and pass them along to
3036  // MachineModuleInfo.
3037  std::vector<GlobalVariable *> TyInfo;
3038  unsigned N = I.getNumOperands();
3039
3040  for (unsigned i = N - 1; i > 2; --i) {
3041    if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3042      unsigned FilterLength = CI->getZExtValue();
3043      unsigned FirstCatch = i + FilterLength + !FilterLength;
3044      assert (FirstCatch <= N && "Invalid filter length");
3045
3046      if (FirstCatch < N) {
3047        TyInfo.reserve(N - FirstCatch);
3048        for (unsigned j = FirstCatch; j < N; ++j)
3049          TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3050        MMI->addCatchTypeInfo(MBB, TyInfo);
3051        TyInfo.clear();
3052      }
3053
3054      if (!FilterLength) {
3055        // Cleanup.
3056        MMI->addCleanup(MBB);
3057      } else {
3058        // Filter.
3059        TyInfo.reserve(FilterLength - 1);
3060        for (unsigned j = i + 1; j < FirstCatch; ++j)
3061          TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3062        MMI->addFilterTypeInfo(MBB, TyInfo);
3063        TyInfo.clear();
3064      }
3065
3066      N = i;
3067    }
3068  }
3069
3070  if (N > 3) {
3071    TyInfo.reserve(N - 3);
3072    for (unsigned j = 3; j < N; ++j)
3073      TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3074    MMI->addCatchTypeInfo(MBB, TyInfo);
3075  }
3076}
3077
3078
3079/// Inlined utility function to implement binary input atomic intrinsics for
3080// visitIntrinsicCall: I is a call instruction
3081//                     Op is the associated NodeType for I
3082const char *
3083SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3084  SDOperand Root = getRoot();
3085  SDOperand L = DAG.getAtomic(Op, Root,
3086                              getValue(I.getOperand(1)),
3087                              getValue(I.getOperand(2)),
3088                              I.getOperand(1));
3089  setValue(&I, L);
3090  DAG.setRoot(L.getValue(1));
3091  return 0;
3092}
3093
3094/// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
3095/// we want to emit this as a call to a named external function, return the name
3096/// otherwise lower it and return null.
3097const char *
3098SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3099  switch (Intrinsic) {
3100  default:
3101    // By default, turn this into a target intrinsic node.
3102    visitTargetIntrinsic(I, Intrinsic);
3103    return 0;
3104  case Intrinsic::vastart:  visitVAStart(I); return 0;
3105  case Intrinsic::vaend:    visitVAEnd(I); return 0;
3106  case Intrinsic::vacopy:   visitVACopy(I); return 0;
3107  case Intrinsic::returnaddress:
3108    setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3109                             getValue(I.getOperand(1))));
3110    return 0;
3111  case Intrinsic::frameaddress:
3112    setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3113                             getValue(I.getOperand(1))));
3114    return 0;
3115  case Intrinsic::setjmp:
3116    return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3117    break;
3118  case Intrinsic::longjmp:
3119    return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3120    break;
3121  case Intrinsic::memcpy_i32:
3122  case Intrinsic::memcpy_i64: {
3123    SDOperand Op1 = getValue(I.getOperand(1));
3124    SDOperand Op2 = getValue(I.getOperand(2));
3125    SDOperand Op3 = getValue(I.getOperand(3));
3126    unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3127    DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3128                              I.getOperand(1), 0, I.getOperand(2), 0));
3129    return 0;
3130  }
3131  case Intrinsic::memset_i32:
3132  case Intrinsic::memset_i64: {
3133    SDOperand Op1 = getValue(I.getOperand(1));
3134    SDOperand Op2 = getValue(I.getOperand(2));
3135    SDOperand Op3 = getValue(I.getOperand(3));
3136    unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3137    DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3138                              I.getOperand(1), 0));
3139    return 0;
3140  }
3141  case Intrinsic::memmove_i32:
3142  case Intrinsic::memmove_i64: {
3143    SDOperand Op1 = getValue(I.getOperand(1));
3144    SDOperand Op2 = getValue(I.getOperand(2));
3145    SDOperand Op3 = getValue(I.getOperand(3));
3146    unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3147
3148    // If the source and destination are known to not be aliases, we can
3149    // lower memmove as memcpy.
3150    uint64_t Size = -1ULL;
3151    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3152      Size = C->getValue();
3153    if (AA.alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3154        AliasAnalysis::NoAlias) {
3155      DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3156                                I.getOperand(1), 0, I.getOperand(2), 0));
3157      return 0;
3158    }
3159
3160    DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3161                               I.getOperand(1), 0, I.getOperand(2), 0));
3162    return 0;
3163  }
3164  case Intrinsic::dbg_stoppoint: {
3165    MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3166    DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3167    if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3168      DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3169      assert(DD && "Not a debug information descriptor");
3170      DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3171                                      SPI.getLine(),
3172                                      SPI.getColumn(),
3173                                      cast<CompileUnitDesc>(DD)));
3174    }
3175
3176    return 0;
3177  }
3178  case Intrinsic::dbg_region_start: {
3179    MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3180    DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3181    if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3182      unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3183      DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3184    }
3185
3186    return 0;
3187  }
3188  case Intrinsic::dbg_region_end: {
3189    MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3190    DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3191    if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3192      unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3193      DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3194    }
3195
3196    return 0;
3197  }
3198  case Intrinsic::dbg_func_start: {
3199    MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3200    if (!MMI) return 0;
3201    DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3202    Value *SP = FSI.getSubprogram();
3203    if (SP && MMI->Verify(SP)) {
3204      // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3205      // what (most?) gdb expects.
3206      DebugInfoDesc *DD = MMI->getDescFor(SP);
3207      assert(DD && "Not a debug information descriptor");
3208      SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3209      const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3210      unsigned SrcFile = MMI->RecordSource(CompileUnit);
3211      // Record the source line but does create a label. It will be emitted
3212      // at asm emission time.
3213      MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3214    }
3215
3216    return 0;
3217  }
3218  case Intrinsic::dbg_declare: {
3219    MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3220    DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3221    Value *Variable = DI.getVariable();
3222    if (MMI && Variable && MMI->Verify(Variable))
3223      DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3224                              getValue(DI.getAddress()), getValue(Variable)));
3225    return 0;
3226  }
3227
3228  case Intrinsic::eh_exception: {
3229    if (!CurMBB->isLandingPad()) {
3230      // FIXME: Mark exception register as live in.  Hack for PR1508.
3231      unsigned Reg = TLI.getExceptionAddressRegister();
3232      if (Reg) CurMBB->addLiveIn(Reg);
3233    }
3234    // Insert the EXCEPTIONADDR instruction.
3235    SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3236    SDOperand Ops[1];
3237    Ops[0] = DAG.getRoot();
3238    SDOperand Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3239    setValue(&I, Op);
3240    DAG.setRoot(Op.getValue(1));
3241    return 0;
3242  }
3243
3244  case Intrinsic::eh_selector_i32:
3245  case Intrinsic::eh_selector_i64: {
3246    MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3247    MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3248                         MVT::i32 : MVT::i64);
3249
3250    if (MMI) {
3251      if (CurMBB->isLandingPad())
3252        addCatchInfo(I, MMI, CurMBB);
3253      else {
3254#ifndef NDEBUG
3255        FuncInfo.CatchInfoLost.insert(&I);
3256#endif
3257        // FIXME: Mark exception selector register as live in.  Hack for PR1508.
3258        unsigned Reg = TLI.getExceptionSelectorRegister();
3259        if (Reg) CurMBB->addLiveIn(Reg);
3260      }
3261
3262      // Insert the EHSELECTION instruction.
3263      SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3264      SDOperand Ops[2];
3265      Ops[0] = getValue(I.getOperand(1));
3266      Ops[1] = getRoot();
3267      SDOperand Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3268      setValue(&I, Op);
3269      DAG.setRoot(Op.getValue(1));
3270    } else {
3271      setValue(&I, DAG.getConstant(0, VT));
3272    }
3273
3274    return 0;
3275  }
3276
3277  case Intrinsic::eh_typeid_for_i32:
3278  case Intrinsic::eh_typeid_for_i64: {
3279    MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3280    MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3281                         MVT::i32 : MVT::i64);
3282
3283    if (MMI) {
3284      // Find the type id for the given typeinfo.
3285      GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3286
3287      unsigned TypeID = MMI->getTypeIDFor(GV);
3288      setValue(&I, DAG.getConstant(TypeID, VT));
3289    } else {
3290      // Return something different to eh_selector.
3291      setValue(&I, DAG.getConstant(1, VT));
3292    }
3293
3294    return 0;
3295  }
3296
3297  case Intrinsic::eh_return: {
3298    MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3299
3300    if (MMI) {
3301      MMI->setCallsEHReturn(true);
3302      DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3303                              MVT::Other,
3304                              getControlRoot(),
3305                              getValue(I.getOperand(1)),
3306                              getValue(I.getOperand(2))));
3307    } else {
3308      setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3309    }
3310
3311    return 0;
3312  }
3313
3314   case Intrinsic::eh_unwind_init: {
3315     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3316       MMI->setCallsUnwindInit(true);
3317     }
3318
3319     return 0;
3320   }
3321
3322   case Intrinsic::eh_dwarf_cfa: {
3323     MVT VT = getValue(I.getOperand(1)).getValueType();
3324     SDOperand CfaArg;
3325     if (VT.bitsGT(TLI.getPointerTy()))
3326       CfaArg = DAG.getNode(ISD::TRUNCATE,
3327                            TLI.getPointerTy(), getValue(I.getOperand(1)));
3328     else
3329       CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3330                            TLI.getPointerTy(), getValue(I.getOperand(1)));
3331
3332     SDOperand Offset = DAG.getNode(ISD::ADD,
3333                                    TLI.getPointerTy(),
3334                                    DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3335                                                TLI.getPointerTy()),
3336                                    CfaArg);
3337     setValue(&I, DAG.getNode(ISD::ADD,
3338                              TLI.getPointerTy(),
3339                              DAG.getNode(ISD::FRAMEADDR,
3340                                          TLI.getPointerTy(),
3341                                          DAG.getConstant(0,
3342                                                          TLI.getPointerTy())),
3343                              Offset));
3344     return 0;
3345  }
3346
3347  case Intrinsic::sqrt:
3348    setValue(&I, DAG.getNode(ISD::FSQRT,
3349                             getValue(I.getOperand(1)).getValueType(),
3350                             getValue(I.getOperand(1))));
3351    return 0;
3352  case Intrinsic::powi:
3353    setValue(&I, DAG.getNode(ISD::FPOWI,
3354                             getValue(I.getOperand(1)).getValueType(),
3355                             getValue(I.getOperand(1)),
3356                             getValue(I.getOperand(2))));
3357    return 0;
3358  case Intrinsic::sin:
3359    setValue(&I, DAG.getNode(ISD::FSIN,
3360                             getValue(I.getOperand(1)).getValueType(),
3361                             getValue(I.getOperand(1))));
3362    return 0;
3363  case Intrinsic::cos:
3364    setValue(&I, DAG.getNode(ISD::FCOS,
3365                             getValue(I.getOperand(1)).getValueType(),
3366                             getValue(I.getOperand(1))));
3367    return 0;
3368  case Intrinsic::pow:
3369    setValue(&I, DAG.getNode(ISD::FPOW,
3370                             getValue(I.getOperand(1)).getValueType(),
3371                             getValue(I.getOperand(1)),
3372                             getValue(I.getOperand(2))));
3373    return 0;
3374  case Intrinsic::pcmarker: {
3375    SDOperand Tmp = getValue(I.getOperand(1));
3376    DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3377    return 0;
3378  }
3379  case Intrinsic::readcyclecounter: {
3380    SDOperand Op = getRoot();
3381    SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3382                                DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3383                                &Op, 1);
3384    setValue(&I, Tmp);
3385    DAG.setRoot(Tmp.getValue(1));
3386    return 0;
3387  }
3388  case Intrinsic::part_select: {
3389    // Currently not implemented: just abort
3390    assert(0 && "part_select intrinsic not implemented");
3391    abort();
3392  }
3393  case Intrinsic::part_set: {
3394    // Currently not implemented: just abort
3395    assert(0 && "part_set intrinsic not implemented");
3396    abort();
3397  }
3398  case Intrinsic::bswap:
3399    setValue(&I, DAG.getNode(ISD::BSWAP,
3400                             getValue(I.getOperand(1)).getValueType(),
3401                             getValue(I.getOperand(1))));
3402    return 0;
3403  case Intrinsic::cttz: {
3404    SDOperand Arg = getValue(I.getOperand(1));
3405    MVT Ty = Arg.getValueType();
3406    SDOperand result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3407    setValue(&I, result);
3408    return 0;
3409  }
3410  case Intrinsic::ctlz: {
3411    SDOperand Arg = getValue(I.getOperand(1));
3412    MVT Ty = Arg.getValueType();
3413    SDOperand result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3414    setValue(&I, result);
3415    return 0;
3416  }
3417  case Intrinsic::ctpop: {
3418    SDOperand Arg = getValue(I.getOperand(1));
3419    MVT Ty = Arg.getValueType();
3420    SDOperand result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3421    setValue(&I, result);
3422    return 0;
3423  }
3424  case Intrinsic::stacksave: {
3425    SDOperand Op = getRoot();
3426    SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
3427              DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3428    setValue(&I, Tmp);
3429    DAG.setRoot(Tmp.getValue(1));
3430    return 0;
3431  }
3432  case Intrinsic::stackrestore: {
3433    SDOperand Tmp = getValue(I.getOperand(1));
3434    DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3435    return 0;
3436  }
3437  case Intrinsic::var_annotation:
3438    // Discard annotate attributes
3439    return 0;
3440
3441  case Intrinsic::init_trampoline: {
3442    const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3443
3444    SDOperand Ops[6];
3445    Ops[0] = getRoot();
3446    Ops[1] = getValue(I.getOperand(1));
3447    Ops[2] = getValue(I.getOperand(2));
3448    Ops[3] = getValue(I.getOperand(3));
3449    Ops[4] = DAG.getSrcValue(I.getOperand(1));
3450    Ops[5] = DAG.getSrcValue(F);
3451
3452    SDOperand Tmp = DAG.getNode(ISD::TRAMPOLINE,
3453                                DAG.getNodeValueTypes(TLI.getPointerTy(),
3454                                                      MVT::Other), 2,
3455                                Ops, 6);
3456
3457    setValue(&I, Tmp);
3458    DAG.setRoot(Tmp.getValue(1));
3459    return 0;
3460  }
3461
3462  case Intrinsic::gcroot:
3463    if (GCI) {
3464      Value *Alloca = I.getOperand(1);
3465      Constant *TypeMap = cast<Constant>(I.getOperand(2));
3466
3467      FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).Val);
3468      GCI->addStackRoot(FI->getIndex(), TypeMap);
3469    }
3470    return 0;
3471
3472  case Intrinsic::gcread:
3473  case Intrinsic::gcwrite:
3474    assert(0 && "Collector failed to lower gcread/gcwrite intrinsics!");
3475    return 0;
3476
3477  case Intrinsic::flt_rounds: {
3478    setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3479    return 0;
3480  }
3481
3482  case Intrinsic::trap: {
3483    DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3484    return 0;
3485  }
3486  case Intrinsic::prefetch: {
3487    SDOperand Ops[4];
3488    Ops[0] = getRoot();
3489    Ops[1] = getValue(I.getOperand(1));
3490    Ops[2] = getValue(I.getOperand(2));
3491    Ops[3] = getValue(I.getOperand(3));
3492    DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3493    return 0;
3494  }
3495
3496  case Intrinsic::memory_barrier: {
3497    SDOperand Ops[6];
3498    Ops[0] = getRoot();
3499    for (int x = 1; x < 6; ++x)
3500      Ops[x] = getValue(I.getOperand(x));
3501
3502    DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3503    return 0;
3504  }
3505  case Intrinsic::atomic_cmp_swap: {
3506    SDOperand Root = getRoot();
3507    SDOperand L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, Root,
3508                                getValue(I.getOperand(1)),
3509                                getValue(I.getOperand(2)),
3510                                getValue(I.getOperand(3)),
3511                                I.getOperand(1));
3512    setValue(&I, L);
3513    DAG.setRoot(L.getValue(1));
3514    return 0;
3515  }
3516  case Intrinsic::atomic_load_add:
3517    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
3518  case Intrinsic::atomic_load_sub:
3519    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
3520  case Intrinsic::atomic_load_and:
3521    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
3522  case Intrinsic::atomic_load_or:
3523    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
3524  case Intrinsic::atomic_load_xor:
3525    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
3526  case Intrinsic::atomic_load_nand:
3527    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
3528  case Intrinsic::atomic_load_min:
3529    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
3530  case Intrinsic::atomic_load_max:
3531    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
3532  case Intrinsic::atomic_load_umin:
3533    return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
3534  case Intrinsic::atomic_load_umax:
3535      return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
3536  case Intrinsic::atomic_swap:
3537    return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
3538  }
3539}
3540
3541
3542void SelectionDAGLowering::LowerCallTo(CallSite CS, SDOperand Callee,
3543                                       bool IsTailCall,
3544                                       MachineBasicBlock *LandingPad) {
3545  const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3546  const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3547  MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3548  unsigned BeginLabel = 0, EndLabel = 0;
3549
3550  TargetLowering::ArgListTy Args;
3551  TargetLowering::ArgListEntry Entry;
3552  Args.reserve(CS.arg_size());
3553  for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3554       i != e; ++i) {
3555    SDOperand ArgNode = getValue(*i);
3556    Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3557
3558    unsigned attrInd = i - CS.arg_begin() + 1;
3559    Entry.isSExt  = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3560    Entry.isZExt  = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3561    Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3562    Entry.isSRet  = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3563    Entry.isNest  = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3564    Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3565    Entry.Alignment = CS.getParamAlignment(attrInd);
3566    Args.push_back(Entry);
3567  }
3568
3569  if (LandingPad && MMI) {
3570    // Insert a label before the invoke call to mark the try range.  This can be
3571    // used to detect deletion of the invoke via the MachineModuleInfo.
3572    BeginLabel = MMI->NextLabelID();
3573    // Both PendingLoads and PendingExports must be flushed here;
3574    // this call might not return.
3575    (void)getRoot();
3576    DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
3577  }
3578
3579  std::pair<SDOperand,SDOperand> Result =
3580    TLI.LowerCallTo(getRoot(), CS.getType(),
3581                    CS.paramHasAttr(0, ParamAttr::SExt),
3582                    CS.paramHasAttr(0, ParamAttr::ZExt),
3583                    FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3584                    Callee, Args, DAG);
3585  if (CS.getType() != Type::VoidTy)
3586    setValue(CS.getInstruction(), Result.first);
3587  DAG.setRoot(Result.second);
3588
3589  if (LandingPad && MMI) {
3590    // Insert a label at the end of the invoke call to mark the try range.  This
3591    // can be used to detect deletion of the invoke via the MachineModuleInfo.
3592    EndLabel = MMI->NextLabelID();
3593    DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
3594
3595    // Inform MachineModuleInfo of range.
3596    MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3597  }
3598}
3599
3600
3601void SelectionDAGLowering::visitCall(CallInst &I) {
3602  const char *RenameFn = 0;
3603  if (Function *F = I.getCalledFunction()) {
3604    if (F->isDeclaration()) {
3605      if (unsigned IID = F->getIntrinsicID()) {
3606        RenameFn = visitIntrinsicCall(I, IID);
3607        if (!RenameFn)
3608          return;
3609      }
3610    }
3611
3612    // Check for well-known libc/libm calls.  If the function is internal, it
3613    // can't be a library call.
3614    unsigned NameLen = F->getNameLen();
3615    if (!F->hasInternalLinkage() && NameLen) {
3616      const char *NameStr = F->getNameStart();
3617      if (NameStr[0] == 'c' &&
3618          ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3619           (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3620        if (I.getNumOperands() == 3 &&   // Basic sanity checks.
3621            I.getOperand(1)->getType()->isFloatingPoint() &&
3622            I.getType() == I.getOperand(1)->getType() &&
3623            I.getType() == I.getOperand(2)->getType()) {
3624          SDOperand LHS = getValue(I.getOperand(1));
3625          SDOperand RHS = getValue(I.getOperand(2));
3626          setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3627                                   LHS, RHS));
3628          return;
3629        }
3630      } else if (NameStr[0] == 'f' &&
3631                 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3632                  (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3633                  (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3634        if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3635            I.getOperand(1)->getType()->isFloatingPoint() &&
3636            I.getType() == I.getOperand(1)->getType()) {
3637          SDOperand Tmp = getValue(I.getOperand(1));
3638          setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3639          return;
3640        }
3641      } else if (NameStr[0] == 's' &&
3642                 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3643                  (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3644                  (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3645        if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3646            I.getOperand(1)->getType()->isFloatingPoint() &&
3647            I.getType() == I.getOperand(1)->getType()) {
3648          SDOperand Tmp = getValue(I.getOperand(1));
3649          setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3650          return;
3651        }
3652      } else if (NameStr[0] == 'c' &&
3653                 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3654                  (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3655                  (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3656        if (I.getNumOperands() == 2 &&   // Basic sanity checks.
3657            I.getOperand(1)->getType()->isFloatingPoint() &&
3658            I.getType() == I.getOperand(1)->getType()) {
3659          SDOperand Tmp = getValue(I.getOperand(1));
3660          setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3661          return;
3662        }
3663      }
3664    }
3665  } else if (isa<InlineAsm>(I.getOperand(0))) {
3666    visitInlineAsm(&I);
3667    return;
3668  }
3669
3670  SDOperand Callee;
3671  if (!RenameFn)
3672    Callee = getValue(I.getOperand(0));
3673  else
3674    Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3675
3676  LowerCallTo(&I, Callee, I.isTailCall());
3677}
3678
3679
3680void SelectionDAGLowering::visitGetResult(GetResultInst &I) {
3681  if (isa<UndefValue>(I.getOperand(0))) {
3682    SDOperand Undef = DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType()));
3683    setValue(&I, Undef);
3684    return;
3685  }
3686
3687  // To add support for individual return values with aggregate types,
3688  // we'd need a way to take a getresult index and determine which
3689  // values of the Call SDNode are associated with it.
3690  assert(TLI.getValueType(I.getType(), true) != MVT::Other &&
3691         "Individual return values must not be aggregates!");
3692
3693  SDOperand Call = getValue(I.getOperand(0));
3694  setValue(&I, SDOperand(Call.Val, I.getIndex()));
3695}
3696
3697
3698/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3699/// this value and returns the result as a ValueVT value.  This uses
3700/// Chain/Flag as the input and updates them for the output Chain/Flag.
3701/// If the Flag pointer is NULL, no flag is used.
3702SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3703                                        SDOperand &Chain,
3704                                        SDOperand *Flag) const {
3705  // Assemble the legal parts into the final values.
3706  SmallVector<SDOperand, 4> Values(ValueVTs.size());
3707  SmallVector<SDOperand, 8> Parts;
3708  for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3709    // Copy the legal parts from the registers.
3710    MVT ValueVT = ValueVTs[Value];
3711    unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3712    MVT RegisterVT = RegVTs[Value];
3713
3714    Parts.resize(NumRegs);
3715    for (unsigned i = 0; i != NumRegs; ++i) {
3716      SDOperand P;
3717      if (Flag == 0)
3718        P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3719      else {
3720        P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3721        *Flag = P.getValue(2);
3722      }
3723      Chain = P.getValue(1);
3724
3725      // If the source register was virtual and if we know something about it,
3726      // add an assert node.
3727      if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3728          RegisterVT.isInteger() && !RegisterVT.isVector()) {
3729        unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3730        FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3731        if (FLI.LiveOutRegInfo.size() > SlotNo) {
3732          FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3733
3734          unsigned RegSize = RegisterVT.getSizeInBits();
3735          unsigned NumSignBits = LOI.NumSignBits;
3736          unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3737
3738          // FIXME: We capture more information than the dag can represent.  For
3739          // now, just use the tightest assertzext/assertsext possible.
3740          bool isSExt = true;
3741          MVT FromVT(MVT::Other);
3742          if (NumSignBits == RegSize)
3743            isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
3744          else if (NumZeroBits >= RegSize-1)
3745            isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
3746          else if (NumSignBits > RegSize-8)
3747            isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
3748          else if (NumZeroBits >= RegSize-9)
3749            isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
3750          else if (NumSignBits > RegSize-16)
3751            isSExt = true, FromVT = MVT::i16;   // ASSERT SEXT 16
3752          else if (NumZeroBits >= RegSize-17)
3753            isSExt = false, FromVT = MVT::i16;  // ASSERT ZEXT 16
3754          else if (NumSignBits > RegSize-32)
3755            isSExt = true, FromVT = MVT::i32;   // ASSERT SEXT 32
3756          else if (NumZeroBits >= RegSize-33)
3757            isSExt = false, FromVT = MVT::i32;  // ASSERT ZEXT 32
3758
3759          if (FromVT != MVT::Other) {
3760            P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3761                            RegisterVT, P, DAG.getValueType(FromVT));
3762
3763          }
3764        }
3765      }
3766
3767      Parts[Part+i] = P;
3768    }
3769
3770    Values[Value] = getCopyFromParts(DAG, &Parts[Part], NumRegs, RegisterVT,
3771                                     ValueVT);
3772    Part += NumRegs;
3773  }
3774
3775  if (ValueVTs.size() == 1)
3776    return Values[0];
3777
3778  return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3779                            &Values[0], ValueVTs.size());
3780}
3781
3782/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3783/// specified value into the registers specified by this object.  This uses
3784/// Chain/Flag as the input and updates them for the output Chain/Flag.
3785/// If the Flag pointer is NULL, no flag is used.
3786void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
3787                                 SDOperand &Chain, SDOperand *Flag) const {
3788  // Get the list of the values's legal parts.
3789  unsigned NumRegs = Regs.size();
3790  SmallVector<SDOperand, 8> Parts(NumRegs);
3791  for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3792    MVT ValueVT = ValueVTs[Value];
3793    unsigned NumParts = TLI->getNumRegisters(ValueVT);
3794    MVT RegisterVT = RegVTs[Value];
3795
3796    getCopyToParts(DAG, Val.getValue(Val.ResNo + Value),
3797                   &Parts[Part], NumParts, RegisterVT);
3798    Part += NumParts;
3799  }
3800
3801  // Copy the parts into the registers.
3802  SmallVector<SDOperand, 8> Chains(NumRegs);
3803  for (unsigned i = 0; i != NumRegs; ++i) {
3804    SDOperand Part;
3805    if (Flag == 0)
3806      Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3807    else {
3808      Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3809      *Flag = Part.getValue(1);
3810    }
3811    Chains[i] = Part.getValue(0);
3812  }
3813
3814  if (NumRegs == 1 || Flag)
3815    // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3816    // flagged to it. That is the CopyToReg nodes and the user are considered
3817    // a single scheduling unit. If we create a TokenFactor and return it as
3818    // chain, then the TokenFactor is both a predecessor (operand) of the
3819    // user as well as a successor (the TF operands are flagged to the user).
3820    // c1, f1 = CopyToReg
3821    // c2, f2 = CopyToReg
3822    // c3     = TokenFactor c1, c2
3823    // ...
3824    //        = op c3, ..., f2
3825    Chain = Chains[NumRegs-1];
3826  else
3827    Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3828}
3829
3830/// AddInlineAsmOperands - Add this value to the specified inlineasm node
3831/// operand list.  This adds the code marker and includes the number of
3832/// values added into it.
3833void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3834                                        std::vector<SDOperand> &Ops) const {
3835  MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3836  Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3837  for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3838    unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3839    MVT RegisterVT = RegVTs[Value];
3840    for (unsigned i = 0; i != NumRegs; ++i)
3841      Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3842  }
3843}
3844
3845/// isAllocatableRegister - If the specified register is safe to allocate,
3846/// i.e. it isn't a stack pointer or some other special register, return the
3847/// register class for the register.  Otherwise, return null.
3848static const TargetRegisterClass *
3849isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3850                      const TargetLowering &TLI,
3851                      const TargetRegisterInfo *TRI) {
3852  MVT FoundVT = MVT::Other;
3853  const TargetRegisterClass *FoundRC = 0;
3854  for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3855       E = TRI->regclass_end(); RCI != E; ++RCI) {
3856    MVT ThisVT = MVT::Other;
3857
3858    const TargetRegisterClass *RC = *RCI;
3859    // If none of the the value types for this register class are valid, we
3860    // can't use it.  For example, 64-bit reg classes on 32-bit targets.
3861    for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3862         I != E; ++I) {
3863      if (TLI.isTypeLegal(*I)) {
3864        // If we have already found this register in a different register class,
3865        // choose the one with the largest VT specified.  For example, on
3866        // PowerPC, we favor f64 register classes over f32.
3867        if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
3868          ThisVT = *I;
3869          break;
3870        }
3871      }
3872    }
3873
3874    if (ThisVT == MVT::Other) continue;
3875
3876    // NOTE: This isn't ideal.  In particular, this might allocate the
3877    // frame pointer in functions that need it (due to them not being taken
3878    // out of allocation, because a variable sized allocation hasn't been seen
3879    // yet).  This is a slight code pessimization, but should still work.
3880    for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3881         E = RC->allocation_order_end(MF); I != E; ++I)
3882      if (*I == Reg) {
3883        // We found a matching register class.  Keep looking at others in case
3884        // we find one with larger registers that this physreg is also in.
3885        FoundRC = RC;
3886        FoundVT = ThisVT;
3887        break;
3888      }
3889  }
3890  return FoundRC;
3891}
3892
3893
3894namespace {
3895/// AsmOperandInfo - This contains information for each constraint that we are
3896/// lowering.
3897struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3898  /// CallOperand - If this is the result output operand or a clobber
3899  /// this is null, otherwise it is the incoming operand to the CallInst.
3900  /// This gets modified as the asm is processed.
3901  SDOperand CallOperand;
3902
3903  /// AssignedRegs - If this is a register or register class operand, this
3904  /// contains the set of register corresponding to the operand.
3905  RegsForValue AssignedRegs;
3906
3907  explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3908    : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3909  }
3910
3911  /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3912  /// busy in OutputRegs/InputRegs.
3913  void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3914                         std::set<unsigned> &OutputRegs,
3915                         std::set<unsigned> &InputRegs,
3916                         const TargetRegisterInfo &TRI) const {
3917    if (isOutReg) {
3918      for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3919        MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3920    }
3921    if (isInReg) {
3922      for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3923        MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3924    }
3925  }
3926
3927private:
3928  /// MarkRegAndAliases - Mark the specified register and all aliases in the
3929  /// specified set.
3930  static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3931                                const TargetRegisterInfo &TRI) {
3932    assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3933    Regs.insert(Reg);
3934    if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3935      for (; *Aliases; ++Aliases)
3936        Regs.insert(*Aliases);
3937  }
3938};
3939} // end anon namespace.
3940
3941
3942/// GetRegistersForValue - Assign registers (virtual or physical) for the
3943/// specified operand.  We prefer to assign virtual registers, to allow the
3944/// register allocator handle the assignment process.  However, if the asm uses
3945/// features that we can't model on machineinstrs, we have SDISel do the
3946/// allocation.  This produces generally horrible, but correct, code.
3947///
3948///   OpInfo describes the operand.
3949///   HasEarlyClobber is true if there are any early clobber constraints (=&r)
3950///     or any explicitly clobbered registers.
3951///   Input and OutputRegs are the set of already allocated physical registers.
3952///
3953void SelectionDAGLowering::
3954GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3955                     std::set<unsigned> &OutputRegs,
3956                     std::set<unsigned> &InputRegs) {
3957  // Compute whether this value requires an input register, an output register,
3958  // or both.
3959  bool isOutReg = false;
3960  bool isInReg = false;
3961  switch (OpInfo.Type) {
3962  case InlineAsm::isOutput:
3963    isOutReg = true;
3964
3965    // If this is an early-clobber output, or if there is an input
3966    // constraint that matches this, we need to reserve the input register
3967    // so no other inputs allocate to it.
3968    isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3969    break;
3970  case InlineAsm::isInput:
3971    isInReg = true;
3972    isOutReg = false;
3973    break;
3974  case InlineAsm::isClobber:
3975    isOutReg = true;
3976    isInReg = true;
3977    break;
3978  }
3979
3980
3981  MachineFunction &MF = DAG.getMachineFunction();
3982  SmallVector<unsigned, 4> Regs;
3983
3984  // If this is a constraint for a single physreg, or a constraint for a
3985  // register class, find it.
3986  std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3987    TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3988                                     OpInfo.ConstraintVT);
3989
3990  unsigned NumRegs = 1;
3991  if (OpInfo.ConstraintVT != MVT::Other)
3992    NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3993  MVT RegVT;
3994  MVT ValueVT = OpInfo.ConstraintVT;
3995
3996
3997  // If this is a constraint for a specific physical register, like {r17},
3998  // assign it now.
3999  if (PhysReg.first) {
4000    if (OpInfo.ConstraintVT == MVT::Other)
4001      ValueVT = *PhysReg.second->vt_begin();
4002
4003    // Get the actual register value type.  This is important, because the user
4004    // may have asked for (e.g.) the AX register in i32 type.  We need to
4005    // remember that AX is actually i16 to get the right extension.
4006    RegVT = *PhysReg.second->vt_begin();
4007
4008    // This is a explicit reference to a physical register.
4009    Regs.push_back(PhysReg.first);
4010
4011    // If this is an expanded reference, add the rest of the regs to Regs.
4012    if (NumRegs != 1) {
4013      TargetRegisterClass::iterator I = PhysReg.second->begin();
4014      for (; *I != PhysReg.first; ++I)
4015        assert(I != PhysReg.second->end() && "Didn't find reg!");
4016
4017      // Already added the first reg.
4018      --NumRegs; ++I;
4019      for (; NumRegs; --NumRegs, ++I) {
4020        assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4021        Regs.push_back(*I);
4022      }
4023    }
4024    OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4025    const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4026    OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4027    return;
4028  }
4029
4030  // Otherwise, if this was a reference to an LLVM register class, create vregs
4031  // for this reference.
4032  std::vector<unsigned> RegClassRegs;
4033  const TargetRegisterClass *RC = PhysReg.second;
4034  if (RC) {
4035    // If this is an early clobber or tied register, our regalloc doesn't know
4036    // how to maintain the constraint.  If it isn't, go ahead and create vreg
4037    // and let the regalloc do the right thing.
4038    if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
4039        // If there is some other early clobber and this is an input register,
4040        // then we are forced to pre-allocate the input reg so it doesn't
4041        // conflict with the earlyclobber.
4042        !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
4043      RegVT = *PhysReg.second->vt_begin();
4044
4045      if (OpInfo.ConstraintVT == MVT::Other)
4046        ValueVT = RegVT;
4047
4048      // Create the appropriate number of virtual registers.
4049      MachineRegisterInfo &RegInfo = MF.getRegInfo();
4050      for (; NumRegs; --NumRegs)
4051        Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4052
4053      OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4054      return;
4055    }
4056
4057    // Otherwise, we can't allocate it.  Let the code below figure out how to
4058    // maintain these constraints.
4059    RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4060
4061  } else {
4062    // This is a reference to a register class that doesn't directly correspond
4063    // to an LLVM register class.  Allocate NumRegs consecutive, available,
4064    // registers from the class.
4065    RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4066                                                         OpInfo.ConstraintVT);
4067  }
4068
4069  const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4070  unsigned NumAllocated = 0;
4071  for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4072    unsigned Reg = RegClassRegs[i];
4073    // See if this register is available.
4074    if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
4075        (isInReg  && InputRegs.count(Reg))) {    // Already used.
4076      // Make sure we find consecutive registers.
4077      NumAllocated = 0;
4078      continue;
4079    }
4080
4081    // Check to see if this register is allocatable (i.e. don't give out the
4082    // stack pointer).
4083    if (RC == 0) {
4084      RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4085      if (!RC) {        // Couldn't allocate this register.
4086        // Reset NumAllocated to make sure we return consecutive registers.
4087        NumAllocated = 0;
4088        continue;
4089      }
4090    }
4091
4092    // Okay, this register is good, we can use it.
4093    ++NumAllocated;
4094
4095    // If we allocated enough consecutive registers, succeed.
4096    if (NumAllocated == NumRegs) {
4097      unsigned RegStart = (i-NumAllocated)+1;
4098      unsigned RegEnd   = i+1;
4099      // Mark all of the allocated registers used.
4100      for (unsigned i = RegStart; i != RegEnd; ++i)
4101        Regs.push_back(RegClassRegs[i]);
4102
4103      OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4104                                         OpInfo.ConstraintVT);
4105      OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4106      return;
4107    }
4108  }
4109
4110  // Otherwise, we couldn't allocate enough registers for this.
4111}
4112
4113
4114/// visitInlineAsm - Handle a call to an InlineAsm object.
4115///
4116void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4117  InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4118
4119  /// ConstraintOperands - Information about all of the constraints.
4120  std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4121
4122  SDOperand Chain = getRoot();
4123  SDOperand Flag;
4124
4125  std::set<unsigned> OutputRegs, InputRegs;
4126
4127  // Do a prepass over the constraints, canonicalizing them, and building up the
4128  // ConstraintOperands list.
4129  std::vector<InlineAsm::ConstraintInfo>
4130    ConstraintInfos = IA->ParseConstraints();
4131
4132  // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
4133  // constraint.  If so, we can't let the register allocator allocate any input
4134  // registers, because it will not know to avoid the earlyclobbered output reg.
4135  bool SawEarlyClobber = false;
4136
4137  unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
4138  unsigned ResNo = 0;   // ResNo - The result number of the next output.
4139  for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4140    ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4141    SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4142
4143    MVT OpVT = MVT::Other;
4144
4145    // Compute the value type for each operand.
4146    switch (OpInfo.Type) {
4147    case InlineAsm::isOutput:
4148      // Indirect outputs just consume an argument.
4149      if (OpInfo.isIndirect) {
4150        OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4151        break;
4152      }
4153      // The return value of the call is this value.  As such, there is no
4154      // corresponding argument.
4155      assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4156      if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4157        OpVT = TLI.getValueType(STy->getElementType(ResNo));
4158      } else {
4159        assert(ResNo == 0 && "Asm only has one result!");
4160        OpVT = TLI.getValueType(CS.getType());
4161      }
4162      ++ResNo;
4163      break;
4164    case InlineAsm::isInput:
4165      OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4166      break;
4167    case InlineAsm::isClobber:
4168      // Nothing to do.
4169      break;
4170    }
4171
4172    // If this is an input or an indirect output, process the call argument.
4173    // BasicBlocks are labels, currently appearing only in asm's.
4174    if (OpInfo.CallOperandVal) {
4175      if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4176        OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4177      else {
4178        OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4179        const Type *OpTy = OpInfo.CallOperandVal->getType();
4180        // If this is an indirect operand, the operand is a pointer to the
4181        // accessed type.
4182        if (OpInfo.isIndirect)
4183          OpTy = cast<PointerType>(OpTy)->getElementType();
4184
4185        // If OpTy is not a single value, it may be a struct/union that we
4186        // can tile with integers.
4187        if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4188          unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4189          switch (BitSize) {
4190          default: break;
4191          case 1:
4192          case 8:
4193          case 16:
4194          case 32:
4195          case 64:
4196            OpTy = IntegerType::get(BitSize);
4197            break;
4198          }
4199        }
4200
4201        OpVT = TLI.getValueType(OpTy, true);
4202      }
4203    }
4204
4205    OpInfo.ConstraintVT = OpVT;
4206
4207    // Compute the constraint code and ConstraintType to use.
4208    TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
4209
4210    // Keep track of whether we see an earlyclobber.
4211    SawEarlyClobber |= OpInfo.isEarlyClobber;
4212
4213    // If we see a clobber of a register, it is an early clobber.
4214    if (!SawEarlyClobber &&
4215        OpInfo.Type == InlineAsm::isClobber &&
4216        OpInfo.ConstraintType == TargetLowering::C_Register) {
4217      // Note that we want to ignore things that we don't trick here, like
4218      // dirflag, fpsr, flags, etc.
4219      std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4220        TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4221                                         OpInfo.ConstraintVT);
4222      if (PhysReg.first || PhysReg.second) {
4223        // This is a register we know of.
4224        SawEarlyClobber = true;
4225      }
4226    }
4227
4228    // If this is a memory input, and if the operand is not indirect, do what we
4229    // need to to provide an address for the memory input.
4230    if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4231        !OpInfo.isIndirect) {
4232      assert(OpInfo.Type == InlineAsm::isInput &&
4233             "Can only indirectify direct input operands!");
4234
4235      // Memory operands really want the address of the value.  If we don't have
4236      // an indirect input, put it in the constpool if we can, otherwise spill
4237      // it to a stack slot.
4238
4239      // If the operand is a float, integer, or vector constant, spill to a
4240      // constant pool entry to get its address.
4241      Value *OpVal = OpInfo.CallOperandVal;
4242      if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4243          isa<ConstantVector>(OpVal)) {
4244        OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4245                                                 TLI.getPointerTy());
4246      } else {
4247        // Otherwise, create a stack slot and emit a store to it before the
4248        // asm.
4249        const Type *Ty = OpVal->getType();
4250        uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4251        unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4252        MachineFunction &MF = DAG.getMachineFunction();
4253        int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4254        SDOperand StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4255        Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4256        OpInfo.CallOperand = StackSlot;
4257      }
4258
4259      // There is no longer a Value* corresponding to this operand.
4260      OpInfo.CallOperandVal = 0;
4261      // It is now an indirect operand.
4262      OpInfo.isIndirect = true;
4263    }
4264
4265    // If this constraint is for a specific register, allocate it before
4266    // anything else.
4267    if (OpInfo.ConstraintType == TargetLowering::C_Register)
4268      GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4269  }
4270  ConstraintInfos.clear();
4271
4272
4273  // Second pass - Loop over all of the operands, assigning virtual or physregs
4274  // to registerclass operands.
4275  for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4276    SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4277
4278    // C_Register operands have already been allocated, Other/Memory don't need
4279    // to be.
4280    if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4281      GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4282  }
4283
4284  // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4285  std::vector<SDOperand> AsmNodeOperands;
4286  AsmNodeOperands.push_back(SDOperand());  // reserve space for input chain
4287  AsmNodeOperands.push_back(
4288          DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4289
4290
4291  // Loop over all of the inputs, copying the operand values into the
4292  // appropriate registers and processing the output regs.
4293  RegsForValue RetValRegs;
4294
4295  // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4296  std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4297
4298  for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4299    SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4300
4301    switch (OpInfo.Type) {
4302    case InlineAsm::isOutput: {
4303      if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4304          OpInfo.ConstraintType != TargetLowering::C_Register) {
4305        // Memory output, or 'other' output (e.g. 'X' constraint).
4306        assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4307
4308        // Add information to the INLINEASM node to know about this output.
4309        unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4310        AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4311                                                        TLI.getPointerTy()));
4312        AsmNodeOperands.push_back(OpInfo.CallOperand);
4313        break;
4314      }
4315
4316      // Otherwise, this is a register or register class output.
4317
4318      // Copy the output from the appropriate register.  Find a register that
4319      // we can use.
4320      if (OpInfo.AssignedRegs.Regs.empty()) {
4321        cerr << "Couldn't allocate output reg for constraint '"
4322             << OpInfo.ConstraintCode << "'!\n";
4323        exit(1);
4324      }
4325
4326      // If this is an indirect operand, store through the pointer after the
4327      // asm.
4328      if (OpInfo.isIndirect) {
4329        IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4330                                                      OpInfo.CallOperandVal));
4331      } else {
4332        // This is the result value of the call.
4333        assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4334        // Concatenate this output onto the outputs list.
4335        RetValRegs.append(OpInfo.AssignedRegs);
4336      }
4337
4338      // Add information to the INLINEASM node to know that this register is
4339      // set.
4340      OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4341                                               AsmNodeOperands);
4342      break;
4343    }
4344    case InlineAsm::isInput: {
4345      SDOperand InOperandVal = OpInfo.CallOperand;
4346
4347      if (isdigit(OpInfo.ConstraintCode[0])) {    // Matching constraint?
4348        // If this is required to match an output register we have already set,
4349        // just use its register.
4350        unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4351
4352        // Scan until we find the definition we already emitted of this operand.
4353        // When we find it, create a RegsForValue operand.
4354        unsigned CurOp = 2;  // The first operand.
4355        for (; OperandNo; --OperandNo) {
4356          // Advance to the next operand.
4357          unsigned NumOps =
4358            cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4359          assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4360                  (NumOps & 7) == 4 /*MEM*/) &&
4361                 "Skipped past definitions?");
4362          CurOp += (NumOps>>3)+1;
4363        }
4364
4365        unsigned NumOps =
4366          cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4367        if ((NumOps & 7) == 2 /*REGDEF*/) {
4368          // Add NumOps>>3 registers to MatchedRegs.
4369          RegsForValue MatchedRegs;
4370          MatchedRegs.TLI = &TLI;
4371          MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4372          MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4373          for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4374            unsigned Reg =
4375              cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4376            MatchedRegs.Regs.push_back(Reg);
4377          }
4378
4379          // Use the produced MatchedRegs object to
4380          MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4381          MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4382          break;
4383        } else {
4384          assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4385          assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4386          // Add information to the INLINEASM node to know about this input.
4387          unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4388          AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4389                                                          TLI.getPointerTy()));
4390          AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4391          break;
4392        }
4393      }
4394
4395      if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4396        assert(!OpInfo.isIndirect &&
4397               "Don't know how to handle indirect other inputs yet!");
4398
4399        std::vector<SDOperand> Ops;
4400        TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4401                                         Ops, DAG);
4402        if (Ops.empty()) {
4403          cerr << "Invalid operand for inline asm constraint '"
4404               << OpInfo.ConstraintCode << "'!\n";
4405          exit(1);
4406        }
4407
4408        // Add information to the INLINEASM node to know about this input.
4409        unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4410        AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4411                                                        TLI.getPointerTy()));
4412        AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4413        break;
4414      } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4415        assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4416        assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4417               "Memory operands expect pointer values");
4418
4419        // Add information to the INLINEASM node to know about this input.
4420        unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4421        AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4422                                                        TLI.getPointerTy()));
4423        AsmNodeOperands.push_back(InOperandVal);
4424        break;
4425      }
4426
4427      assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4428              OpInfo.ConstraintType == TargetLowering::C_Register) &&
4429             "Unknown constraint type!");
4430      assert(!OpInfo.isIndirect &&
4431             "Don't know how to handle indirect register inputs yet!");
4432
4433      // Copy the input into the appropriate registers.
4434      assert(!OpInfo.AssignedRegs.Regs.empty() &&
4435             "Couldn't allocate input reg!");
4436
4437      OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4438
4439      OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4440                                               AsmNodeOperands);
4441      break;
4442    }
4443    case InlineAsm::isClobber: {
4444      // Add the clobbered value to the operand list, so that the register
4445      // allocator is aware that the physreg got clobbered.
4446      if (!OpInfo.AssignedRegs.Regs.empty())
4447        OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4448                                                 AsmNodeOperands);
4449      break;
4450    }
4451    }
4452  }
4453
4454  // Finish up input operands.
4455  AsmNodeOperands[0] = Chain;
4456  if (Flag.Val) AsmNodeOperands.push_back(Flag);
4457
4458  Chain = DAG.getNode(ISD::INLINEASM,
4459                      DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4460                      &AsmNodeOperands[0], AsmNodeOperands.size());
4461  Flag = Chain.getValue(1);
4462
4463  // If this asm returns a register value, copy the result from that register
4464  // and set it as the value of the call.
4465  if (!RetValRegs.Regs.empty()) {
4466    SDOperand Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4467
4468    // If any of the results of the inline asm is a vector, it may have the
4469    // wrong width/num elts.  This can happen for register classes that can
4470    // contain multiple different value types.  The preg or vreg allocated may
4471    // not have the same VT as was expected.  Convert it to the right type with
4472    // bit_convert.
4473    if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4474      for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4475        if (Val.Val->getValueType(i).isVector())
4476          Val = DAG.getNode(ISD::BIT_CONVERT,
4477                            TLI.getValueType(ResSTy->getElementType(i)), Val);
4478      }
4479    } else {
4480      if (Val.getValueType().isVector())
4481        Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4482                          Val);
4483    }
4484
4485    setValue(CS.getInstruction(), Val);
4486  }
4487
4488  std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
4489
4490  // Process indirect outputs, first output all of the flagged copies out of
4491  // physregs.
4492  for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4493    RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4494    Value *Ptr = IndirectStoresToEmit[i].second;
4495    SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4496    StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4497  }
4498
4499  // Emit the non-flagged stores from the physregs.
4500  SmallVector<SDOperand, 8> OutChains;
4501  for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4502    OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4503                                    getValue(StoresToEmit[i].second),
4504                                    StoresToEmit[i].second, 0));
4505  if (!OutChains.empty())
4506    Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4507                        &OutChains[0], OutChains.size());
4508  DAG.setRoot(Chain);
4509}
4510
4511
4512void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4513  SDOperand Src = getValue(I.getOperand(0));
4514
4515  MVT IntPtr = TLI.getPointerTy();
4516
4517  if (IntPtr.bitsLT(Src.getValueType()))
4518    Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4519  else if (IntPtr.bitsGT(Src.getValueType()))
4520    Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4521
4522  // Scale the source by the type size.
4523  uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4524  Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4525                    Src, DAG.getIntPtrConstant(ElementSize));
4526
4527  TargetLowering::ArgListTy Args;
4528  TargetLowering::ArgListEntry Entry;
4529  Entry.Node = Src;
4530  Entry.Ty = TLI.getTargetData()->getIntPtrType();
4531  Args.push_back(Entry);
4532
4533  std::pair<SDOperand,SDOperand> Result =
4534    TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4535                    true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4536  setValue(&I, Result.first);  // Pointers always fit in registers
4537  DAG.setRoot(Result.second);
4538}
4539
4540void SelectionDAGLowering::visitFree(FreeInst &I) {
4541  TargetLowering::ArgListTy Args;
4542  TargetLowering::ArgListEntry Entry;
4543  Entry.Node = getValue(I.getOperand(0));
4544  Entry.Ty = TLI.getTargetData()->getIntPtrType();
4545  Args.push_back(Entry);
4546  MVT IntPtr = TLI.getPointerTy();
4547  std::pair<SDOperand,SDOperand> Result =
4548    TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4549                    CallingConv::C, true,
4550                    DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4551  DAG.setRoot(Result.second);
4552}
4553
4554// EmitInstrWithCustomInserter - This method should be implemented by targets
4555// that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
4556// instructions are special in various ways, which require special support to
4557// insert.  The specified MachineInstr is created but not inserted into any
4558// basic blocks, and the scheduler passes ownership of it to this method.
4559MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
4560                                                       MachineBasicBlock *MBB) {
4561  cerr << "If a target marks an instruction with "
4562       << "'usesCustomDAGSchedInserter', it must implement "
4563       << "TargetLowering::EmitInstrWithCustomInserter!\n";
4564  abort();
4565  return 0;
4566}
4567
4568void SelectionDAGLowering::visitVAStart(CallInst &I) {
4569  DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4570                          getValue(I.getOperand(1)),
4571                          DAG.getSrcValue(I.getOperand(1))));
4572}
4573
4574void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4575  SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4576                             getValue(I.getOperand(0)),
4577                             DAG.getSrcValue(I.getOperand(0)));
4578  setValue(&I, V);
4579  DAG.setRoot(V.getValue(1));
4580}
4581
4582void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4583  DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4584                          getValue(I.getOperand(1)),
4585                          DAG.getSrcValue(I.getOperand(1))));
4586}
4587
4588void SelectionDAGLowering::visitVACopy(CallInst &I) {
4589  DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4590                          getValue(I.getOperand(1)),
4591                          getValue(I.getOperand(2)),
4592                          DAG.getSrcValue(I.getOperand(1)),
4593                          DAG.getSrcValue(I.getOperand(2))));
4594}
4595
4596/// TargetLowering::LowerArguments - This is the default LowerArguments
4597/// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
4598/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4599/// integrated into SDISel.
4600void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
4601                                    SmallVectorImpl<SDOperand> &ArgValues) {
4602  // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4603  SmallVector<SDOperand, 3+16> Ops;
4604  Ops.push_back(DAG.getRoot());
4605  Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4606  Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4607
4608  // Add one result value for each formal argument.
4609  SmallVector<MVT, 16> RetVals;
4610  unsigned j = 1;
4611  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4612       I != E; ++I, ++j) {
4613    SmallVector<MVT, 4> ValueVTs;
4614    ComputeValueVTs(*this, I->getType(), ValueVTs);
4615    for (unsigned Value = 0, NumValues = ValueVTs.size();
4616         Value != NumValues; ++Value) {
4617      MVT VT = ValueVTs[Value];
4618      const Type *ArgTy = VT.getTypeForMVT();
4619      ISD::ArgFlagsTy Flags;
4620      unsigned OriginalAlignment =
4621        getTargetData()->getABITypeAlignment(ArgTy);
4622
4623      if (F.paramHasAttr(j, ParamAttr::ZExt))
4624        Flags.setZExt();
4625      if (F.paramHasAttr(j, ParamAttr::SExt))
4626        Flags.setSExt();
4627      if (F.paramHasAttr(j, ParamAttr::InReg))
4628        Flags.setInReg();
4629      if (F.paramHasAttr(j, ParamAttr::StructRet))
4630        Flags.setSRet();
4631      if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4632        Flags.setByVal();
4633        const PointerType *Ty = cast<PointerType>(I->getType());
4634        const Type *ElementTy = Ty->getElementType();
4635        unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4636        unsigned FrameSize  = getTargetData()->getABITypeSize(ElementTy);
4637        // For ByVal, alignment should be passed from FE.  BE will guess if
4638        // this info is not there but there are cases it cannot get right.
4639        if (F.getParamAlignment(j))
4640          FrameAlign = F.getParamAlignment(j);
4641        Flags.setByValAlign(FrameAlign);
4642        Flags.setByValSize(FrameSize);
4643      }
4644      if (F.paramHasAttr(j, ParamAttr::Nest))
4645        Flags.setNest();
4646      Flags.setOrigAlign(OriginalAlignment);
4647
4648      MVT RegisterVT = getRegisterType(VT);
4649      unsigned NumRegs = getNumRegisters(VT);
4650      for (unsigned i = 0; i != NumRegs; ++i) {
4651        RetVals.push_back(RegisterVT);
4652        ISD::ArgFlagsTy MyFlags = Flags;
4653        if (NumRegs > 1 && i == 0)
4654          MyFlags.setSplit();
4655        // if it isn't first piece, alignment must be 1
4656        else if (i > 0)
4657          MyFlags.setOrigAlign(1);
4658        Ops.push_back(DAG.getArgFlags(MyFlags));
4659      }
4660    }
4661  }
4662
4663  RetVals.push_back(MVT::Other);
4664
4665  // Create the node.
4666  SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4667                               DAG.getVTList(&RetVals[0], RetVals.size()),
4668                               &Ops[0], Ops.size()).Val;
4669
4670  // Prelower FORMAL_ARGUMENTS.  This isn't required for functionality, but
4671  // allows exposing the loads that may be part of the argument access to the
4672  // first DAGCombiner pass.
4673  SDOperand TmpRes = LowerOperation(SDOperand(Result, 0), DAG);
4674
4675  // The number of results should match up, except that the lowered one may have
4676  // an extra flag result.
4677  assert((Result->getNumValues() == TmpRes.Val->getNumValues() ||
4678          (Result->getNumValues()+1 == TmpRes.Val->getNumValues() &&
4679           TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4680         && "Lowering produced unexpected number of results!");
4681  Result = TmpRes.Val;
4682
4683  unsigned NumArgRegs = Result->getNumValues() - 1;
4684  DAG.setRoot(SDOperand(Result, NumArgRegs));
4685
4686  // Set up the return result vector.
4687  unsigned i = 0;
4688  unsigned Idx = 1;
4689  for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4690      ++I, ++Idx) {
4691    SmallVector<MVT, 4> ValueVTs;
4692    ComputeValueVTs(*this, I->getType(), ValueVTs);
4693    for (unsigned Value = 0, NumValues = ValueVTs.size();
4694         Value != NumValues; ++Value) {
4695      MVT VT = ValueVTs[Value];
4696      MVT PartVT = getRegisterType(VT);
4697
4698      unsigned NumParts = getNumRegisters(VT);
4699      SmallVector<SDOperand, 4> Parts(NumParts);
4700      for (unsigned j = 0; j != NumParts; ++j)
4701        Parts[j] = SDOperand(Result, i++);
4702
4703      ISD::NodeType AssertOp = ISD::DELETED_NODE;
4704      if (F.paramHasAttr(Idx, ParamAttr::SExt))
4705        AssertOp = ISD::AssertSext;
4706      else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4707        AssertOp = ISD::AssertZext;
4708
4709      ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4710                                           AssertOp));
4711    }
4712  }
4713  assert(i == NumArgRegs && "Argument register count mismatch!");
4714}
4715
4716
4717/// TargetLowering::LowerCallTo - This is the default LowerCallTo
4718/// implementation, which just inserts an ISD::CALL node, which is later custom
4719/// lowered by the target to something concrete.  FIXME: When all targets are
4720/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4721std::pair<SDOperand, SDOperand>
4722TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
4723                            bool RetSExt, bool RetZExt, bool isVarArg,
4724                            unsigned CallingConv, bool isTailCall,
4725                            SDOperand Callee,
4726                            ArgListTy &Args, SelectionDAG &DAG) {
4727  SmallVector<SDOperand, 32> Ops;
4728  Ops.push_back(Chain);   // Op#0 - Chain
4729  Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4730  Ops.push_back(DAG.getConstant(isVarArg, getPointerTy()));    // Op#2 - VarArg
4731  Ops.push_back(DAG.getConstant(isTailCall, getPointerTy()));  // Op#3 - Tail
4732  Ops.push_back(Callee);
4733
4734  // Handle all of the outgoing arguments.
4735  for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4736    SmallVector<MVT, 4> ValueVTs;
4737    ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4738    for (unsigned Value = 0, NumValues = ValueVTs.size();
4739         Value != NumValues; ++Value) {
4740      MVT VT = ValueVTs[Value];
4741      const Type *ArgTy = VT.getTypeForMVT();
4742      SDOperand Op = SDOperand(Args[i].Node.Val, Args[i].Node.ResNo + Value);
4743      ISD::ArgFlagsTy Flags;
4744      unsigned OriginalAlignment =
4745        getTargetData()->getABITypeAlignment(ArgTy);
4746
4747      if (Args[i].isZExt)
4748        Flags.setZExt();
4749      if (Args[i].isSExt)
4750        Flags.setSExt();
4751      if (Args[i].isInReg)
4752        Flags.setInReg();
4753      if (Args[i].isSRet)
4754        Flags.setSRet();
4755      if (Args[i].isByVal) {
4756        Flags.setByVal();
4757        const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4758        const Type *ElementTy = Ty->getElementType();
4759        unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4760        unsigned FrameSize  = getTargetData()->getABITypeSize(ElementTy);
4761        // For ByVal, alignment should come from FE.  BE will guess if this
4762        // info is not there but there are cases it cannot get right.
4763        if (Args[i].Alignment)
4764          FrameAlign = Args[i].Alignment;
4765        Flags.setByValAlign(FrameAlign);
4766        Flags.setByValSize(FrameSize);
4767      }
4768      if (Args[i].isNest)
4769        Flags.setNest();
4770      Flags.setOrigAlign(OriginalAlignment);
4771
4772      MVT PartVT = getRegisterType(VT);
4773      unsigned NumParts = getNumRegisters(VT);
4774      SmallVector<SDOperand, 4> Parts(NumParts);
4775      ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4776
4777      if (Args[i].isSExt)
4778        ExtendKind = ISD::SIGN_EXTEND;
4779      else if (Args[i].isZExt)
4780        ExtendKind = ISD::ZERO_EXTEND;
4781
4782      getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4783
4784      for (unsigned i = 0; i != NumParts; ++i) {
4785        // if it isn't first piece, alignment must be 1
4786        ISD::ArgFlagsTy MyFlags = Flags;
4787        if (NumParts > 1 && i == 0)
4788          MyFlags.setSplit();
4789        else if (i != 0)
4790          MyFlags.setOrigAlign(1);
4791
4792        Ops.push_back(Parts[i]);
4793        Ops.push_back(DAG.getArgFlags(MyFlags));
4794      }
4795    }
4796  }
4797
4798  // Figure out the result value types. We start by making a list of
4799  // the potentially illegal return value types.
4800  SmallVector<MVT, 4> LoweredRetTys;
4801  SmallVector<MVT, 4> RetTys;
4802  ComputeValueVTs(*this, RetTy, RetTys);
4803
4804  // Then we translate that to a list of legal types.
4805  for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4806    MVT VT = RetTys[I];
4807    MVT RegisterVT = getRegisterType(VT);
4808    unsigned NumRegs = getNumRegisters(VT);
4809    for (unsigned i = 0; i != NumRegs; ++i)
4810      LoweredRetTys.push_back(RegisterVT);
4811  }
4812
4813  LoweredRetTys.push_back(MVT::Other);  // Always has a chain.
4814
4815  // Create the CALL node.
4816  SDOperand Res = DAG.getNode(ISD::CALL,
4817                              DAG.getVTList(&LoweredRetTys[0],
4818                                            LoweredRetTys.size()),
4819                              &Ops[0], Ops.size());
4820  Chain = Res.getValue(LoweredRetTys.size() - 1);
4821
4822  // Gather up the call result into a single value.
4823  if (RetTy != Type::VoidTy) {
4824    ISD::NodeType AssertOp = ISD::DELETED_NODE;
4825
4826    if (RetSExt)
4827      AssertOp = ISD::AssertSext;
4828    else if (RetZExt)
4829      AssertOp = ISD::AssertZext;
4830
4831    SmallVector<SDOperand, 4> ReturnValues;
4832    unsigned RegNo = 0;
4833    for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4834      MVT VT = RetTys[I];
4835      MVT RegisterVT = getRegisterType(VT);
4836      unsigned NumRegs = getNumRegisters(VT);
4837      unsigned RegNoEnd = NumRegs + RegNo;
4838      SmallVector<SDOperand, 4> Results;
4839      for (; RegNo != RegNoEnd; ++RegNo)
4840        Results.push_back(Res.getValue(RegNo));
4841      SDOperand ReturnValue =
4842        getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4843                         AssertOp);
4844      ReturnValues.push_back(ReturnValue);
4845    }
4846    Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4847                             &ReturnValues[0], ReturnValues.size());
4848  }
4849
4850  return std::make_pair(Res, Chain);
4851}
4852
4853SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
4854  assert(0 && "LowerOperation not implemented for this target!");
4855  abort();
4856  return SDOperand();
4857}
4858
4859SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
4860                                                 SelectionDAG &DAG) {
4861  assert(0 && "CustomPromoteOperation not implemented for this target!");
4862  abort();
4863  return SDOperand();
4864}
4865
4866//===----------------------------------------------------------------------===//
4867// SelectionDAGISel code
4868//===----------------------------------------------------------------------===//
4869
4870unsigned SelectionDAGISel::MakeReg(MVT VT) {
4871  return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
4872}
4873
4874void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
4875  AU.addRequired<AliasAnalysis>();
4876  AU.addRequired<CollectorModuleMetadata>();
4877  AU.setPreservesAll();
4878}
4879
4880bool SelectionDAGISel::runOnFunction(Function &Fn) {
4881  // Get alias analysis for load/store combining.
4882  AA = &getAnalysis<AliasAnalysis>();
4883
4884  MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
4885  if (MF.getFunction()->hasCollector())
4886    GCI = &getAnalysis<CollectorModuleMetadata>().get(*MF.getFunction());
4887  else
4888    GCI = 0;
4889  RegInfo = &MF.getRegInfo();
4890  DOUT << "\n\n\n=== " << Fn.getName() << "\n";
4891
4892  FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
4893
4894  for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4895    if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
4896      // Mark landing pad.
4897      FuncInfo.MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
4898
4899  for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
4900    SelectBasicBlock(I, MF, FuncInfo);
4901
4902  // Add function live-ins to entry block live-in set.
4903  BasicBlock *EntryBB = &Fn.getEntryBlock();
4904  BB = FuncInfo.MBBMap[EntryBB];
4905  if (!RegInfo->livein_empty())
4906    for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
4907           E = RegInfo->livein_end(); I != E; ++I)
4908      BB->addLiveIn(I->first);
4909
4910#ifndef NDEBUG
4911  assert(FuncInfo.CatchInfoFound.size() == FuncInfo.CatchInfoLost.size() &&
4912         "Not all catch info was assigned to a landing pad!");
4913#endif
4914
4915  return true;
4916}
4917
4918void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4919  SDOperand Op = getValue(V);
4920  assert((Op.getOpcode() != ISD::CopyFromReg ||
4921          cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4922         "Copy from a reg to the same reg!");
4923  assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4924
4925  RegsForValue RFV(TLI, Reg, V->getType());
4926  SDOperand Chain = DAG.getEntryNode();
4927  RFV.getCopyToRegs(Op, DAG, Chain, 0);
4928  PendingExports.push_back(Chain);
4929}
4930
4931void SelectionDAGISel::
4932LowerArguments(BasicBlock *LLVMBB, SelectionDAGLowering &SDL) {
4933  // If this is the entry block, emit arguments.
4934  Function &F = *LLVMBB->getParent();
4935  FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
4936  SDOperand OldRoot = SDL.DAG.getRoot();
4937  SmallVector<SDOperand, 16> Args;
4938  TLI.LowerArguments(F, SDL.DAG, Args);
4939
4940  unsigned a = 0;
4941  for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4942       AI != E; ++AI) {
4943    SmallVector<MVT, 4> ValueVTs;
4944    ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4945    unsigned NumValues = ValueVTs.size();
4946    if (!AI->use_empty()) {
4947      SmallVector<MVT, 4> LegalValueVTs(NumValues);
4948      for (unsigned VI = 0; VI != NumValues; ++VI)
4949        LegalValueVTs[VI] = Args[a + VI].getValueType();
4950      SDL.setValue(AI,
4951                   SDL.DAG.getMergeValues(SDL.DAG.getVTList(&LegalValueVTs[0],
4952                                                            NumValues),
4953                                          &Args[a], NumValues));
4954      // If this argument is live outside of the entry block, insert a copy from
4955      // whereever we got it to the vreg that other BB's will reference it as.
4956      DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo.ValueMap.find(AI);
4957      if (VMI != FuncInfo.ValueMap.end()) {
4958        SDL.CopyValueToVirtualRegister(AI, VMI->second);
4959      }
4960    }
4961    a += NumValues;
4962  }
4963
4964  // Finally, if the target has anything special to do, allow it to do so.
4965  // FIXME: this should insert code into the DAG!
4966  EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
4967}
4968
4969static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
4970                          MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
4971  for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
4972    if (isSelector(I)) {
4973      // Apply the catch info to DestBB.
4974      addCatchInfo(cast<CallInst>(*I), MMI, FLI.MBBMap[DestBB]);
4975#ifndef NDEBUG
4976      if (!FLI.MBBMap[SrcBB]->isLandingPad())
4977        FLI.CatchInfoFound.insert(I);
4978#endif
4979    }
4980}
4981
4982/// IsFixedFrameObjectWithPosOffset - Check if object is a fixed frame object and
4983/// whether object offset >= 0.
4984static bool
4985IsFixedFrameObjectWithPosOffset(MachineFrameInfo * MFI, SDOperand Op) {
4986  if (!isa<FrameIndexSDNode>(Op)) return false;
4987
4988  FrameIndexSDNode * FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op);
4989  int FrameIdx =  FrameIdxNode->getIndex();
4990  return MFI->isFixedObjectIndex(FrameIdx) &&
4991    MFI->getObjectOffset(FrameIdx) >= 0;
4992}
4993
4994/// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
4995/// possibly be overwritten when lowering the outgoing arguments in a tail
4996/// call. Currently the implementation of this call is very conservative and
4997/// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
4998/// virtual registers would be overwritten by direct lowering.
4999static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
5000                                                    MachineFrameInfo * MFI) {
5001  RegisterSDNode * OpReg = NULL;
5002  if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
5003      (Op.getOpcode()== ISD::CopyFromReg &&
5004       (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
5005       (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
5006      (Op.getOpcode() == ISD::LOAD &&
5007       IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(1))) ||
5008      (Op.getOpcode() == ISD::MERGE_VALUES &&
5009       Op.getOperand(Op.ResNo).getOpcode() == ISD::LOAD &&
5010       IsFixedFrameObjectWithPosOffset(MFI, Op.getOperand(Op.ResNo).
5011                                       getOperand(1))))
5012    return true;
5013  return false;
5014}
5015
5016/// CheckDAGForTailCallsAndFixThem - This Function looks for CALL nodes in the
5017/// DAG and fixes their tailcall attribute operand.
5018static void CheckDAGForTailCallsAndFixThem(SelectionDAG &DAG,
5019                                           TargetLowering& TLI) {
5020  SDNode * Ret = NULL;
5021  SDOperand Terminator = DAG.getRoot();
5022
5023  // Find RET node.
5024  if (Terminator.getOpcode() == ISD::RET) {
5025    Ret = Terminator.Val;
5026  }
5027
5028  // Fix tail call attribute of CALL nodes.
5029  for (SelectionDAG::allnodes_iterator BE = DAG.allnodes_begin(),
5030         BI = prior(DAG.allnodes_end()); BI != BE; --BI) {
5031    if (BI->getOpcode() == ISD::CALL) {
5032      SDOperand OpRet(Ret, 0);
5033      SDOperand OpCall(static_cast<SDNode*>(BI), 0);
5034      bool isMarkedTailCall =
5035        cast<ConstantSDNode>(OpCall.getOperand(3))->getValue() != 0;
5036      // If CALL node has tail call attribute set to true and the call is not
5037      // eligible (no RET or the target rejects) the attribute is fixed to
5038      // false. The TargetLowering::IsEligibleForTailCallOptimization function
5039      // must correctly identify tail call optimizable calls.
5040      if (!isMarkedTailCall) continue;
5041      if (Ret==NULL ||
5042          !TLI.IsEligibleForTailCallOptimization(OpCall, OpRet, DAG)) {
5043        // Not eligible. Mark CALL node as non tail call.
5044        SmallVector<SDOperand, 32> Ops;
5045        unsigned idx=0;
5046        for(SDNode::op_iterator I =OpCall.Val->op_begin(),
5047              E = OpCall.Val->op_end(); I != E; I++, idx++) {
5048          if (idx!=3)
5049            Ops.push_back(*I);
5050          else
5051            Ops.push_back(DAG.getConstant(false, TLI.getPointerTy()));
5052        }
5053        DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5054      } else {
5055        // Look for tail call clobbered arguments. Emit a series of
5056        // copyto/copyfrom virtual register nodes to protect them.
5057        SmallVector<SDOperand, 32> Ops;
5058        SDOperand Chain = OpCall.getOperand(0), InFlag;
5059        unsigned idx=0;
5060        for(SDNode::op_iterator I = OpCall.Val->op_begin(),
5061              E = OpCall.Val->op_end(); I != E; I++, idx++) {
5062          SDOperand Arg = *I;
5063          if (idx > 4 && (idx % 2)) {
5064            bool isByVal = cast<ARG_FLAGSSDNode>(OpCall.getOperand(idx+1))->
5065              getArgFlags().isByVal();
5066            MachineFunction &MF = DAG.getMachineFunction();
5067            MachineFrameInfo *MFI = MF.getFrameInfo();
5068            if (!isByVal &&
5069                IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
5070              MVT VT = Arg.getValueType();
5071              unsigned VReg = MF.getRegInfo().
5072                createVirtualRegister(TLI.getRegClassFor(VT));
5073              Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
5074              InFlag = Chain.getValue(1);
5075              Arg = DAG.getCopyFromReg(Chain, VReg, VT, InFlag);
5076              Chain = Arg.getValue(1);
5077              InFlag = Arg.getValue(2);
5078            }
5079          }
5080          Ops.push_back(Arg);
5081        }
5082        // Link in chain of CopyTo/CopyFromReg.
5083        Ops[0] = Chain;
5084        DAG.UpdateNodeOperands(OpCall, Ops.begin(), Ops.size());
5085      }
5086    }
5087  }
5088}
5089
5090void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
5091       std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
5092                                         FunctionLoweringInfo &FuncInfo) {
5093  SelectionDAGLowering SDL(DAG, TLI, *AA, FuncInfo, GCI);
5094
5095  // Lower any arguments needed in this block if this is the entry block.
5096  if (LLVMBB == &LLVMBB->getParent()->getEntryBlock())
5097    LowerArguments(LLVMBB, SDL);
5098
5099  BB = FuncInfo.MBBMap[LLVMBB];
5100  SDL.setCurrentBasicBlock(BB);
5101
5102  MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
5103
5104  if (MMI && BB->isLandingPad()) {
5105    // Add a label to mark the beginning of the landing pad.  Deletion of the
5106    // landing pad can thus be detected via the MachineModuleInfo.
5107    unsigned LabelID = MMI->addLandingPad(BB);
5108    DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, DAG.getEntryNode(), LabelID));
5109
5110    // Mark exception register as live in.
5111    unsigned Reg = TLI.getExceptionAddressRegister();
5112    if (Reg) BB->addLiveIn(Reg);
5113
5114    // Mark exception selector register as live in.
5115    Reg = TLI.getExceptionSelectorRegister();
5116    if (Reg) BB->addLiveIn(Reg);
5117
5118    // FIXME: Hack around an exception handling flaw (PR1508): the personality
5119    // function and list of typeids logically belong to the invoke (or, if you
5120    // like, the basic block containing the invoke), and need to be associated
5121    // with it in the dwarf exception handling tables.  Currently however the
5122    // information is provided by an intrinsic (eh.selector) that can be moved
5123    // to unexpected places by the optimizers: if the unwind edge is critical,
5124    // then breaking it can result in the intrinsics being in the successor of
5125    // the landing pad, not the landing pad itself.  This results in exceptions
5126    // not being caught because no typeids are associated with the invoke.
5127    // This may not be the only way things can go wrong, but it is the only way
5128    // we try to work around for the moment.
5129    BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
5130
5131    if (Br && Br->isUnconditional()) { // Critical edge?
5132      BasicBlock::iterator I, E;
5133      for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
5134        if (isSelector(I))
5135          break;
5136
5137      if (I == E)
5138        // No catch info found - try to extract some from the successor.
5139        copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, FuncInfo);
5140    }
5141  }
5142
5143  // Lower all of the non-terminator instructions.
5144  for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
5145       I != E; ++I)
5146    SDL.visit(*I);
5147
5148  // Ensure that all instructions which are used outside of their defining
5149  // blocks are available as virtual registers.  Invoke is handled elsewhere.
5150  for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
5151    if (!I->use_empty() && !isa<PHINode>(I) && !isa<InvokeInst>(I)) {
5152      DenseMap<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
5153      if (VMI != FuncInfo.ValueMap.end())
5154        SDL.CopyValueToVirtualRegister(I, VMI->second);
5155    }
5156
5157  // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
5158  // ensure constants are generated when needed.  Remember the virtual registers
5159  // that need to be added to the Machine PHI nodes as input.  We cannot just
5160  // directly add them, because expansion might result in multiple MBB's for one
5161  // BB.  As such, the start of the BB might correspond to a different MBB than
5162  // the end.
5163  //
5164  TerminatorInst *TI = LLVMBB->getTerminator();
5165
5166  // Emit constants only once even if used by multiple PHI nodes.
5167  std::map<Constant*, unsigned> ConstantsOut;
5168
5169  // Vector bool would be better, but vector<bool> is really slow.
5170  std::vector<unsigned char> SuccsHandled;
5171  if (TI->getNumSuccessors())
5172    SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
5173
5174  // Check successor nodes' PHI nodes that expect a constant to be available
5175  // from this block.
5176  for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5177    BasicBlock *SuccBB = TI->getSuccessor(succ);
5178    if (!isa<PHINode>(SuccBB->begin())) continue;
5179    MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
5180
5181    // If this terminator has multiple identical successors (common for
5182    // switches), only handle each succ once.
5183    unsigned SuccMBBNo = SuccMBB->getNumber();
5184    if (SuccsHandled[SuccMBBNo]) continue;
5185    SuccsHandled[SuccMBBNo] = true;
5186
5187    MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5188    PHINode *PN;
5189
5190    // At this point we know that there is a 1-1 correspondence between LLVM PHI
5191    // nodes and Machine PHI nodes, but the incoming operands have not been
5192    // emitted yet.
5193    for (BasicBlock::iterator I = SuccBB->begin();
5194         (PN = dyn_cast<PHINode>(I)); ++I) {
5195      // Ignore dead phi's.
5196      if (PN->use_empty()) continue;
5197
5198      unsigned Reg;
5199      Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5200
5201      if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5202        unsigned &RegOut = ConstantsOut[C];
5203        if (RegOut == 0) {
5204          RegOut = FuncInfo.CreateRegForValue(C);
5205          SDL.CopyValueToVirtualRegister(C, RegOut);
5206        }
5207        Reg = RegOut;
5208      } else {
5209        Reg = FuncInfo.ValueMap[PHIOp];
5210        if (Reg == 0) {
5211          assert(isa<AllocaInst>(PHIOp) &&
5212                 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5213                 "Didn't codegen value into a register!??");
5214          Reg = FuncInfo.CreateRegForValue(PHIOp);
5215          SDL.CopyValueToVirtualRegister(PHIOp, Reg);
5216        }
5217      }
5218
5219      // Remember that this register needs to added to the machine PHI node as
5220      // the input for this MBB.
5221      MVT VT = TLI.getValueType(PN->getType());
5222      unsigned NumRegisters = TLI.getNumRegisters(VT);
5223      for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5224        PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5225    }
5226  }
5227  ConstantsOut.clear();
5228
5229  // Lower the terminator after the copies are emitted.
5230  SDL.visit(*LLVMBB->getTerminator());
5231
5232  // Copy over any CaseBlock records that may now exist due to SwitchInst
5233  // lowering, as well as any jump table information.
5234  SwitchCases.clear();
5235  SwitchCases = SDL.SwitchCases;
5236  JTCases.clear();
5237  JTCases = SDL.JTCases;
5238  BitTestCases.clear();
5239  BitTestCases = SDL.BitTestCases;
5240
5241  // Make sure the root of the DAG is up-to-date.
5242  DAG.setRoot(SDL.getControlRoot());
5243
5244  // Check whether calls in this block are real tail calls. Fix up CALL nodes
5245  // with correct tailcall attribute so that the target can rely on the tailcall
5246  // attribute indicating whether the call is really eligible for tail call
5247  // optimization.
5248  CheckDAGForTailCallsAndFixThem(DAG, TLI);
5249}
5250
5251void SelectionDAGISel::ComputeLiveOutVRegInfo(SelectionDAG &DAG) {
5252  SmallPtrSet<SDNode*, 128> VisitedNodes;
5253  SmallVector<SDNode*, 128> Worklist;
5254
5255  Worklist.push_back(DAG.getRoot().Val);
5256
5257  APInt Mask;
5258  APInt KnownZero;
5259  APInt KnownOne;
5260
5261  while (!Worklist.empty()) {
5262    SDNode *N = Worklist.back();
5263    Worklist.pop_back();
5264
5265    // If we've already seen this node, ignore it.
5266    if (!VisitedNodes.insert(N))
5267      continue;
5268
5269    // Otherwise, add all chain operands to the worklist.
5270    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5271      if (N->getOperand(i).getValueType() == MVT::Other)
5272        Worklist.push_back(N->getOperand(i).Val);
5273
5274    // If this is a CopyToReg with a vreg dest, process it.
5275    if (N->getOpcode() != ISD::CopyToReg)
5276      continue;
5277
5278    unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
5279    if (!TargetRegisterInfo::isVirtualRegister(DestReg))
5280      continue;
5281
5282    // Ignore non-scalar or non-integer values.
5283    SDOperand Src = N->getOperand(2);
5284    MVT SrcVT = Src.getValueType();
5285    if (!SrcVT.isInteger() || SrcVT.isVector())
5286      continue;
5287
5288    unsigned NumSignBits = DAG.ComputeNumSignBits(Src);
5289    Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
5290    DAG.ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
5291
5292    // Only install this information if it tells us something.
5293    if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
5294      DestReg -= TargetRegisterInfo::FirstVirtualRegister;
5295      FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5296      if (DestReg >= FLI.LiveOutRegInfo.size())
5297        FLI.LiveOutRegInfo.resize(DestReg+1);
5298      FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[DestReg];
5299      LOI.NumSignBits = NumSignBits;
5300      LOI.KnownOne = NumSignBits;
5301      LOI.KnownZero = NumSignBits;
5302    }
5303  }
5304}
5305
5306void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
5307  DOUT << "Lowered selection DAG:\n";
5308  DEBUG(DAG.dump());
5309
5310  // Run the DAG combiner in pre-legalize mode.
5311  if (TimePassesIsEnabled) {
5312    NamedRegionTimer T("DAG Combining 1");
5313    DAG.Combine(false, *AA);
5314  } else {
5315    DAG.Combine(false, *AA);
5316  }
5317
5318  DOUT << "Optimized lowered selection DAG:\n";
5319  DEBUG(DAG.dump());
5320
5321  // Second step, hack on the DAG until it only uses operations and types that
5322  // the target supports.
5323#if 0  // Enable this some day.
5324  DAG.LegalizeTypes();
5325  // Someday even later, enable a dag combine pass here.
5326#endif
5327  if (TimePassesIsEnabled) {
5328    NamedRegionTimer T("DAG Legalization");
5329    DAG.Legalize();
5330  } else {
5331    DAG.Legalize();
5332  }
5333
5334  DOUT << "Legalized selection DAG:\n";
5335  DEBUG(DAG.dump());
5336
5337  // Run the DAG combiner in post-legalize mode.
5338  if (TimePassesIsEnabled) {
5339    NamedRegionTimer T("DAG Combining 2");
5340    DAG.Combine(true, *AA);
5341  } else {
5342    DAG.Combine(true, *AA);
5343  }
5344
5345  DOUT << "Optimized legalized selection DAG:\n";
5346  DEBUG(DAG.dump());
5347
5348  if (ViewISelDAGs) DAG.viewGraph();
5349
5350  if (EnableValueProp)  // FIXME: Only do this if !fast.
5351    ComputeLiveOutVRegInfo(DAG);
5352
5353  // Third, instruction select all of the operations to machine code, adding the
5354  // code to the MachineBasicBlock.
5355  if (TimePassesIsEnabled) {
5356    NamedRegionTimer T("Instruction Selection");
5357    InstructionSelect(DAG);
5358  } else {
5359    InstructionSelect(DAG);
5360  }
5361
5362  // Emit machine code to BB.  This can change 'BB' to the last block being
5363  // inserted into.
5364  if (TimePassesIsEnabled) {
5365    NamedRegionTimer T("Instruction Scheduling");
5366    ScheduleAndEmitDAG(DAG);
5367  } else {
5368    ScheduleAndEmitDAG(DAG);
5369  }
5370
5371  // Perform target specific isel post processing.
5372  if (TimePassesIsEnabled) {
5373    NamedRegionTimer T("Instruction Selection Post Processing");
5374    InstructionSelectPostProcessing(DAG);
5375  } else {
5376    InstructionSelectPostProcessing(DAG);
5377  }
5378
5379  DOUT << "Selected machine code:\n";
5380  DEBUG(BB->dump());
5381}
5382
5383void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
5384                                        FunctionLoweringInfo &FuncInfo) {
5385  std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
5386  {
5387    SelectionDAG DAG(TLI, MF, FuncInfo,
5388                     getAnalysisToUpdate<MachineModuleInfo>());
5389    CurDAG = &DAG;
5390
5391    // First step, lower LLVM code to some DAG.  This DAG may use operations and
5392    // types that are not supported by the target.
5393    BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
5394
5395    // Second step, emit the lowered DAG as machine code.
5396    CodeGenAndEmitDAG(DAG);
5397  }
5398
5399  DOUT << "Total amount of phi nodes to update: "
5400       << PHINodesToUpdate.size() << "\n";
5401  DEBUG(for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i)
5402          DOUT << "Node " << i << " : (" << PHINodesToUpdate[i].first
5403               << ", " << PHINodesToUpdate[i].second << ")\n";);
5404
5405  // Next, now that we know what the last MBB the LLVM BB expanded is, update
5406  // PHI nodes in successors.
5407  if (SwitchCases.empty() && JTCases.empty() && BitTestCases.empty()) {
5408    for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5409      MachineInstr *PHI = PHINodesToUpdate[i].first;
5410      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5411             "This is not a machine PHI node that we are updating!");
5412      PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5413                                                false));
5414      PHI->addOperand(MachineOperand::CreateMBB(BB));
5415    }
5416    return;
5417  }
5418
5419  for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i) {
5420    // Lower header first, if it wasn't already lowered
5421    if (!BitTestCases[i].Emitted) {
5422      SelectionDAG HSDAG(TLI, MF, FuncInfo,
5423                         getAnalysisToUpdate<MachineModuleInfo>());
5424      CurDAG = &HSDAG;
5425      SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5426      // Set the current basic block to the mbb we wish to insert the code into
5427      BB = BitTestCases[i].Parent;
5428      HSDL.setCurrentBasicBlock(BB);
5429      // Emit the code
5430      HSDL.visitBitTestHeader(BitTestCases[i]);
5431      HSDAG.setRoot(HSDL.getRoot());
5432      CodeGenAndEmitDAG(HSDAG);
5433    }
5434
5435    for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5436      SelectionDAG BSDAG(TLI, MF, FuncInfo,
5437                         getAnalysisToUpdate<MachineModuleInfo>());
5438      CurDAG = &BSDAG;
5439      SelectionDAGLowering BSDL(BSDAG, TLI, *AA, FuncInfo, GCI);
5440      // Set the current basic block to the mbb we wish to insert the code into
5441      BB = BitTestCases[i].Cases[j].ThisBB;
5442      BSDL.setCurrentBasicBlock(BB);
5443      // Emit the code
5444      if (j+1 != ej)
5445        BSDL.visitBitTestCase(BitTestCases[i].Cases[j+1].ThisBB,
5446                              BitTestCases[i].Reg,
5447                              BitTestCases[i].Cases[j]);
5448      else
5449        BSDL.visitBitTestCase(BitTestCases[i].Default,
5450                              BitTestCases[i].Reg,
5451                              BitTestCases[i].Cases[j]);
5452
5453
5454      BSDAG.setRoot(BSDL.getRoot());
5455      CodeGenAndEmitDAG(BSDAG);
5456    }
5457
5458    // Update PHI Nodes
5459    for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5460      MachineInstr *PHI = PHINodesToUpdate[pi].first;
5461      MachineBasicBlock *PHIBB = PHI->getParent();
5462      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5463             "This is not a machine PHI node that we are updating!");
5464      // This is "default" BB. We have two jumps to it. From "header" BB and
5465      // from last "case" BB.
5466      if (PHIBB == BitTestCases[i].Default) {
5467        PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5468                                                  false));
5469        PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Parent));
5470        PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5471                                                  false));
5472        PHI->addOperand(MachineOperand::CreateMBB(BitTestCases[i].Cases.
5473                                                  back().ThisBB));
5474      }
5475      // One of "cases" BB.
5476      for (unsigned j = 0, ej = BitTestCases[i].Cases.size(); j != ej; ++j) {
5477        MachineBasicBlock* cBB = BitTestCases[i].Cases[j].ThisBB;
5478        if (cBB->succ_end() !=
5479            std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
5480          PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5481                                                    false));
5482          PHI->addOperand(MachineOperand::CreateMBB(cBB));
5483        }
5484      }
5485    }
5486  }
5487
5488  // If the JumpTable record is filled in, then we need to emit a jump table.
5489  // Updating the PHI nodes is tricky in this case, since we need to determine
5490  // whether the PHI is a successor of the range check MBB or the jump table MBB
5491  for (unsigned i = 0, e = JTCases.size(); i != e; ++i) {
5492    // Lower header first, if it wasn't already lowered
5493    if (!JTCases[i].first.Emitted) {
5494      SelectionDAG HSDAG(TLI, MF, FuncInfo,
5495                         getAnalysisToUpdate<MachineModuleInfo>());
5496      CurDAG = &HSDAG;
5497      SelectionDAGLowering HSDL(HSDAG, TLI, *AA, FuncInfo, GCI);
5498      // Set the current basic block to the mbb we wish to insert the code into
5499      BB = JTCases[i].first.HeaderBB;
5500      HSDL.setCurrentBasicBlock(BB);
5501      // Emit the code
5502      HSDL.visitJumpTableHeader(JTCases[i].second, JTCases[i].first);
5503      HSDAG.setRoot(HSDL.getRoot());
5504      CodeGenAndEmitDAG(HSDAG);
5505    }
5506
5507    SelectionDAG JSDAG(TLI, MF, FuncInfo,
5508                       getAnalysisToUpdate<MachineModuleInfo>());
5509    CurDAG = &JSDAG;
5510    SelectionDAGLowering JSDL(JSDAG, TLI, *AA, FuncInfo, GCI);
5511    // Set the current basic block to the mbb we wish to insert the code into
5512    BB = JTCases[i].second.MBB;
5513    JSDL.setCurrentBasicBlock(BB);
5514    // Emit the code
5515    JSDL.visitJumpTable(JTCases[i].second);
5516    JSDAG.setRoot(JSDL.getRoot());
5517    CodeGenAndEmitDAG(JSDAG);
5518
5519    // Update PHI Nodes
5520    for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
5521      MachineInstr *PHI = PHINodesToUpdate[pi].first;
5522      MachineBasicBlock *PHIBB = PHI->getParent();
5523      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5524             "This is not a machine PHI node that we are updating!");
5525      // "default" BB. We can go there only from header BB.
5526      if (PHIBB == JTCases[i].second.Default) {
5527        PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5528                                                  false));
5529        PHI->addOperand(MachineOperand::CreateMBB(JTCases[i].first.HeaderBB));
5530      }
5531      // JT BB. Just iterate over successors here
5532      if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
5533        PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pi].second,
5534                                                  false));
5535        PHI->addOperand(MachineOperand::CreateMBB(BB));
5536      }
5537    }
5538  }
5539
5540  // If the switch block involved a branch to one of the actual successors, we
5541  // need to update PHI nodes in that block.
5542  for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
5543    MachineInstr *PHI = PHINodesToUpdate[i].first;
5544    assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
5545           "This is not a machine PHI node that we are updating!");
5546    if (BB->isSuccessor(PHI->getParent())) {
5547      PHI->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[i].second,
5548                                                false));
5549      PHI->addOperand(MachineOperand::CreateMBB(BB));
5550    }
5551  }
5552
5553  // If we generated any switch lowering information, build and codegen any
5554  // additional DAGs necessary.
5555  for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
5556    SelectionDAG SDAG(TLI, MF, FuncInfo,
5557                      getAnalysisToUpdate<MachineModuleInfo>());
5558    CurDAG = &SDAG;
5559    SelectionDAGLowering SDL(SDAG, TLI, *AA, FuncInfo, GCI);
5560
5561    // Set the current basic block to the mbb we wish to insert the code into
5562    BB = SwitchCases[i].ThisBB;
5563    SDL.setCurrentBasicBlock(BB);
5564
5565    // Emit the code
5566    SDL.visitSwitchCase(SwitchCases[i]);
5567    SDAG.setRoot(SDL.getRoot());
5568    CodeGenAndEmitDAG(SDAG);
5569
5570    // Handle any PHI nodes in successors of this chunk, as if we were coming
5571    // from the original BB before switch expansion.  Note that PHI nodes can
5572    // occur multiple times in PHINodesToUpdate.  We have to be very careful to
5573    // handle them the right number of times.
5574    while ((BB = SwitchCases[i].TrueBB)) {  // Handle LHS and RHS.
5575      for (MachineBasicBlock::iterator Phi = BB->begin();
5576           Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
5577        // This value for this PHI node is recorded in PHINodesToUpdate, get it.
5578        for (unsigned pn = 0; ; ++pn) {
5579          assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
5580          if (PHINodesToUpdate[pn].first == Phi) {
5581            Phi->addOperand(MachineOperand::CreateReg(PHINodesToUpdate[pn].
5582                                                      second, false));
5583            Phi->addOperand(MachineOperand::CreateMBB(SwitchCases[i].ThisBB));
5584            break;
5585          }
5586        }
5587      }
5588
5589      // Don't process RHS if same block as LHS.
5590      if (BB == SwitchCases[i].FalseBB)
5591        SwitchCases[i].FalseBB = 0;
5592
5593      // If we haven't handled the RHS, do so now.  Otherwise, we're done.
5594      SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
5595      SwitchCases[i].FalseBB = 0;
5596    }
5597    assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
5598  }
5599}
5600
5601
5602//===----------------------------------------------------------------------===//
5603/// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
5604/// target node in the graph.
5605void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
5606  if (ViewSchedDAGs) DAG.viewGraph();
5607
5608  RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
5609
5610  if (!Ctor) {
5611    Ctor = ISHeuristic;
5612    RegisterScheduler::setDefault(Ctor);
5613  }
5614
5615  ScheduleDAG *SL = Ctor(this, &DAG, BB, FastISel);
5616  BB = SL->Run();
5617
5618  if (ViewSUnitDAGs) SL->viewGraph();
5619
5620  delete SL;
5621}
5622
5623
5624HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
5625  return new HazardRecognizer();
5626}
5627
5628//===----------------------------------------------------------------------===//
5629// Helper functions used by the generated instruction selector.
5630//===----------------------------------------------------------------------===//
5631// Calls to these methods are generated by tblgen.
5632
5633/// CheckAndMask - The isel is trying to match something like (and X, 255).  If
5634/// the dag combiner simplified the 255, we still want to match.  RHS is the
5635/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
5636/// specified in the .td file (e.g. 255).
5637bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS,
5638                                    int64_t DesiredMaskS) const {
5639  const APInt &ActualMask = RHS->getAPIntValue();
5640  const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5641
5642  // If the actual mask exactly matches, success!
5643  if (ActualMask == DesiredMask)
5644    return true;
5645
5646  // If the actual AND mask is allowing unallowed bits, this doesn't match.
5647  if (ActualMask.intersects(~DesiredMask))
5648    return false;
5649
5650  // Otherwise, the DAG Combiner may have proven that the value coming in is
5651  // either already zero or is not demanded.  Check for known zero input bits.
5652  APInt NeededMask = DesiredMask & ~ActualMask;
5653  if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
5654    return true;
5655
5656  // TODO: check to see if missing bits are just not demanded.
5657
5658  // Otherwise, this pattern doesn't match.
5659  return false;
5660}
5661
5662/// CheckOrMask - The isel is trying to match something like (or X, 255).  If
5663/// the dag combiner simplified the 255, we still want to match.  RHS is the
5664/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
5665/// specified in the .td file (e.g. 255).
5666bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS,
5667                                   int64_t DesiredMaskS) const {
5668  const APInt &ActualMask = RHS->getAPIntValue();
5669  const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
5670
5671  // If the actual mask exactly matches, success!
5672  if (ActualMask == DesiredMask)
5673    return true;
5674
5675  // If the actual AND mask is allowing unallowed bits, this doesn't match.
5676  if (ActualMask.intersects(~DesiredMask))
5677    return false;
5678
5679  // Otherwise, the DAG Combiner may have proven that the value coming in is
5680  // either already zero or is not demanded.  Check for known zero input bits.
5681  APInt NeededMask = DesiredMask & ~ActualMask;
5682
5683  APInt KnownZero, KnownOne;
5684  CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
5685
5686  // If all the missing bits in the or are already known to be set, match!
5687  if ((NeededMask & KnownOne) == NeededMask)
5688    return true;
5689
5690  // TODO: check to see if missing bits are just not demanded.
5691
5692  // Otherwise, this pattern doesn't match.
5693  return false;
5694}
5695
5696
5697/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
5698/// by tblgen.  Others should not call it.
5699void SelectionDAGISel::
5700SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
5701  std::vector<SDOperand> InOps;
5702  std::swap(InOps, Ops);
5703
5704  Ops.push_back(InOps[0]);  // input chain.
5705  Ops.push_back(InOps[1]);  // input asm string.
5706
5707  unsigned i = 2, e = InOps.size();
5708  if (InOps[e-1].getValueType() == MVT::Flag)
5709    --e;  // Don't process a flag operand if it is here.
5710
5711  while (i != e) {
5712    unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
5713    if ((Flags & 7) != 4 /*MEM*/) {
5714      // Just skip over this operand, copying the operands verbatim.
5715      Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
5716      i += (Flags >> 3) + 1;
5717    } else {
5718      assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
5719      // Otherwise, this is a memory operand.  Ask the target to select it.
5720      std::vector<SDOperand> SelOps;
5721      if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
5722        cerr << "Could not match memory address.  Inline asm failure!\n";
5723        exit(1);
5724      }
5725
5726      // Add this to the output node.
5727      MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
5728      Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
5729                                          IntPtrTy));
5730      Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
5731      i += 2;
5732    }
5733  }
5734
5735  // Add the flag input back if present.
5736  if (e != InOps.size())
5737    Ops.push_back(InOps.back());
5738}
5739
5740char SelectionDAGISel::ID = 0;
5741