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