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