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