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