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