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