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