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