3b5ef32e3c34f856566a8167ad24cb09e63a5ece
[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/CallingConv.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Intrinsics.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/SelectionDAG.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/MRegisterInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetFrameInfo.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetLowering.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include <map>
37 #include <iostream>
38 using namespace llvm;
39
40 #ifndef NDEBUG
41 static cl::opt<bool>
42 ViewDAGs("view-isel-dags", cl::Hidden,
43          cl::desc("Pop up a window to show isel dags as they are selected"));
44 #else
45 static const bool ViewDAGs = 0;
46 #endif
47
48
49 namespace llvm {
50   //===--------------------------------------------------------------------===//
51   /// FunctionLoweringInfo - This contains information that is global to a
52   /// function that is used when lowering a region of the function.
53   class FunctionLoweringInfo {
54   public:
55     TargetLowering &TLI;
56     Function &Fn;
57     MachineFunction &MF;
58     SSARegMap *RegMap;
59
60     FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
61
62     /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
63     std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
64
65     /// ValueMap - Since we emit code for the function a basic block at a time,
66     /// we must remember which virtual registers hold the values for
67     /// cross-basic-block values.
68     std::map<const Value*, unsigned> ValueMap;
69
70     /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
71     /// the entry block.  This allows the allocas to be efficiently referenced
72     /// anywhere in the function.
73     std::map<const AllocaInst*, int> StaticAllocaMap;
74
75     unsigned MakeReg(MVT::ValueType VT) {
76       return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
77     }
78
79     unsigned CreateRegForValue(const Value *V) {
80       MVT::ValueType VT = TLI.getValueType(V->getType());
81       // The common case is that we will only create one register for this
82       // value.  If we have that case, create and return the virtual register.
83       unsigned NV = TLI.getNumElements(VT);
84       if (NV == 1) {
85         // If we are promoting this value, pick the next largest supported type.
86         return MakeReg(TLI.getTypeToTransformTo(VT));
87       }
88
89       // If this value is represented with multiple target registers, make sure
90       // to create enough consequtive registers of the right (smaller) type.
91       unsigned NT = VT-1;  // Find the type to use.
92       while (TLI.getNumElements((MVT::ValueType)NT) != 1)
93         --NT;
94
95       unsigned R = MakeReg((MVT::ValueType)NT);
96       for (unsigned i = 1; i != NV; ++i)
97         MakeReg((MVT::ValueType)NT);
98       return R;
99     }
100
101     unsigned InitializeRegForValue(const Value *V) {
102       unsigned &R = ValueMap[V];
103       assert(R == 0 && "Already initialized this value register!");
104       return R = CreateRegForValue(V);
105     }
106   };
107 }
108
109 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
110 /// PHI nodes or outside of the basic block that defines it.
111 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
112   if (isa<PHINode>(I)) return true;
113   BasicBlock *BB = I->getParent();
114   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
115     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
116       return true;
117   return false;
118 }
119
120 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
121 /// entry block, return true.
122 static bool isOnlyUsedInEntryBlock(Argument *A) {
123   BasicBlock *Entry = A->getParent()->begin();
124   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
125     if (cast<Instruction>(*UI)->getParent() != Entry)
126       return false;  // Use not in entry block.
127   return true;
128 }
129
130 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
131                                            Function &fn, MachineFunction &mf)
132     : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
133
134   // Create a vreg for each argument register that is not dead and is used
135   // outside of the entry block for the function.
136   for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
137        AI != E; ++AI)
138     if (!isOnlyUsedInEntryBlock(AI))
139       InitializeRegForValue(AI);
140
141   // Initialize the mapping of values to registers.  This is only set up for
142   // instruction values that are used outside of the block that defines
143   // them.
144   Function::iterator BB = Fn.begin(), EB = Fn.end();
145   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
146     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
147       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
148         const Type *Ty = AI->getAllocatedType();
149         uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
150         unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
151
152         // If the alignment of the value is smaller than the size of the value,
153         // and if the size of the value is particularly small (<= 8 bytes),
154         // round up to the size of the value for potentially better performance.
155         //
156         // FIXME: This could be made better with a preferred alignment hook in
157         // TargetData.  It serves primarily to 8-byte align doubles for X86.
158         if (Align < TySize && TySize <= 8) Align = TySize;
159         TySize *= CUI->getValue();   // Get total allocated size.
160         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
161         StaticAllocaMap[AI] =
162           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
163       }
164
165   for (; BB != EB; ++BB)
166     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
167       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
168         if (!isa<AllocaInst>(I) ||
169             !StaticAllocaMap.count(cast<AllocaInst>(I)))
170           InitializeRegForValue(I);
171
172   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
173   // also creates the initial PHI MachineInstrs, though none of the input
174   // operands are populated.
175   for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
176     MachineBasicBlock *MBB = new MachineBasicBlock(BB);
177     MBBMap[BB] = MBB;
178     MF.getBasicBlockList().push_back(MBB);
179
180     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
181     // appropriate.
182     PHINode *PN;
183     for (BasicBlock::iterator I = BB->begin();
184          (PN = dyn_cast<PHINode>(I)); ++I)
185       if (!PN->use_empty()) {
186         unsigned NumElements =
187           TLI.getNumElements(TLI.getValueType(PN->getType()));
188         unsigned PHIReg = ValueMap[PN];
189         assert(PHIReg &&"PHI node does not have an assigned virtual register!");
190         for (unsigned i = 0; i != NumElements; ++i)
191           BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
192       }
193   }
194 }
195
196
197
198 //===----------------------------------------------------------------------===//
199 /// SelectionDAGLowering - This is the common target-independent lowering
200 /// implementation that is parameterized by a TargetLowering object.
201 /// Also, targets can overload any lowering method.
202 ///
203 namespace llvm {
204 class SelectionDAGLowering {
205   MachineBasicBlock *CurMBB;
206
207   std::map<const Value*, SDOperand> NodeMap;
208
209   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
210   /// them up and then emit token factor nodes when possible.  This allows us to
211   /// get simple disambiguation between loads without worrying about alias
212   /// analysis.
213   std::vector<SDOperand> PendingLoads;
214
215 public:
216   // TLI - This is information that describes the available target features we
217   // need for lowering.  This indicates when operations are unavailable,
218   // implemented with a libcall, etc.
219   TargetLowering &TLI;
220   SelectionDAG &DAG;
221   const TargetData &TD;
222
223   /// FuncInfo - Information about the function as a whole.
224   ///
225   FunctionLoweringInfo &FuncInfo;
226
227   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
228                        FunctionLoweringInfo &funcinfo)
229     : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
230       FuncInfo(funcinfo) {
231   }
232
233   /// getRoot - Return the current virtual root of the Selection DAG.
234   ///
235   SDOperand getRoot() {
236     if (PendingLoads.empty())
237       return DAG.getRoot();
238
239     if (PendingLoads.size() == 1) {
240       SDOperand Root = PendingLoads[0];
241       DAG.setRoot(Root);
242       PendingLoads.clear();
243       return Root;
244     }
245
246     // Otherwise, we have to make a token factor node.
247     SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
248     PendingLoads.clear();
249     DAG.setRoot(Root);
250     return Root;
251   }
252
253   void visit(Instruction &I) { visit(I.getOpcode(), I); }
254
255   void visit(unsigned Opcode, User &I) {
256     switch (Opcode) {
257     default: assert(0 && "Unknown instruction type encountered!");
258              abort();
259       // Build the switch statement using the Instruction.def file.
260 #define HANDLE_INST(NUM, OPCODE, CLASS) \
261     case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
262 #include "llvm/Instruction.def"
263     }
264   }
265
266   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
267
268
269   SDOperand getIntPtrConstant(uint64_t Val) {
270     return DAG.getConstant(Val, TLI.getPointerTy());
271   }
272
273   SDOperand getValue(const Value *V) {
274     SDOperand &N = NodeMap[V];
275     if (N.Val) return N;
276
277     MVT::ValueType VT = TLI.getValueType(V->getType());
278     if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
279       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
280         visit(CE->getOpcode(), *CE);
281         assert(N.Val && "visit didn't populate the ValueMap!");
282         return N;
283       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
284         return N = DAG.getGlobalAddress(GV, VT);
285       } else if (isa<ConstantPointerNull>(C)) {
286         return N = DAG.getConstant(0, TLI.getPointerTy());
287       } else if (isa<UndefValue>(C)) {
288         return N = DAG.getNode(ISD::UNDEF, VT);
289       } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
290         return N = DAG.getConstantFP(CFP->getValue(), VT);
291       } else {
292         // Canonicalize all constant ints to be unsigned.
293         return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
294       }
295
296     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
297       std::map<const AllocaInst*, int>::iterator SI =
298         FuncInfo.StaticAllocaMap.find(AI);
299       if (SI != FuncInfo.StaticAllocaMap.end())
300         return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
301     }
302
303     std::map<const Value*, unsigned>::const_iterator VMI =
304       FuncInfo.ValueMap.find(V);
305     assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
306
307     unsigned InReg = VMI->second;
308    
309     // If this type is not legal, make it so now.
310     MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
311     
312     N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
313     if (DestVT < VT) {
314       // Source must be expanded.  This input value is actually coming from the
315       // register pair VMI->second and VMI->second+1.
316       N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
317                       DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
318     } else {
319       if (DestVT > VT) { // Promotion case
320         if (MVT::isFloatingPoint(VT))
321           N = DAG.getNode(ISD::FP_ROUND, VT, N);
322         else
323           N = DAG.getNode(ISD::TRUNCATE, VT, N);
324       }
325     }
326     
327     return N;
328   }
329
330   const SDOperand &setValue(const Value *V, SDOperand NewN) {
331     SDOperand &N = NodeMap[V];
332     assert(N.Val == 0 && "Already set a value for this node!");
333     return N = NewN;
334   }
335
336   // Terminator instructions.
337   void visitRet(ReturnInst &I);
338   void visitBr(BranchInst &I);
339   void visitUnreachable(UnreachableInst &I) { /* noop */ }
340
341   // These all get lowered before this pass.
342   void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
343   void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
344   void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
345
346   //
347   void visitBinary(User &I, unsigned Opcode, bool isShift = false);
348   void visitAdd(User &I) {
349     visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FADD : ISD::ADD);
350   }
351   void visitSub(User &I);
352   void visitMul(User &I) {
353     visitBinary(I, I.getType()->isFloatingPoint() ? ISD::FMUL : ISD::MUL);
354   }
355   void visitDiv(User &I) {
356     unsigned Opc;
357     const Type *Ty = I.getType();
358     if (Ty->isFloatingPoint())
359       Opc = ISD::FDIV;
360     else if (Ty->isUnsigned())
361       Opc = ISD::UDIV;
362     else
363       Opc = ISD::SDIV;
364     visitBinary(I, Opc);
365   }
366   void visitRem(User &I) {
367     unsigned Opc;
368     const Type *Ty = I.getType();
369     if (Ty->isFloatingPoint())
370       Opc = ISD::FREM;
371     else if (Ty->isUnsigned())
372       Opc = ISD::UREM;
373     else
374       Opc = ISD::SREM;
375     visitBinary(I, Opc);
376   }
377   void visitAnd(User &I) { visitBinary(I, ISD::AND); }
378   void visitOr (User &I) { visitBinary(I, ISD::OR); }
379   void visitXor(User &I) { visitBinary(I, ISD::XOR); }
380   void visitShl(User &I) { visitBinary(I, ISD::SHL, true); }
381   void visitShr(User &I) {
382     visitBinary(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA, true);
383   }
384
385   void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
386   void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
387   void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
388   void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
389   void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
390   void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
391   void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
392
393   void visitGetElementPtr(User &I);
394   void visitCast(User &I);
395   void visitSelect(User &I);
396   //
397
398   void visitMalloc(MallocInst &I);
399   void visitFree(FreeInst &I);
400   void visitAlloca(AllocaInst &I);
401   void visitLoad(LoadInst &I);
402   void visitStore(StoreInst &I);
403   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
404   void visitCall(CallInst &I);
405
406   void visitVAStart(CallInst &I);
407   void visitVAArg(VAArgInst &I);
408   void visitVAEnd(CallInst &I);
409   void visitVACopy(CallInst &I);
410   void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
411
412   void visitMemIntrinsic(CallInst &I, unsigned Op);
413
414   void visitUserOp1(Instruction &I) {
415     assert(0 && "UserOp1 should not exist at instruction selection time!");
416     abort();
417   }
418   void visitUserOp2(Instruction &I) {
419     assert(0 && "UserOp2 should not exist at instruction selection time!");
420     abort();
421   }
422 };
423 } // end namespace llvm
424
425 void SelectionDAGLowering::visitRet(ReturnInst &I) {
426   if (I.getNumOperands() == 0) {
427     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
428     return;
429   }
430
431   SDOperand Op1 = getValue(I.getOperand(0));
432   MVT::ValueType TmpVT;
433
434   switch (Op1.getValueType()) {
435   default: assert(0 && "Unknown value type!");
436   case MVT::i1:
437   case MVT::i8:
438   case MVT::i16:
439   case MVT::i32:
440     // If this is a machine where 32-bits is legal or expanded, promote to
441     // 32-bits, otherwise, promote to 64-bits.
442     if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
443       TmpVT = TLI.getTypeToTransformTo(MVT::i32);
444     else
445       TmpVT = MVT::i32;
446
447     // Extend integer types to result type.
448     if (I.getOperand(0)->getType()->isSigned())
449       Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
450     else
451       Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
452     break;
453   case MVT::f32:
454   case MVT::i64:
455   case MVT::f64:
456     break; // No extension needed!
457   }
458   // Allow targets to lower this further to meet ABI requirements
459   DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
460 }
461
462 void SelectionDAGLowering::visitBr(BranchInst &I) {
463   // Update machine-CFG edges.
464   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
465
466   // Figure out which block is immediately after the current one.
467   MachineBasicBlock *NextBlock = 0;
468   MachineFunction::iterator BBI = CurMBB;
469   if (++BBI != CurMBB->getParent()->end())
470     NextBlock = BBI;
471
472   if (I.isUnconditional()) {
473     // If this is not a fall-through branch, emit the branch.
474     if (Succ0MBB != NextBlock)
475       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
476                               DAG.getBasicBlock(Succ0MBB)));
477   } else {
478     MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
479
480     SDOperand Cond = getValue(I.getCondition());
481     if (Succ1MBB == NextBlock) {
482       // If the condition is false, fall through.  This means we should branch
483       // if the condition is true to Succ #0.
484       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
485                               Cond, DAG.getBasicBlock(Succ0MBB)));
486     } else if (Succ0MBB == NextBlock) {
487       // If the condition is true, fall through.  This means we should branch if
488       // the condition is false to Succ #1.  Invert the condition first.
489       SDOperand True = DAG.getConstant(1, Cond.getValueType());
490       Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
491       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
492                               Cond, DAG.getBasicBlock(Succ1MBB)));
493     } else {
494       std::vector<SDOperand> Ops;
495       Ops.push_back(getRoot());
496       Ops.push_back(Cond);
497       Ops.push_back(DAG.getBasicBlock(Succ0MBB));
498       Ops.push_back(DAG.getBasicBlock(Succ1MBB));
499       DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
500     }
501   }
502 }
503
504 void SelectionDAGLowering::visitSub(User &I) {
505   // -0.0 - X --> fneg
506   if (I.getType()->isFloatingPoint()) {
507     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
508       if (CFP->isExactlyValue(-0.0)) {
509         SDOperand Op2 = getValue(I.getOperand(1));
510         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
511         return;
512       }
513     visitBinary(I, ISD::FSUB);
514   } else {
515     visitBinary(I, ISD::SUB);
516   }
517 }
518
519 void SelectionDAGLowering::visitBinary(User &I, unsigned Opcode, bool isShift) {
520   SDOperand Op1 = getValue(I.getOperand(0));
521   SDOperand Op2 = getValue(I.getOperand(1));
522
523   if (isShift)
524     Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
525
526   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
527 }
528
529 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
530                                       ISD::CondCode UnsignedOpcode) {
531   SDOperand Op1 = getValue(I.getOperand(0));
532   SDOperand Op2 = getValue(I.getOperand(1));
533   ISD::CondCode Opcode = SignedOpcode;
534   if (I.getOperand(0)->getType()->isUnsigned())
535     Opcode = UnsignedOpcode;
536   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
537 }
538
539 void SelectionDAGLowering::visitSelect(User &I) {
540   SDOperand Cond     = getValue(I.getOperand(0));
541   SDOperand TrueVal  = getValue(I.getOperand(1));
542   SDOperand FalseVal = getValue(I.getOperand(2));
543   setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
544                            TrueVal, FalseVal));
545 }
546
547 void SelectionDAGLowering::visitCast(User &I) {
548   SDOperand N = getValue(I.getOperand(0));
549   MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
550   MVT::ValueType DestTy = TLI.getValueType(I.getType());
551
552   if (N.getValueType() == DestTy) {
553     setValue(&I, N);  // noop cast.
554   } else if (DestTy == MVT::i1) {
555     // Cast to bool is a comparison against zero, not truncation to zero.
556     SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
557                                        DAG.getConstantFP(0.0, N.getValueType());
558     setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
559   } else if (isInteger(SrcTy)) {
560     if (isInteger(DestTy)) {        // Int -> Int cast
561       if (DestTy < SrcTy)   // Truncating cast?
562         setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
563       else if (I.getOperand(0)->getType()->isSigned())
564         setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
565       else
566         setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
567     } else {                        // Int -> FP cast
568       if (I.getOperand(0)->getType()->isSigned())
569         setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
570       else
571         setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
572     }
573   } else {
574     assert(isFloatingPoint(SrcTy) && "Unknown value type!");
575     if (isFloatingPoint(DestTy)) {  // FP -> FP cast
576       if (DestTy < SrcTy)   // Rounding cast?
577         setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
578       else
579         setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
580     } else {                        // FP -> Int cast.
581       if (I.getType()->isSigned())
582         setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
583       else
584         setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
585     }
586   }
587 }
588
589 void SelectionDAGLowering::visitGetElementPtr(User &I) {
590   SDOperand N = getValue(I.getOperand(0));
591   const Type *Ty = I.getOperand(0)->getType();
592   const Type *UIntPtrTy = TD.getIntPtrType();
593
594   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
595        OI != E; ++OI) {
596     Value *Idx = *OI;
597     if (const StructType *StTy = dyn_cast<StructType> (Ty)) {
598       unsigned Field = cast<ConstantUInt>(Idx)->getValue();
599       if (Field) {
600         // N = N + Offset
601         uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
602         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
603                         getIntPtrConstant(Offset));
604       }
605       Ty = StTy->getElementType(Field);
606     } else {
607       Ty = cast<SequentialType>(Ty)->getElementType();
608       if (!isa<Constant>(Idx) || !cast<Constant>(Idx)->isNullValue()) {
609         // N = N + Idx * ElementSize;
610         uint64_t ElementSize = TD.getTypeSize(Ty);
611         SDOperand IdxN = getValue(Idx), Scale = getIntPtrConstant(ElementSize);
612
613         // If the index is smaller or larger than intptr_t, truncate or extend
614         // it.
615         if (IdxN.getValueType() < Scale.getValueType()) {
616           if (Idx->getType()->isSigned())
617             IdxN = DAG.getNode(ISD::SIGN_EXTEND, Scale.getValueType(), IdxN);
618           else
619             IdxN = DAG.getNode(ISD::ZERO_EXTEND, Scale.getValueType(), IdxN);
620         } else if (IdxN.getValueType() > Scale.getValueType())
621           IdxN = DAG.getNode(ISD::TRUNCATE, Scale.getValueType(), IdxN);
622
623         IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
624         N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
625       }
626     }
627   }
628   setValue(&I, N);
629 }
630
631 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
632   // If this is a fixed sized alloca in the entry block of the function,
633   // allocate it statically on the stack.
634   if (FuncInfo.StaticAllocaMap.count(&I))
635     return;   // getValue will auto-populate this.
636
637   const Type *Ty = I.getAllocatedType();
638   uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
639   unsigned Align = TLI.getTargetData().getTypeAlignment(Ty);
640
641   SDOperand AllocSize = getValue(I.getArraySize());
642   MVT::ValueType IntPtr = TLI.getPointerTy();
643   if (IntPtr < AllocSize.getValueType())
644     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
645   else if (IntPtr > AllocSize.getValueType())
646     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
647
648   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
649                           getIntPtrConstant(TySize));
650
651   // Handle alignment.  If the requested alignment is less than or equal to the
652   // stack alignment, ignore it and round the size of the allocation up to the
653   // stack alignment size.  If the size is greater than the stack alignment, we
654   // note this in the DYNAMIC_STACKALLOC node.
655   unsigned StackAlign =
656     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
657   if (Align <= StackAlign) {
658     Align = 0;
659     // Add SA-1 to the size.
660     AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
661                             getIntPtrConstant(StackAlign-1));
662     // Mask out the low bits for alignment purposes.
663     AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
664                             getIntPtrConstant(~(uint64_t)(StackAlign-1)));
665   }
666
667   std::vector<MVT::ValueType> VTs;
668   VTs.push_back(AllocSize.getValueType());
669   VTs.push_back(MVT::Other);
670   std::vector<SDOperand> Ops;
671   Ops.push_back(getRoot());
672   Ops.push_back(AllocSize);
673   Ops.push_back(getIntPtrConstant(Align));
674   SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
675   DAG.setRoot(setValue(&I, DSA).getValue(1));
676
677   // Inform the Frame Information that we have just allocated a variable-sized
678   // object.
679   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
680 }
681
682
683 void SelectionDAGLowering::visitLoad(LoadInst &I) {
684   SDOperand Ptr = getValue(I.getOperand(0));
685
686   SDOperand Root;
687   if (I.isVolatile())
688     Root = getRoot();
689   else {
690     // Do not serialize non-volatile loads against each other.
691     Root = DAG.getRoot();
692   }
693
694   SDOperand L = DAG.getLoad(TLI.getValueType(I.getType()), Root, Ptr,
695                             DAG.getSrcValue(I.getOperand(0)));
696   setValue(&I, L);
697
698   if (I.isVolatile())
699     DAG.setRoot(L.getValue(1));
700   else
701     PendingLoads.push_back(L.getValue(1));
702 }
703
704
705 void SelectionDAGLowering::visitStore(StoreInst &I) {
706   Value *SrcV = I.getOperand(0);
707   SDOperand Src = getValue(SrcV);
708   SDOperand Ptr = getValue(I.getOperand(1));
709   DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
710                           DAG.getSrcValue(I.getOperand(1))));
711 }
712
713 void SelectionDAGLowering::visitCall(CallInst &I) {
714   const char *RenameFn = 0;
715   SDOperand Tmp;
716   if (Function *F = I.getCalledFunction())
717     if (F->isExternal())
718       switch (F->getIntrinsicID()) {
719       case 0:     // Not an LLVM intrinsic.
720         if (F->getName() == "fabs" || F->getName() == "fabsf") {
721           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
722               I.getOperand(1)->getType()->isFloatingPoint() &&
723               I.getType() == I.getOperand(1)->getType()) {
724             Tmp = getValue(I.getOperand(1));
725             setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
726             return;
727           }
728         }
729         else if (F->getName() == "sin" || F->getName() == "sinf") {
730           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
731               I.getOperand(1)->getType()->isFloatingPoint() &&
732               I.getType() == I.getOperand(1)->getType()) {
733             Tmp = getValue(I.getOperand(1));
734             setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
735             return;
736           }
737         }
738         else if (F->getName() == "cos" || F->getName() == "cosf") {
739           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
740               I.getOperand(1)->getType()->isFloatingPoint() &&
741               I.getType() == I.getOperand(1)->getType()) {
742             Tmp = getValue(I.getOperand(1));
743             setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
744             return;
745           }
746         }
747         break;
748       case Intrinsic::vastart:  visitVAStart(I); return;
749       case Intrinsic::vaend:    visitVAEnd(I); return;
750       case Intrinsic::vacopy:   visitVACopy(I); return;
751       case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return;
752       case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return;
753
754       case Intrinsic::setjmp:
755         RenameFn = "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
756         break;
757       case Intrinsic::longjmp:
758         RenameFn = "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
759         break;
760       case Intrinsic::memcpy:  visitMemIntrinsic(I, ISD::MEMCPY); return;
761       case Intrinsic::memset:  visitMemIntrinsic(I, ISD::MEMSET); return;
762       case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return;
763
764       case Intrinsic::readport:
765       case Intrinsic::readio: {
766         std::vector<MVT::ValueType> VTs;
767         VTs.push_back(TLI.getValueType(I.getType()));
768         VTs.push_back(MVT::Other);
769         std::vector<SDOperand> Ops;
770         Ops.push_back(getRoot());
771         Ops.push_back(getValue(I.getOperand(1)));
772         Tmp = DAG.getNode(F->getIntrinsicID() == Intrinsic::readport ?
773                           ISD::READPORT : ISD::READIO, VTs, Ops);
774
775         setValue(&I, Tmp);
776         DAG.setRoot(Tmp.getValue(1));
777         return;
778       }
779       case Intrinsic::writeport:
780       case Intrinsic::writeio:
781         DAG.setRoot(DAG.getNode(F->getIntrinsicID() == Intrinsic::writeport ?
782                                 ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
783                                 getRoot(), getValue(I.getOperand(1)),
784                                 getValue(I.getOperand(2))));
785         return;
786       case Intrinsic::dbg_stoppoint:
787       case Intrinsic::dbg_region_start:
788       case Intrinsic::dbg_region_end:
789       case Intrinsic::dbg_func_start:
790       case Intrinsic::dbg_declare:
791         if (I.getType() != Type::VoidTy)
792           setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
793         return;
794
795       case Intrinsic::isunordered:
796         setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
797                                   getValue(I.getOperand(2)), ISD::SETUO));
798         return;
799
800       case Intrinsic::sqrt:
801         setValue(&I, DAG.getNode(ISD::FSQRT,
802                                  getValue(I.getOperand(1)).getValueType(),
803                                  getValue(I.getOperand(1))));
804         return;
805
806       case Intrinsic::pcmarker:
807         Tmp = getValue(I.getOperand(1));
808         DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
809         return;
810       case Intrinsic::cttz:
811         setValue(&I, DAG.getNode(ISD::CTTZ,
812                                  getValue(I.getOperand(1)).getValueType(),
813                                  getValue(I.getOperand(1))));
814         return;
815       case Intrinsic::ctlz:
816         setValue(&I, DAG.getNode(ISD::CTLZ,
817                                  getValue(I.getOperand(1)).getValueType(),
818                                  getValue(I.getOperand(1))));
819         return;
820       case Intrinsic::ctpop:
821         setValue(&I, DAG.getNode(ISD::CTPOP,
822                                  getValue(I.getOperand(1)).getValueType(),
823                                  getValue(I.getOperand(1))));
824         return;
825       default:
826         std::cerr << I;
827         assert(0 && "This intrinsic is not implemented yet!");
828         return;
829       }
830
831   SDOperand Callee;
832   if (!RenameFn)
833     Callee = getValue(I.getOperand(0));
834   else
835     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
836   std::vector<std::pair<SDOperand, const Type*> > Args;
837
838   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
839     Value *Arg = I.getOperand(i);
840     SDOperand ArgNode = getValue(Arg);
841     Args.push_back(std::make_pair(ArgNode, Arg->getType()));
842   }
843
844   const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
845   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
846
847   std::pair<SDOperand,SDOperand> Result =
848     TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
849                     I.isTailCall(), Callee, Args, DAG);
850   if (I.getType() != Type::VoidTy)
851     setValue(&I, Result.first);
852   DAG.setRoot(Result.second);
853 }
854
855 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
856   SDOperand Src = getValue(I.getOperand(0));
857
858   MVT::ValueType IntPtr = TLI.getPointerTy();
859
860   if (IntPtr < Src.getValueType())
861     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
862   else if (IntPtr > Src.getValueType())
863     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
864
865   // Scale the source by the type size.
866   uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
867   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
868                     Src, getIntPtrConstant(ElementSize));
869
870   std::vector<std::pair<SDOperand, const Type*> > Args;
871   Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
872
873   std::pair<SDOperand,SDOperand> Result =
874     TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
875                     DAG.getExternalSymbol("malloc", IntPtr),
876                     Args, DAG);
877   setValue(&I, Result.first);  // Pointers always fit in registers
878   DAG.setRoot(Result.second);
879 }
880
881 void SelectionDAGLowering::visitFree(FreeInst &I) {
882   std::vector<std::pair<SDOperand, const Type*> > Args;
883   Args.push_back(std::make_pair(getValue(I.getOperand(0)),
884                                 TLI.getTargetData().getIntPtrType()));
885   MVT::ValueType IntPtr = TLI.getPointerTy();
886   std::pair<SDOperand,SDOperand> Result =
887     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
888                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
889   DAG.setRoot(Result.second);
890 }
891
892 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
893 // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
894 // instructions are special in various ways, which require special support to
895 // insert.  The specified MachineInstr is created but not inserted into any
896 // basic blocks, and the scheduler passes ownership of it to this method.
897 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
898                                                        MachineBasicBlock *MBB) {
899   std::cerr << "If a target marks an instruction with "
900                "'usesCustomDAGSchedInserter', it must implement "
901                "TargetLowering::InsertAtEndOfBasicBlock!\n";
902   abort();
903   return 0;  
904 }
905
906 SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
907                                         SelectionDAG &DAG) {
908   return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
909 }
910
911 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
912                                        SDOperand VAListP, Value *VAListV,
913                                        SelectionDAG &DAG) {
914   // We have no sane default behavior, just emit a useful error message and bail
915   // out.
916   std::cerr << "Variable arguments handling not implemented on this target!\n";
917   abort();
918   return SDOperand();
919 }
920
921 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
922                                      SelectionDAG &DAG) {
923   // Default to a noop.
924   return Chain;
925 }
926
927 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
928                                       SDOperand SrcP, Value *SrcV,
929                                       SDOperand DestP, Value *DestV,
930                                       SelectionDAG &DAG) {
931   // Default to copying the input list.
932   SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
933                               SrcP, DAG.getSrcValue(SrcV));
934   SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
935                                  Val, DestP, DAG.getSrcValue(DestV));
936   return Result;
937 }
938
939 std::pair<SDOperand,SDOperand>
940 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
941                            const Type *ArgTy, SelectionDAG &DAG) {
942   // We have no sane default behavior, just emit a useful error message and bail
943   // out.
944   std::cerr << "Variable arguments handling not implemented on this target!\n";
945   abort();
946   return std::make_pair(SDOperand(), SDOperand());
947 }
948
949
950 void SelectionDAGLowering::visitVAStart(CallInst &I) {
951   DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
952                                I.getOperand(1), DAG));
953 }
954
955 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
956   std::pair<SDOperand,SDOperand> Result =
957     TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
958                    I.getType(), DAG);
959   setValue(&I, Result.first);
960   DAG.setRoot(Result.second);
961 }
962
963 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
964   DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
965                              I.getOperand(1), DAG));
966 }
967
968 void SelectionDAGLowering::visitVACopy(CallInst &I) {
969   SDOperand Result =
970     TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
971                     getValue(I.getOperand(1)), I.getOperand(1), DAG);
972   DAG.setRoot(Result);
973 }
974
975
976 // It is always conservatively correct for llvm.returnaddress and
977 // llvm.frameaddress to return 0.
978 std::pair<SDOperand, SDOperand>
979 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
980                                         unsigned Depth, SelectionDAG &DAG) {
981   return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
982 }
983
984 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
985   assert(0 && "LowerOperation not implemented for this target!");
986   abort();
987   return SDOperand();
988 }
989
990 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
991   unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
992   std::pair<SDOperand,SDOperand> Result =
993     TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
994   setValue(&I, Result.first);
995   DAG.setRoot(Result.second);
996 }
997
998 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
999   std::vector<SDOperand> Ops;
1000   Ops.push_back(getRoot());
1001   Ops.push_back(getValue(I.getOperand(1)));
1002   Ops.push_back(getValue(I.getOperand(2)));
1003   Ops.push_back(getValue(I.getOperand(3)));
1004   Ops.push_back(getValue(I.getOperand(4)));
1005   DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1006 }
1007
1008 //===----------------------------------------------------------------------===//
1009 // SelectionDAGISel code
1010 //===----------------------------------------------------------------------===//
1011
1012 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1013   return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1014 }
1015
1016 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1017   // FIXME: we only modify the CFG to split critical edges.  This
1018   // updates dom and loop info.
1019 }
1020
1021
1022 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1023   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1024   RegMap = MF.getSSARegMap();
1025   DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1026
1027   // First pass, split all critical edges for PHI nodes with incoming values
1028   // that are constants, this way the load of the constant into a vreg will not
1029   // be placed into MBBs that are used some other way.
1030   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1031     PHINode *PN;
1032     for (BasicBlock::iterator BBI = BB->begin();
1033          (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1034       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1035         if (isa<Constant>(PN->getIncomingValue(i)))
1036           SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1037   }
1038
1039   FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1040
1041   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1042     SelectBasicBlock(I, MF, FuncInfo);
1043
1044   return true;
1045 }
1046
1047
1048 SDOperand SelectionDAGISel::
1049 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1050   SDOperand Op = SDL.getValue(V);
1051   assert((Op.getOpcode() != ISD::CopyFromReg ||
1052           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1053          "Copy from a reg to the same reg!");
1054   
1055   // If this type is not legal, we must make sure to not create an invalid
1056   // register use.
1057   MVT::ValueType SrcVT = Op.getValueType();
1058   MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1059   SelectionDAG &DAG = SDL.DAG;
1060   if (SrcVT == DestVT) {
1061     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1062   } else if (SrcVT < DestVT) {
1063     // The src value is promoted to the register.
1064     if (MVT::isFloatingPoint(SrcVT))
1065       Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1066     else
1067       Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1068     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1069   } else  {
1070     // The src value is expanded into multiple registers.
1071     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1072                                Op, DAG.getConstant(0, MVT::i32));
1073     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1074                                Op, DAG.getConstant(1, MVT::i32));
1075     Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1076     return DAG.getCopyToReg(Op, Reg+1, Hi);
1077   }
1078 }
1079
1080 void SelectionDAGISel::
1081 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1082                std::vector<SDOperand> &UnorderedChains) {
1083   // If this is the entry block, emit arguments.
1084   Function &F = *BB->getParent();
1085   FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1086   SDOperand OldRoot = SDL.DAG.getRoot();
1087   std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1088
1089   unsigned a = 0;
1090   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1091        AI != E; ++AI, ++a)
1092     if (!AI->use_empty()) {
1093       SDL.setValue(AI, Args[a]);
1094       
1095       // If this argument is live outside of the entry block, insert a copy from
1096       // whereever we got it to the vreg that other BB's will reference it as.
1097       if (FuncInfo.ValueMap.count(AI)) {
1098         SDOperand Copy =
1099           CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1100         UnorderedChains.push_back(Copy);
1101       }
1102     }
1103
1104   // Next, if the function has live ins that need to be copied into vregs,
1105   // emit the copies now, into the top of the block.
1106   MachineFunction &MF = SDL.DAG.getMachineFunction();
1107   if (MF.livein_begin() != MF.livein_end()) {
1108     SSARegMap *RegMap = MF.getSSARegMap();
1109     const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1110     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1111          E = MF.livein_end(); LI != E; ++LI)
1112       if (LI->second)
1113         MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1114                          LI->first, RegMap->getRegClass(LI->second));
1115   }
1116     
1117   // Finally, if the target has anything special to do, allow it to do so.
1118   EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1119 }
1120
1121
1122 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1123        std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1124                                     FunctionLoweringInfo &FuncInfo) {
1125   SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1126
1127   std::vector<SDOperand> UnorderedChains;
1128
1129   // Lower any arguments needed in this block if this is the entry block.
1130   if (LLVMBB == &LLVMBB->getParent()->front())
1131     LowerArguments(LLVMBB, SDL, UnorderedChains);
1132
1133   BB = FuncInfo.MBBMap[LLVMBB];
1134   SDL.setCurrentBasicBlock(BB);
1135
1136   // Lower all of the non-terminator instructions.
1137   for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1138        I != E; ++I)
1139     SDL.visit(*I);
1140
1141   // Ensure that all instructions which are used outside of their defining
1142   // blocks are available as virtual registers.
1143   for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1144     if (!I->use_empty() && !isa<PHINode>(I)) {
1145       std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1146       if (VMI != FuncInfo.ValueMap.end())
1147         UnorderedChains.push_back(
1148                            CopyValueToVirtualRegister(SDL, I, VMI->second));
1149     }
1150
1151   // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
1152   // ensure constants are generated when needed.  Remember the virtual registers
1153   // that need to be added to the Machine PHI nodes as input.  We cannot just
1154   // directly add them, because expansion might result in multiple MBB's for one
1155   // BB.  As such, the start of the BB might correspond to a different MBB than
1156   // the end.
1157   //
1158
1159   // Emit constants only once even if used by multiple PHI nodes.
1160   std::map<Constant*, unsigned> ConstantsOut;
1161
1162   // Check successor nodes PHI nodes that expect a constant to be available from
1163   // this block.
1164   TerminatorInst *TI = LLVMBB->getTerminator();
1165   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1166     BasicBlock *SuccBB = TI->getSuccessor(succ);
1167     MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1168     PHINode *PN;
1169
1170     // At this point we know that there is a 1-1 correspondence between LLVM PHI
1171     // nodes and Machine PHI nodes, but the incoming operands have not been
1172     // emitted yet.
1173     for (BasicBlock::iterator I = SuccBB->begin();
1174          (PN = dyn_cast<PHINode>(I)); ++I)
1175       if (!PN->use_empty()) {
1176         unsigned Reg;
1177         Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1178         if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1179           unsigned &RegOut = ConstantsOut[C];
1180           if (RegOut == 0) {
1181             RegOut = FuncInfo.CreateRegForValue(C);
1182             UnorderedChains.push_back(
1183                              CopyValueToVirtualRegister(SDL, C, RegOut));
1184           }
1185           Reg = RegOut;
1186         } else {
1187           Reg = FuncInfo.ValueMap[PHIOp];
1188           if (Reg == 0) {
1189             assert(isa<AllocaInst>(PHIOp) &&
1190                    FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1191                    "Didn't codegen value into a register!??");
1192             Reg = FuncInfo.CreateRegForValue(PHIOp);
1193             UnorderedChains.push_back(
1194                              CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1195           }
1196         }
1197
1198         // Remember that this register needs to added to the machine PHI node as
1199         // the input for this MBB.
1200         unsigned NumElements =
1201           TLI.getNumElements(TLI.getValueType(PN->getType()));
1202         for (unsigned i = 0, e = NumElements; i != e; ++i)
1203           PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1204       }
1205   }
1206   ConstantsOut.clear();
1207
1208   // Turn all of the unordered chains into one factored node.
1209   if (!UnorderedChains.empty()) {
1210     UnorderedChains.push_back(SDL.getRoot());
1211     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1212   }
1213
1214   // Lower the terminator after the copies are emitted.
1215   SDL.visit(*LLVMBB->getTerminator());
1216
1217   // Make sure the root of the DAG is up-to-date.
1218   DAG.setRoot(SDL.getRoot());
1219 }
1220
1221 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1222                                         FunctionLoweringInfo &FuncInfo) {
1223   SelectionDAG DAG(TLI, MF);
1224   CurDAG = &DAG;
1225   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1226
1227   // First step, lower LLVM code to some DAG.  This DAG may use operations and
1228   // types that are not supported by the target.
1229   BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1230
1231   // Run the DAG combiner in pre-legalize mode.
1232   DAG.Combine(false);
1233   
1234   DEBUG(std::cerr << "Lowered selection DAG:\n");
1235   DEBUG(DAG.dump());
1236
1237   // Second step, hack on the DAG until it only uses operations and types that
1238   // the target supports.
1239   DAG.Legalize();
1240
1241   DEBUG(std::cerr << "Legalized selection DAG:\n");
1242   DEBUG(DAG.dump());
1243
1244   // Run the DAG combiner in post-legalize mode.
1245   DAG.Combine(true);
1246   
1247   if (ViewDAGs) DAG.viewGraph();
1248   
1249   // Third, instruction select all of the operations to machine code, adding the
1250   // code to the MachineBasicBlock.
1251   InstructionSelectBasicBlock(DAG);
1252
1253   DEBUG(std::cerr << "Selected machine code:\n");
1254   DEBUG(BB->dump());
1255
1256   // Next, now that we know what the last MBB the LLVM BB expanded is, update
1257   // PHI nodes in successors.
1258   for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1259     MachineInstr *PHI = PHINodesToUpdate[i].first;
1260     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1261            "This is not a machine PHI node that we are updating!");
1262     PHI->addRegOperand(PHINodesToUpdate[i].second);
1263     PHI->addMachineBasicBlockOperand(BB);
1264   }
1265
1266   // Finally, add the CFG edges from the last selected MBB to the successor
1267   // MBBs.
1268   TerminatorInst *TI = LLVMBB->getTerminator();
1269   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1270     MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1271     BB->addSuccessor(Succ0MBB);
1272   }
1273 }