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