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