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