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