Typo.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGISel.cpp
1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAGISel class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/GlobalVariable.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Intrinsics.h"
24 #include "llvm/CodeGen/IntrinsicLowering.h"
25 #include "llvm/CodeGen/MachineDebugInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/SelectionDAG.h"
30 #include "llvm/CodeGen/SSARegMap.h"
31 #include "llvm/Target/MRegisterInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetFrameInfo.h"
34 #include "llvm/Target/TargetInstrInfo.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/MathExtras.h"
40 #include "llvm/Support/Debug.h"
41 #include <map>
42 #include <iostream>
43 using namespace llvm;
44
45 #ifndef NDEBUG
46 static cl::opt<bool>
47 ViewISelDAGs("view-isel-dags", cl::Hidden,
48           cl::desc("Pop up a window to show isel dags as they are selected"));
49 static cl::opt<bool>
50 ViewSchedDAGs("view-sched-dags", cl::Hidden,
51           cl::desc("Pop up a window to show sched dags as they are processed"));
52 #else
53 static const bool ViewISelDAGs = 0;
54 static const bool ViewSchedDAGs = 0;
55 #endif
56
57 namespace {
58   cl::opt<SchedHeuristics>
59   ISHeuristic(
60     "sched",
61     cl::desc("Choose scheduling style"),
62     cl::init(noScheduling),
63     cl::values(
64       clEnumValN(noScheduling, "none",
65                  "No scheduling: breadth first sequencing"),
66       clEnumValN(simpleScheduling, "simple",
67                  "Simple two pass scheduling: minimize critical path "
68                  "and maximize processor utilization"),
69       clEnumValN(simpleNoItinScheduling, "simple-noitin",
70                  "Simple two pass scheduling: Same as simple "
71                  "except using generic latency"),
72       clEnumValN(listSchedulingBURR, "list-BURR",
73                  "Bottom up register reduction list scheduling"),
74       clEnumValEnd));
75 } // namespace
76
77
78 namespace llvm {
79   //===--------------------------------------------------------------------===//
80   /// FunctionLoweringInfo - This contains information that is global to a
81   /// function that is used when lowering a region of the function.
82   class FunctionLoweringInfo {
83   public:
84     TargetLowering &TLI;
85     Function &Fn;
86     MachineFunction &MF;
87     SSARegMap *RegMap;
88
89     FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
90
91     /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
92     std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
93
94     /// ValueMap - Since we emit code for the function a basic block at a time,
95     /// we must remember which virtual registers hold the values for
96     /// cross-basic-block values.
97     std::map<const Value*, unsigned> ValueMap;
98
99     /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
100     /// the entry block.  This allows the allocas to be efficiently referenced
101     /// anywhere in the function.
102     std::map<const AllocaInst*, int> StaticAllocaMap;
103
104     unsigned MakeReg(MVT::ValueType VT) {
105       return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
106     }
107
108     unsigned CreateRegForValue(const Value *V) {
109       MVT::ValueType VT = TLI.getValueType(V->getType());
110       // The common case is that we will only create one register for this
111       // value.  If we have that case, create and return the virtual register.
112       unsigned NV = TLI.getNumElements(VT);
113       if (NV == 1) {
114         // If we are promoting this value, pick the next largest supported type.
115         return MakeReg(TLI.getTypeToTransformTo(VT));
116       }
117
118       // If this value is represented with multiple target registers, make sure
119       // to create enough consequtive registers of the right (smaller) type.
120       unsigned NT = VT-1;  // Find the type to use.
121       while (TLI.getNumElements((MVT::ValueType)NT) != 1)
122         --NT;
123
124       unsigned R = MakeReg((MVT::ValueType)NT);
125       for (unsigned i = 1; i != NV; ++i)
126         MakeReg((MVT::ValueType)NT);
127       return R;
128     }
129
130     unsigned InitializeRegForValue(const Value *V) {
131       unsigned &R = ValueMap[V];
132       assert(R == 0 && "Already initialized this value register!");
133       return R = CreateRegForValue(V);
134     }
135   };
136 }
137
138 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
139 /// PHI nodes or outside of the basic block that defines it.
140 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
141   if (isa<PHINode>(I)) return true;
142   BasicBlock *BB = I->getParent();
143   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
144     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
145       return true;
146   return false;
147 }
148
149 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
150 /// entry block, return true.
151 static bool isOnlyUsedInEntryBlock(Argument *A) {
152   BasicBlock *Entry = A->getParent()->begin();
153   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
154     if (cast<Instruction>(*UI)->getParent() != Entry)
155       return false;  // Use not in entry block.
156   return true;
157 }
158
159 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
160                                            Function &fn, MachineFunction &mf)
161     : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
162
163   // Create a vreg for each argument register that is not dead and is used
164   // outside of the entry block for the function.
165   for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
166        AI != E; ++AI)
167     if (!isOnlyUsedInEntryBlock(AI))
168       InitializeRegForValue(AI);
169
170   // Initialize the mapping of values to registers.  This is only set up for
171   // instruction values that are used outside of the block that defines
172   // them.
173   Function::iterator BB = Fn.begin(), EB = Fn.end();
174   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
175     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
176       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
177         const Type *Ty = AI->getAllocatedType();
178         uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
179         unsigned Align = 
180           std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
181                    AI->getAlignment());
182
183         // If the alignment of the value is smaller than the size of the value,
184         // and if the size of the value is particularly small (<= 8 bytes),
185         // round up to the size of the value for potentially better performance.
186         //
187         // FIXME: This could be made better with a preferred alignment hook in
188         // TargetData.  It serves primarily to 8-byte align doubles for X86.
189         if (Align < TySize && TySize <= 8) Align = TySize;
190         TySize *= CUI->getValue();   // Get total allocated size.
191         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
192         StaticAllocaMap[AI] =
193           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
194       }
195
196   for (; BB != EB; ++BB)
197     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
198       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
199         if (!isa<AllocaInst>(I) ||
200             !StaticAllocaMap.count(cast<AllocaInst>(I)))
201           InitializeRegForValue(I);
202
203   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
204   // also creates the initial PHI MachineInstrs, though none of the input
205   // operands are populated.
206   for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
207     MachineBasicBlock *MBB = new MachineBasicBlock(BB);
208     MBBMap[BB] = MBB;
209     MF.getBasicBlockList().push_back(MBB);
210
211     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
212     // appropriate.
213     PHINode *PN;
214     for (BasicBlock::iterator I = BB->begin();
215          (PN = dyn_cast<PHINode>(I)); ++I)
216       if (!PN->use_empty()) {
217         unsigned NumElements =
218           TLI.getNumElements(TLI.getValueType(PN->getType()));
219         unsigned PHIReg = ValueMap[PN];
220         assert(PHIReg &&"PHI node does not have an assigned virtual register!");
221         for (unsigned i = 0; i != NumElements; ++i)
222           BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
223       }
224   }
225 }
226
227
228
229 //===----------------------------------------------------------------------===//
230 /// SelectionDAGLowering - This is the common target-independent lowering
231 /// implementation that is parameterized by a TargetLowering object.
232 /// Also, targets can overload any lowering method.
233 ///
234 namespace llvm {
235 class SelectionDAGLowering {
236   MachineBasicBlock *CurMBB;
237
238   std::map<const Value*, SDOperand> NodeMap;
239
240   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
241   /// them up and then emit token factor nodes when possible.  This allows us to
242   /// get simple disambiguation between loads without worrying about alias
243   /// analysis.
244   std::vector<SDOperand> PendingLoads;
245
246 public:
247   // TLI - This is information that describes the available target features we
248   // need for lowering.  This indicates when operations are unavailable,
249   // implemented with a libcall, etc.
250   TargetLowering &TLI;
251   SelectionDAG &DAG;
252   const TargetData &TD;
253
254   /// FuncInfo - Information about the function as a whole.
255   ///
256   FunctionLoweringInfo &FuncInfo;
257
258   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
259                        FunctionLoweringInfo &funcinfo)
260     : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
261       FuncInfo(funcinfo) {
262   }
263
264   /// getRoot - Return the current virtual root of the Selection DAG.
265   ///
266   SDOperand getRoot() {
267     if (PendingLoads.empty())
268       return DAG.getRoot();
269
270     if (PendingLoads.size() == 1) {
271       SDOperand Root = PendingLoads[0];
272       DAG.setRoot(Root);
273       PendingLoads.clear();
274       return Root;
275     }
276
277     // Otherwise, we have to make a token factor node.
278     SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
279     PendingLoads.clear();
280     DAG.setRoot(Root);
281     return Root;
282   }
283
284   void visit(Instruction &I) { visit(I.getOpcode(), I); }
285
286   void visit(unsigned Opcode, User &I) {
287     switch (Opcode) {
288     default: assert(0 && "Unknown instruction type encountered!");
289              abort();
290       // Build the switch statement using the Instruction.def file.
291 #define HANDLE_INST(NUM, OPCODE, CLASS) \
292     case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
293 #include "llvm/Instruction.def"
294     }
295   }
296
297   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
298
299
300   SDOperand getIntPtrConstant(uint64_t Val) {
301     return DAG.getConstant(Val, TLI.getPointerTy());
302   }
303
304   SDOperand getValue(const Value *V) {
305     SDOperand &N = NodeMap[V];
306     if (N.Val) return N;
307
308     const Type *VTy = V->getType();
309     MVT::ValueType VT = TLI.getValueType(VTy);
310     if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V)))
311       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
312         visit(CE->getOpcode(), *CE);
313         assert(N.Val && "visit didn't populate the ValueMap!");
314         return N;
315       } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
316         return N = DAG.getGlobalAddress(GV, VT);
317       } else if (isa<ConstantPointerNull>(C)) {
318         return N = DAG.getConstant(0, TLI.getPointerTy());
319       } else if (isa<UndefValue>(C)) {
320         return N = DAG.getNode(ISD::UNDEF, VT);
321       } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
322         return N = DAG.getConstantFP(CFP->getValue(), VT);
323       } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
324         unsigned NumElements = PTy->getNumElements();
325         MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
326         MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
327         
328         // Now that we know the number and type of the elements, push a
329         // Constant or ConstantFP node onto the ops list for each element of
330         // the packed constant.
331         std::vector<SDOperand> Ops;
332         if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
333           if (MVT::isFloatingPoint(PVT)) {
334             for (unsigned i = 0; i != NumElements; ++i) {
335               const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
336               Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
337             }
338           } else {
339             for (unsigned i = 0; i != NumElements; ++i) {
340               const ConstantIntegral *El = 
341                 cast<ConstantIntegral>(CP->getOperand(i));
342               Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
343             }
344           }
345         } else {
346           assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
347           SDOperand Op;
348           if (MVT::isFloatingPoint(PVT))
349             Op = DAG.getConstantFP(0, PVT);
350           else
351             Op = DAG.getConstant(0, PVT);
352           Ops.assign(NumElements, Op);
353         }
354         
355         // Handle the case where we have a 1-element vector, in which
356         // case we want to immediately turn it into a scalar constant.
357         if (Ops.size() == 1) {
358           return N = Ops[0];
359         } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
360           return N = DAG.getNode(ISD::ConstantVec, TVT, Ops);
361         } else {
362           // If the packed type isn't legal, then create a ConstantVec node with
363           // generic Vector type instead.
364           return N = DAG.getNode(ISD::ConstantVec, MVT::Vector, Ops);
365         }
366       } else {
367         // Canonicalize all constant ints to be unsigned.
368         return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
369       }
370
371     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
372       std::map<const AllocaInst*, int>::iterator SI =
373         FuncInfo.StaticAllocaMap.find(AI);
374       if (SI != FuncInfo.StaticAllocaMap.end())
375         return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
376     }
377
378     std::map<const Value*, unsigned>::const_iterator VMI =
379       FuncInfo.ValueMap.find(V);
380     assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
381
382     unsigned InReg = VMI->second;
383    
384     // If this type is not legal, make it so now.
385     MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
386     
387     N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
388     if (DestVT < VT) {
389       // Source must be expanded.  This input value is actually coming from the
390       // register pair VMI->second and VMI->second+1.
391       N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
392                       DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
393     } else {
394       if (DestVT > VT) { // Promotion case
395         if (MVT::isFloatingPoint(VT))
396           N = DAG.getNode(ISD::FP_ROUND, VT, N);
397         else
398           N = DAG.getNode(ISD::TRUNCATE, VT, N);
399       }
400     }
401     
402     return N;
403   }
404
405   const SDOperand &setValue(const Value *V, SDOperand NewN) {
406     SDOperand &N = NodeMap[V];
407     assert(N.Val == 0 && "Already set a value for this node!");
408     return N = NewN;
409   }
410
411   // Terminator instructions.
412   void visitRet(ReturnInst &I);
413   void visitBr(BranchInst &I);
414   void visitUnreachable(UnreachableInst &I) { /* noop */ }
415
416   // These all get lowered before this pass.
417   void visitExtractElement(ExtractElementInst &I) { assert(0 && "TODO"); }
418   void visitInsertElement(InsertElementInst &I) { assert(0 && "TODO"); }
419   void visitSwitch(SwitchInst &I) { assert(0 && "TODO"); }
420   void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
421   void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
422
423   //
424   void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
425   void visitShift(User &I, unsigned Opcode);
426   void visitAdd(User &I) { 
427     visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD); 
428   }
429   void visitSub(User &I);
430   void visitMul(User &I) { 
431     visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL); 
432   }
433   void visitDiv(User &I) {
434     const Type *Ty = I.getType();
435     visitBinary(I, Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV, 0);
436   }
437   void visitRem(User &I) {
438     const Type *Ty = I.getType();
439     visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
440   }
441   void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, 0); }
442   void visitOr (User &I) { visitBinary(I, ISD::OR,  0, 0); }
443   void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, 0); }
444   void visitShl(User &I) { visitShift(I, ISD::SHL); }
445   void visitShr(User &I) { 
446     visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
447   }
448
449   void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
450   void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
451   void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
452   void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
453   void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
454   void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
455   void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
456
457   void visitGetElementPtr(User &I);
458   void visitCast(User &I);
459   void visitSelect(User &I);
460   //
461
462   void visitMalloc(MallocInst &I);
463   void visitFree(FreeInst &I);
464   void visitAlloca(AllocaInst &I);
465   void visitLoad(LoadInst &I);
466   void visitStore(StoreInst &I);
467   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
468   void visitCall(CallInst &I);
469   const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
470
471   void visitVAStart(CallInst &I);
472   void visitVAArg(VAArgInst &I);
473   void visitVAEnd(CallInst &I);
474   void visitVACopy(CallInst &I);
475   void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
476
477   void visitMemIntrinsic(CallInst &I, unsigned Op);
478
479   void visitUserOp1(Instruction &I) {
480     assert(0 && "UserOp1 should not exist at instruction selection time!");
481     abort();
482   }
483   void visitUserOp2(Instruction &I) {
484     assert(0 && "UserOp2 should not exist at instruction selection time!");
485     abort();
486   }
487 };
488 } // end namespace llvm
489
490 void SelectionDAGLowering::visitRet(ReturnInst &I) {
491   if (I.getNumOperands() == 0) {
492     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
493     return;
494   }
495
496   SDOperand Op1 = getValue(I.getOperand(0));
497   MVT::ValueType TmpVT;
498
499   switch (Op1.getValueType()) {
500   default: assert(0 && "Unknown value type!");
501   case MVT::i1:
502   case MVT::i8:
503   case MVT::i16:
504   case MVT::i32:
505     // If this is a machine where 32-bits is legal or expanded, promote to
506     // 32-bits, otherwise, promote to 64-bits.
507     if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
508       TmpVT = TLI.getTypeToTransformTo(MVT::i32);
509     else
510       TmpVT = MVT::i32;
511
512     // Extend integer types to result type.
513     if (I.getOperand(0)->getType()->isSigned())
514       Op1 = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, Op1);
515     else
516       Op1 = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, Op1);
517     break;
518   case MVT::f32:
519     // If this is a machine where f32 is promoted to f64, do so now.
520     if (TLI.getTypeAction(MVT::f32) == TargetLowering::Promote)
521       Op1 = DAG.getNode(ISD::FP_EXTEND, TLI.getTypeToTransformTo(MVT::f32),Op1);
522     break;
523   case MVT::i64:
524   case MVT::f64:
525     break; // No extension needed!
526   }
527   // Allow targets to lower this further to meet ABI requirements
528   DAG.setRoot(TLI.LowerReturnTo(getRoot(), Op1, DAG));
529 }
530
531 void SelectionDAGLowering::visitBr(BranchInst &I) {
532   // Update machine-CFG edges.
533   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
534
535   // Figure out which block is immediately after the current one.
536   MachineBasicBlock *NextBlock = 0;
537   MachineFunction::iterator BBI = CurMBB;
538   if (++BBI != CurMBB->getParent()->end())
539     NextBlock = BBI;
540
541   if (I.isUnconditional()) {
542     // If this is not a fall-through branch, emit the branch.
543     if (Succ0MBB != NextBlock)
544       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
545                               DAG.getBasicBlock(Succ0MBB)));
546   } else {
547     MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
548
549     SDOperand Cond = getValue(I.getCondition());
550     if (Succ1MBB == NextBlock) {
551       // If the condition is false, fall through.  This means we should branch
552       // if the condition is true to Succ #0.
553       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
554                               Cond, DAG.getBasicBlock(Succ0MBB)));
555     } else if (Succ0MBB == NextBlock) {
556       // If the condition is true, fall through.  This means we should branch if
557       // the condition is false to Succ #1.  Invert the condition first.
558       SDOperand True = DAG.getConstant(1, Cond.getValueType());
559       Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
560       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
561                               Cond, DAG.getBasicBlock(Succ1MBB)));
562     } else {
563       std::vector<SDOperand> Ops;
564       Ops.push_back(getRoot());
565       Ops.push_back(Cond);
566       Ops.push_back(DAG.getBasicBlock(Succ0MBB));
567       Ops.push_back(DAG.getBasicBlock(Succ1MBB));
568       DAG.setRoot(DAG.getNode(ISD::BRCONDTWOWAY, MVT::Other, Ops));
569     }
570   }
571 }
572
573 void SelectionDAGLowering::visitSub(User &I) {
574   // -0.0 - X --> fneg
575   if (I.getType()->isFloatingPoint()) {
576     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
577       if (CFP->isExactlyValue(-0.0)) {
578         SDOperand Op2 = getValue(I.getOperand(1));
579         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
580         return;
581       }
582   }
583   visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
584 }
585
586 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp, 
587                                        unsigned VecOp) {
588   const Type *Ty = I.getType();
589   SDOperand Op1 = getValue(I.getOperand(0));
590   SDOperand Op2 = getValue(I.getOperand(1));
591
592   if (Ty->isIntegral()) {
593     setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
594   } else if (Ty->isFloatingPoint()) {
595     setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
596   } else {
597     const PackedType *PTy = cast<PackedType>(Ty);
598     unsigned NumElements = PTy->getNumElements();
599     MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
600     MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
601     
602     // Immediately scalarize packed types containing only one element, so that
603     // the Legalize pass does not have to deal with them.  Similarly, if the
604     // abstract vector is going to turn into one that the target natively
605     // supports, generate that type now so that Legalize doesn't have to deal
606     // with that either.  These steps ensure that Legalize only has to handle
607     // vector types in its Expand case.
608     unsigned Opc = MVT::isFloatingPoint(PVT) ? FPOp : IntOp;
609     if (NumElements == 1) {
610       setValue(&I, DAG.getNode(Opc, PVT, Op1, Op2));
611     } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
612       setValue(&I, DAG.getNode(Opc, TVT, Op1, Op2));
613     } else {
614       SDOperand Num = DAG.getConstant(NumElements, MVT::i32);
615       SDOperand Typ = DAG.getValueType(PVT);
616       setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
617     }
618   }
619 }
620
621 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
622   SDOperand Op1 = getValue(I.getOperand(0));
623   SDOperand Op2 = getValue(I.getOperand(1));
624   
625   Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
626   
627   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
628 }
629
630 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
631                                       ISD::CondCode UnsignedOpcode) {
632   SDOperand Op1 = getValue(I.getOperand(0));
633   SDOperand Op2 = getValue(I.getOperand(1));
634   ISD::CondCode Opcode = SignedOpcode;
635   if (I.getOperand(0)->getType()->isUnsigned())
636     Opcode = UnsignedOpcode;
637   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
638 }
639
640 void SelectionDAGLowering::visitSelect(User &I) {
641   SDOperand Cond     = getValue(I.getOperand(0));
642   SDOperand TrueVal  = getValue(I.getOperand(1));
643   SDOperand FalseVal = getValue(I.getOperand(2));
644   setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
645                            TrueVal, FalseVal));
646 }
647
648 void SelectionDAGLowering::visitCast(User &I) {
649   SDOperand N = getValue(I.getOperand(0));
650   MVT::ValueType SrcTy = TLI.getValueType(I.getOperand(0)->getType());
651   MVT::ValueType DestTy = TLI.getValueType(I.getType());
652
653   if (N.getValueType() == DestTy) {
654     setValue(&I, N);  // noop cast.
655   } else if (DestTy == MVT::i1) {
656     // Cast to bool is a comparison against zero, not truncation to zero.
657     SDOperand Zero = isInteger(SrcTy) ? DAG.getConstant(0, N.getValueType()) :
658                                        DAG.getConstantFP(0.0, N.getValueType());
659     setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
660   } else if (isInteger(SrcTy)) {
661     if (isInteger(DestTy)) {        // Int -> Int cast
662       if (DestTy < SrcTy)   // Truncating cast?
663         setValue(&I, DAG.getNode(ISD::TRUNCATE, DestTy, N));
664       else if (I.getOperand(0)->getType()->isSigned())
665         setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestTy, N));
666       else
667         setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestTy, N));
668     } else {                        // Int -> FP cast
669       if (I.getOperand(0)->getType()->isSigned())
670         setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestTy, N));
671       else
672         setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestTy, N));
673     }
674   } else {
675     assert(isFloatingPoint(SrcTy) && "Unknown value type!");
676     if (isFloatingPoint(DestTy)) {  // FP -> FP cast
677       if (DestTy < SrcTy)   // Rounding cast?
678         setValue(&I, DAG.getNode(ISD::FP_ROUND, DestTy, N));
679       else
680         setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestTy, N));
681     } else {                        // FP -> Int cast.
682       if (I.getType()->isSigned())
683         setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestTy, N));
684       else
685         setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestTy, N));
686     }
687   }
688 }
689
690 void SelectionDAGLowering::visitGetElementPtr(User &I) {
691   SDOperand N = getValue(I.getOperand(0));
692   const Type *Ty = I.getOperand(0)->getType();
693   const Type *UIntPtrTy = TD.getIntPtrType();
694
695   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
696        OI != E; ++OI) {
697     Value *Idx = *OI;
698     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
699       unsigned Field = cast<ConstantUInt>(Idx)->getValue();
700       if (Field) {
701         // N = N + Offset
702         uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
703         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
704                         getIntPtrConstant(Offset));
705       }
706       Ty = StTy->getElementType(Field);
707     } else {
708       Ty = cast<SequentialType>(Ty)->getElementType();
709
710       // If this is a constant subscript, handle it quickly.
711       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
712         if (CI->getRawValue() == 0) continue;
713
714         uint64_t Offs;
715         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
716           Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
717         else
718           Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
719         N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
720         continue;
721       }
722       
723       // N = N + Idx * ElementSize;
724       uint64_t ElementSize = TD.getTypeSize(Ty);
725       SDOperand IdxN = getValue(Idx);
726
727       // If the index is smaller or larger than intptr_t, truncate or extend
728       // it.
729       if (IdxN.getValueType() < N.getValueType()) {
730         if (Idx->getType()->isSigned())
731           IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
732         else
733           IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
734       } else if (IdxN.getValueType() > N.getValueType())
735         IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
736
737       // If this is a multiply by a power of two, turn it into a shl
738       // immediately.  This is a very common case.
739       if (isPowerOf2_64(ElementSize)) {
740         unsigned Amt = Log2_64(ElementSize);
741         IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
742                            DAG.getConstant(Amt, TLI.getShiftAmountTy()));
743         N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
744         continue;
745       }
746       
747       SDOperand Scale = getIntPtrConstant(ElementSize);
748       IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
749       N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
750     }
751   }
752   setValue(&I, N);
753 }
754
755 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
756   // If this is a fixed sized alloca in the entry block of the function,
757   // allocate it statically on the stack.
758   if (FuncInfo.StaticAllocaMap.count(&I))
759     return;   // getValue will auto-populate this.
760
761   const Type *Ty = I.getAllocatedType();
762   uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
763   unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
764                             I.getAlignment());
765
766   SDOperand AllocSize = getValue(I.getArraySize());
767   MVT::ValueType IntPtr = TLI.getPointerTy();
768   if (IntPtr < AllocSize.getValueType())
769     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
770   else if (IntPtr > AllocSize.getValueType())
771     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
772
773   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
774                           getIntPtrConstant(TySize));
775
776   // Handle alignment.  If the requested alignment is less than or equal to the
777   // stack alignment, ignore it and round the size of the allocation up to the
778   // stack alignment size.  If the size is greater than the stack alignment, we
779   // note this in the DYNAMIC_STACKALLOC node.
780   unsigned StackAlign =
781     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
782   if (Align <= StackAlign) {
783     Align = 0;
784     // Add SA-1 to the size.
785     AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
786                             getIntPtrConstant(StackAlign-1));
787     // Mask out the low bits for alignment purposes.
788     AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
789                             getIntPtrConstant(~(uint64_t)(StackAlign-1)));
790   }
791
792   std::vector<MVT::ValueType> VTs;
793   VTs.push_back(AllocSize.getValueType());
794   VTs.push_back(MVT::Other);
795   std::vector<SDOperand> Ops;
796   Ops.push_back(getRoot());
797   Ops.push_back(AllocSize);
798   Ops.push_back(getIntPtrConstant(Align));
799   SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
800   DAG.setRoot(setValue(&I, DSA).getValue(1));
801
802   // Inform the Frame Information that we have just allocated a variable-sized
803   // object.
804   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
805 }
806
807 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
808 /// global into a string value.  Return an empty string if we can't do it.
809 ///
810 static std::string getStringValue(Value *V, unsigned Offset = 0) {
811   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
812     if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
813       ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
814       if (Init->isString()) {
815         std::string Result = Init->getAsString();
816         if (Offset < Result.size()) {
817           // If we are pointing INTO The string, erase the beginning...
818           Result.erase(Result.begin(), Result.begin()+Offset);
819
820           // Take off the null terminator, and any string fragments after it.
821           std::string::size_type NullPos = Result.find_first_of((char)0);
822           if (NullPos != std::string::npos)
823             Result.erase(Result.begin()+NullPos, Result.end());
824           return Result;
825         }
826       }
827     }
828   } else if (Constant *C = dyn_cast<Constant>(V)) {
829     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
830       return getStringValue(GV, Offset);
831     else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
832       if (CE->getOpcode() == Instruction::GetElementPtr) {
833         // Turn a gep into the specified offset.
834         if (CE->getNumOperands() == 3 &&
835             cast<Constant>(CE->getOperand(1))->isNullValue() &&
836             isa<ConstantInt>(CE->getOperand(2))) {
837           return getStringValue(CE->getOperand(0),
838                    Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
839         }
840       }
841     }
842   }
843   return "";
844 }
845
846 void SelectionDAGLowering::visitLoad(LoadInst &I) {
847   SDOperand Ptr = getValue(I.getOperand(0));
848
849   SDOperand Root;
850   if (I.isVolatile())
851     Root = getRoot();
852   else {
853     // Do not serialize non-volatile loads against each other.
854     Root = DAG.getRoot();
855   }
856   
857   const Type *Ty = I.getType();
858   SDOperand L;
859   
860   if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
861     unsigned NumElements = PTy->getNumElements();
862     MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
863     MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
864     
865     // Immediately scalarize packed types containing only one element, so that
866     // the Legalize pass does not have to deal with them.
867     if (NumElements == 1) {
868       L = DAG.getLoad(PVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
869     } else if (TVT != MVT::Other && TLI.isTypeLegal(TVT)) {
870       L = DAG.getLoad(TVT, Root, Ptr, DAG.getSrcValue(I.getOperand(0)));
871     } else {
872       L = DAG.getVecLoad(NumElements, PVT, Root, Ptr, 
873                          DAG.getSrcValue(I.getOperand(0)));
874     }
875   } else {
876     L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, 
877                     DAG.getSrcValue(I.getOperand(0)));
878   }
879   setValue(&I, L);
880
881   if (I.isVolatile())
882     DAG.setRoot(L.getValue(1));
883   else
884     PendingLoads.push_back(L.getValue(1));
885 }
886
887
888 void SelectionDAGLowering::visitStore(StoreInst &I) {
889   Value *SrcV = I.getOperand(0);
890   SDOperand Src = getValue(SrcV);
891   SDOperand Ptr = getValue(I.getOperand(1));
892   DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
893                           DAG.getSrcValue(I.getOperand(1))));
894 }
895
896 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
897 /// we want to emit this as a call to a named external function, return the name
898 /// otherwise lower it and return null.
899 const char *
900 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
901   switch (Intrinsic) {
902   case Intrinsic::vastart:  visitVAStart(I); return 0;
903   case Intrinsic::vaend:    visitVAEnd(I); return 0;
904   case Intrinsic::vacopy:   visitVACopy(I); return 0;
905   case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
906   case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
907   case Intrinsic::setjmp:
908     return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
909     break;
910   case Intrinsic::longjmp:
911     return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
912     break;
913   case Intrinsic::memcpy:  visitMemIntrinsic(I, ISD::MEMCPY); return 0;
914   case Intrinsic::memset:  visitMemIntrinsic(I, ISD::MEMSET); return 0;
915   case Intrinsic::memmove: visitMemIntrinsic(I, ISD::MEMMOVE); return 0;
916     
917   case Intrinsic::readport:
918   case Intrinsic::readio: {
919     std::vector<MVT::ValueType> VTs;
920     VTs.push_back(TLI.getValueType(I.getType()));
921     VTs.push_back(MVT::Other);
922     std::vector<SDOperand> Ops;
923     Ops.push_back(getRoot());
924     Ops.push_back(getValue(I.getOperand(1)));
925     SDOperand Tmp = DAG.getNode(Intrinsic == Intrinsic::readport ?
926                                 ISD::READPORT : ISD::READIO, VTs, Ops);
927     
928     setValue(&I, Tmp);
929     DAG.setRoot(Tmp.getValue(1));
930     return 0;
931   }
932   case Intrinsic::writeport:
933   case Intrinsic::writeio:
934     DAG.setRoot(DAG.getNode(Intrinsic == Intrinsic::writeport ?
935                             ISD::WRITEPORT : ISD::WRITEIO, MVT::Other,
936                             getRoot(), getValue(I.getOperand(1)),
937                             getValue(I.getOperand(2))));
938     return 0;
939     
940   case Intrinsic::dbg_stoppoint: {
941     if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
942       return "llvm_debugger_stop";
943     
944     std::string fname = "<unknown>";
945     std::vector<SDOperand> Ops;
946
947     // Input Chain
948     Ops.push_back(getRoot());
949     
950     // line number
951     Ops.push_back(getValue(I.getOperand(2)));
952    
953     // column
954     Ops.push_back(getValue(I.getOperand(3)));
955
956     // filename/working dir
957     // Pull the filename out of the the compilation unit.
958     const GlobalVariable *cunit = dyn_cast<GlobalVariable>(I.getOperand(4));
959     if (cunit && cunit->hasInitializer()) {
960       if (ConstantStruct *CS = 
961             dyn_cast<ConstantStruct>(cunit->getInitializer())) {
962         if (CS->getNumOperands() > 0) {
963           Ops.push_back(DAG.getString(getStringValue(CS->getOperand(3))));
964           Ops.push_back(DAG.getString(getStringValue(CS->getOperand(4))));
965         }
966       }
967     }
968     
969     if (Ops.size() == 5)  // Found filename/workingdir.
970       DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
971     setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
972     return 0;
973   }
974   case Intrinsic::dbg_region_start:
975     if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
976       return "llvm_dbg_region_start";
977     if (I.getType() != Type::VoidTy)
978       setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
979     return 0;
980   case Intrinsic::dbg_region_end:
981     if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
982       return "llvm_dbg_region_end";
983     if (I.getType() != Type::VoidTy)
984       setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
985     return 0;
986   case Intrinsic::dbg_func_start:
987     if (TLI.getTargetMachine().getIntrinsicLowering().EmitDebugFunctions())
988       return "llvm_dbg_subprogram";
989     if (I.getType() != Type::VoidTy)
990       setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
991     return 0;
992   case Intrinsic::dbg_declare:
993     if (I.getType() != Type::VoidTy)
994       setValue(&I, DAG.getNode(ISD::UNDEF, TLI.getValueType(I.getType())));
995     return 0;
996     
997   case Intrinsic::isunordered_f32:
998   case Intrinsic::isunordered_f64:
999     setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1000                               getValue(I.getOperand(2)), ISD::SETUO));
1001     return 0;
1002     
1003   case Intrinsic::sqrt_f32:
1004   case Intrinsic::sqrt_f64:
1005     setValue(&I, DAG.getNode(ISD::FSQRT,
1006                              getValue(I.getOperand(1)).getValueType(),
1007                              getValue(I.getOperand(1))));
1008     return 0;
1009   case Intrinsic::pcmarker: {
1010     SDOperand Tmp = getValue(I.getOperand(1));
1011     DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1012     return 0;
1013   }
1014   case Intrinsic::readcyclecounter: {
1015     std::vector<MVT::ValueType> VTs;
1016     VTs.push_back(MVT::i64);
1017     VTs.push_back(MVT::Other);
1018     std::vector<SDOperand> Ops;
1019     Ops.push_back(getRoot());
1020     SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1021     setValue(&I, Tmp);
1022     DAG.setRoot(Tmp.getValue(1));
1023     return 0;
1024   }
1025   case Intrinsic::bswap_i16:
1026   case Intrinsic::bswap_i32:
1027   case Intrinsic::bswap_i64:
1028     setValue(&I, DAG.getNode(ISD::BSWAP,
1029                              getValue(I.getOperand(1)).getValueType(),
1030                              getValue(I.getOperand(1))));
1031     return 0;
1032   case Intrinsic::cttz_i8:
1033   case Intrinsic::cttz_i16:
1034   case Intrinsic::cttz_i32:
1035   case Intrinsic::cttz_i64:
1036     setValue(&I, DAG.getNode(ISD::CTTZ,
1037                              getValue(I.getOperand(1)).getValueType(),
1038                              getValue(I.getOperand(1))));
1039     return 0;
1040   case Intrinsic::ctlz_i8:
1041   case Intrinsic::ctlz_i16:
1042   case Intrinsic::ctlz_i32:
1043   case Intrinsic::ctlz_i64:
1044     setValue(&I, DAG.getNode(ISD::CTLZ,
1045                              getValue(I.getOperand(1)).getValueType(),
1046                              getValue(I.getOperand(1))));
1047     return 0;
1048   case Intrinsic::ctpop_i8:
1049   case Intrinsic::ctpop_i16:
1050   case Intrinsic::ctpop_i32:
1051   case Intrinsic::ctpop_i64:
1052     setValue(&I, DAG.getNode(ISD::CTPOP,
1053                              getValue(I.getOperand(1)).getValueType(),
1054                              getValue(I.getOperand(1))));
1055     return 0;
1056   case Intrinsic::stacksave: {
1057     std::vector<MVT::ValueType> VTs;
1058     VTs.push_back(TLI.getPointerTy());
1059     VTs.push_back(MVT::Other);
1060     std::vector<SDOperand> Ops;
1061     Ops.push_back(getRoot());
1062     SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1063     setValue(&I, Tmp);
1064     DAG.setRoot(Tmp.getValue(1));
1065     return 0;
1066   }
1067   case Intrinsic::stackrestore: {
1068     SDOperand Tmp = getValue(I.getOperand(1));
1069     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1070     return 0;
1071   }
1072   case Intrinsic::prefetch:
1073     // FIXME: Currently discarding prefetches.
1074     return 0;
1075   default:
1076     std::cerr << I;
1077     assert(0 && "This intrinsic is not implemented yet!");
1078     return 0;
1079   }
1080 }
1081
1082
1083 void SelectionDAGLowering::visitCall(CallInst &I) {
1084   const char *RenameFn = 0;
1085   if (Function *F = I.getCalledFunction()) {
1086     if (F->isExternal())
1087       if (unsigned IID = F->getIntrinsicID()) {
1088         RenameFn = visitIntrinsicCall(I, IID);
1089         if (!RenameFn)
1090           return;
1091       } else {    // Not an LLVM intrinsic.
1092         const std::string &Name = F->getName();
1093         if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1094           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1095               I.getOperand(1)->getType()->isFloatingPoint() &&
1096               I.getType() == I.getOperand(1)->getType()) {
1097             SDOperand Tmp = getValue(I.getOperand(1));
1098             setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1099             return;
1100           }
1101         } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1102           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1103               I.getOperand(1)->getType()->isFloatingPoint() &&
1104               I.getType() == I.getOperand(1)->getType() &&
1105               TLI.isOperationLegal(ISD::FSIN,
1106                                  TLI.getValueType(I.getOperand(1)->getType()))) {
1107             SDOperand Tmp = getValue(I.getOperand(1));
1108             setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1109             return;
1110           }
1111         } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1112           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1113               I.getOperand(1)->getType()->isFloatingPoint() &&
1114               I.getType() == I.getOperand(1)->getType() &&
1115               TLI.isOperationLegal(ISD::FCOS,
1116                               TLI.getValueType(I.getOperand(1)->getType()))) {
1117             SDOperand Tmp = getValue(I.getOperand(1));
1118             setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1119             return;
1120           }
1121         }
1122       }
1123   }
1124
1125   SDOperand Callee;
1126   if (!RenameFn)
1127     Callee = getValue(I.getOperand(0));
1128   else
1129     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1130   std::vector<std::pair<SDOperand, const Type*> > Args;
1131   Args.reserve(I.getNumOperands());
1132   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1133     Value *Arg = I.getOperand(i);
1134     SDOperand ArgNode = getValue(Arg);
1135     Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1136   }
1137
1138   const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1139   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1140
1141   std::pair<SDOperand,SDOperand> Result =
1142     TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1143                     I.isTailCall(), Callee, Args, DAG);
1144   if (I.getType() != Type::VoidTy)
1145     setValue(&I, Result.first);
1146   DAG.setRoot(Result.second);
1147 }
1148
1149 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
1150   SDOperand Src = getValue(I.getOperand(0));
1151
1152   MVT::ValueType IntPtr = TLI.getPointerTy();
1153
1154   if (IntPtr < Src.getValueType())
1155     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
1156   else if (IntPtr > Src.getValueType())
1157     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
1158
1159   // Scale the source by the type size.
1160   uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
1161   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
1162                     Src, getIntPtrConstant(ElementSize));
1163
1164   std::vector<std::pair<SDOperand, const Type*> > Args;
1165   Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
1166
1167   std::pair<SDOperand,SDOperand> Result =
1168     TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
1169                     DAG.getExternalSymbol("malloc", IntPtr),
1170                     Args, DAG);
1171   setValue(&I, Result.first);  // Pointers always fit in registers
1172   DAG.setRoot(Result.second);
1173 }
1174
1175 void SelectionDAGLowering::visitFree(FreeInst &I) {
1176   std::vector<std::pair<SDOperand, const Type*> > Args;
1177   Args.push_back(std::make_pair(getValue(I.getOperand(0)),
1178                                 TLI.getTargetData().getIntPtrType()));
1179   MVT::ValueType IntPtr = TLI.getPointerTy();
1180   std::pair<SDOperand,SDOperand> Result =
1181     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
1182                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
1183   DAG.setRoot(Result.second);
1184 }
1185
1186 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
1187 // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
1188 // instructions are special in various ways, which require special support to
1189 // insert.  The specified MachineInstr is created but not inserted into any
1190 // basic blocks, and the scheduler passes ownership of it to this method.
1191 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
1192                                                        MachineBasicBlock *MBB) {
1193   std::cerr << "If a target marks an instruction with "
1194                "'usesCustomDAGSchedInserter', it must implement "
1195                "TargetLowering::InsertAtEndOfBasicBlock!\n";
1196   abort();
1197   return 0;  
1198 }
1199
1200 SDOperand TargetLowering::LowerReturnTo(SDOperand Chain, SDOperand Op,
1201                                         SelectionDAG &DAG) {
1202   return DAG.getNode(ISD::RET, MVT::Other, Chain, Op);
1203 }
1204
1205 SDOperand TargetLowering::LowerVAStart(SDOperand Chain,
1206                                        SDOperand VAListP, Value *VAListV,
1207                                        SelectionDAG &DAG) {
1208   // We have no sane default behavior, just emit a useful error message and bail
1209   // out.
1210   std::cerr << "Variable arguments handling not implemented on this target!\n";
1211   abort();
1212   return SDOperand();
1213 }
1214
1215 SDOperand TargetLowering::LowerVAEnd(SDOperand Chain, SDOperand LP, Value *LV,
1216                                      SelectionDAG &DAG) {
1217   // Default to a noop.
1218   return Chain;
1219 }
1220
1221 SDOperand TargetLowering::LowerVACopy(SDOperand Chain,
1222                                       SDOperand SrcP, Value *SrcV,
1223                                       SDOperand DestP, Value *DestV,
1224                                       SelectionDAG &DAG) {
1225   // Default to copying the input list.
1226   SDOperand Val = DAG.getLoad(getPointerTy(), Chain,
1227                               SrcP, DAG.getSrcValue(SrcV));
1228   SDOperand Result = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
1229                                  Val, DestP, DAG.getSrcValue(DestV));
1230   return Result;
1231 }
1232
1233 std::pair<SDOperand,SDOperand>
1234 TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
1235                            const Type *ArgTy, SelectionDAG &DAG) {
1236   // We have no sane default behavior, just emit a useful error message and bail
1237   // out.
1238   std::cerr << "Variable arguments handling not implemented on this target!\n";
1239   abort();
1240   return std::make_pair(SDOperand(), SDOperand());
1241 }
1242
1243
1244 void SelectionDAGLowering::visitVAStart(CallInst &I) {
1245   DAG.setRoot(TLI.LowerVAStart(getRoot(), getValue(I.getOperand(1)),
1246                                I.getOperand(1), DAG));
1247 }
1248
1249 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
1250   std::pair<SDOperand,SDOperand> Result =
1251     TLI.LowerVAArg(getRoot(), getValue(I.getOperand(0)), I.getOperand(0),
1252                    I.getType(), DAG);
1253   setValue(&I, Result.first);
1254   DAG.setRoot(Result.second);
1255 }
1256
1257 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
1258   DAG.setRoot(TLI.LowerVAEnd(getRoot(), getValue(I.getOperand(1)),
1259                              I.getOperand(1), DAG));
1260 }
1261
1262 void SelectionDAGLowering::visitVACopy(CallInst &I) {
1263   SDOperand Result =
1264     TLI.LowerVACopy(getRoot(), getValue(I.getOperand(2)), I.getOperand(2),
1265                     getValue(I.getOperand(1)), I.getOperand(1), DAG);
1266   DAG.setRoot(Result);
1267 }
1268
1269
1270 // It is always conservatively correct for llvm.returnaddress and
1271 // llvm.frameaddress to return 0.
1272 std::pair<SDOperand, SDOperand>
1273 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
1274                                         unsigned Depth, SelectionDAG &DAG) {
1275   return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
1276 }
1277
1278 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
1279   assert(0 && "LowerOperation not implemented for this target!");
1280   abort();
1281   return SDOperand();
1282 }
1283
1284 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
1285   unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
1286   std::pair<SDOperand,SDOperand> Result =
1287     TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
1288   setValue(&I, Result.first);
1289   DAG.setRoot(Result.second);
1290 }
1291
1292 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
1293 #if 0
1294   // If the size of the cpy/move/set is constant (known)
1295   if (ConstantUInt* op3 = dyn_cast<ConstantUInt>(I.getOperand(3))) {
1296     uint64_t size = op3->getValue();
1297     switch (Op) {
1298       case ISD::MEMSET: 
1299         if (size <= TLI.getMaxStoresPerMemSet()) {
1300           if (ConstantUInt* op4 = dyn_cast<ConstantUInt>(I.getOperand(4))) {
1301         uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1302             uint64_t align = op4.getValue();
1303             while (size > align) {
1304               size -=align;
1305             }
1306   Value *SrcV = I.getOperand(0);
1307   SDOperand Src = getValue(SrcV);
1308   SDOperand Ptr = getValue(I.getOperand(1));
1309   DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1310                           DAG.getSrcValue(I.getOperand(1))));
1311           }
1312           break;
1313         }
1314         break; // don't do this optimization, use a normal memset
1315       case ISD::MEMMOVE: 
1316       case ISD::MEMCPY:
1317         break; // FIXME: not implemented yet
1318     }
1319   }
1320 #endif
1321
1322   // Non-optimized version
1323   std::vector<SDOperand> Ops;
1324   Ops.push_back(getRoot());
1325   Ops.push_back(getValue(I.getOperand(1)));
1326   Ops.push_back(getValue(I.getOperand(2)));
1327   Ops.push_back(getValue(I.getOperand(3)));
1328   Ops.push_back(getValue(I.getOperand(4)));
1329   DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
1330 }
1331
1332 //===----------------------------------------------------------------------===//
1333 // SelectionDAGISel code
1334 //===----------------------------------------------------------------------===//
1335
1336 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
1337   return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
1338 }
1339
1340 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
1341   // FIXME: we only modify the CFG to split critical edges.  This
1342   // updates dom and loop info.
1343 }
1344
1345
1346 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
1347 /// casting to the type of GEPI.
1348 static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
1349                                    Value *Ptr, Value *PtrOffset) {
1350   if (V) return V;   // Already computed.
1351   
1352   BasicBlock::iterator InsertPt;
1353   if (BB == GEPI->getParent()) {
1354     // If insert into the GEP's block, insert right after the GEP.
1355     InsertPt = GEPI;
1356     ++InsertPt;
1357   } else {
1358     // Otherwise, insert at the top of BB, after any PHI nodes
1359     InsertPt = BB->begin();
1360     while (isa<PHINode>(InsertPt)) ++InsertPt;
1361   }
1362   
1363   // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
1364   // BB so that there is only one value live across basic blocks (the cast 
1365   // operand).
1366   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
1367     if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
1368       Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
1369   
1370   // Add the offset, cast it to the right type.
1371   Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
1372   Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
1373   return V = Ptr;
1374 }
1375
1376
1377 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
1378 /// selection, we want to be a bit careful about some things.  In particular, if
1379 /// we have a GEP instruction that is used in a different block than it is
1380 /// defined, the addressing expression of the GEP cannot be folded into loads or
1381 /// stores that use it.  In this case, decompose the GEP and move constant
1382 /// indices into blocks that use it.
1383 static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
1384                                   const TargetData &TD) {
1385   // If this GEP is only used inside the block it is defined in, there is no
1386   // need to rewrite it.
1387   bool isUsedOutsideDefBB = false;
1388   BasicBlock *DefBB = GEPI->getParent();
1389   for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end(); 
1390        UI != E; ++UI) {
1391     if (cast<Instruction>(*UI)->getParent() != DefBB) {
1392       isUsedOutsideDefBB = true;
1393       break;
1394     }
1395   }
1396   if (!isUsedOutsideDefBB) return;
1397
1398   // If this GEP has no non-zero constant indices, there is nothing we can do,
1399   // ignore it.
1400   bool hasConstantIndex = false;
1401   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1402        E = GEPI->op_end(); OI != E; ++OI) {
1403     if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
1404       if (CI->getRawValue()) {
1405         hasConstantIndex = true;
1406         break;
1407       }
1408   }
1409   // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
1410   if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
1411   
1412   // Otherwise, decompose the GEP instruction into multiplies and adds.  Sum the
1413   // constant offset (which we now know is non-zero) and deal with it later.
1414   uint64_t ConstantOffset = 0;
1415   const Type *UIntPtrTy = TD.getIntPtrType();
1416   Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
1417   const Type *Ty = GEPI->getOperand(0)->getType();
1418
1419   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
1420        E = GEPI->op_end(); OI != E; ++OI) {
1421     Value *Idx = *OI;
1422     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1423       unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1424       if (Field)
1425         ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
1426       Ty = StTy->getElementType(Field);
1427     } else {
1428       Ty = cast<SequentialType>(Ty)->getElementType();
1429
1430       // Handle constant subscripts.
1431       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1432         if (CI->getRawValue() == 0) continue;
1433         
1434         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1435           ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1436         else
1437           ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1438         continue;
1439       }
1440       
1441       // Ptr = Ptr + Idx * ElementSize;
1442       
1443       // Cast Idx to UIntPtrTy if needed.
1444       Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
1445       
1446       uint64_t ElementSize = TD.getTypeSize(Ty);
1447       // Mask off bits that should not be set.
1448       ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1449       Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
1450
1451       // Multiply by the element size and add to the base.
1452       Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
1453       Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
1454     }
1455   }
1456   
1457   // Make sure that the offset fits in uintptr_t.
1458   ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
1459   Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
1460   
1461   // Okay, we have now emitted all of the variable index parts to the BB that
1462   // the GEP is defined in.  Loop over all of the using instructions, inserting
1463   // an "add Ptr, ConstantOffset" into each block that uses it and update the
1464   // instruction to use the newly computed value, making GEPI dead.  When the
1465   // user is a load or store instruction address, we emit the add into the user
1466   // block, otherwise we use a canonical version right next to the gep (these 
1467   // won't be foldable as addresses, so we might as well share the computation).
1468   
1469   std::map<BasicBlock*,Value*> InsertedExprs;
1470   while (!GEPI->use_empty()) {
1471     Instruction *User = cast<Instruction>(GEPI->use_back());
1472
1473     // If this use is not foldable into the addressing mode, use a version 
1474     // emitted in the GEP block.
1475     Value *NewVal;
1476     if (!isa<LoadInst>(User) &&
1477         (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
1478       NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI, 
1479                                     Ptr, PtrOffset);
1480     } else {
1481       // Otherwise, insert the code in the User's block so it can be folded into
1482       // any users in that block.
1483       NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()], 
1484                                     User->getParent(), GEPI, 
1485                                     Ptr, PtrOffset);
1486     }
1487     User->replaceUsesOfWith(GEPI, NewVal);
1488   }
1489   
1490   // Finally, the GEP is dead, remove it.
1491   GEPI->eraseFromParent();
1492 }
1493
1494 bool SelectionDAGISel::runOnFunction(Function &Fn) {
1495   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
1496   RegMap = MF.getSSARegMap();
1497   DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
1498
1499   // First, split all critical edges for PHI nodes with incoming values that are
1500   // constants, this way the load of the constant into a vreg will not be placed
1501   // into MBBs that are used some other way.
1502   //
1503   // In this pass we also look for GEP instructions that are used across basic
1504   // blocks and rewrites them to improve basic-block-at-a-time selection.
1505   // 
1506   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
1507     PHINode *PN;
1508     BasicBlock::iterator BBI;
1509     for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
1510       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1511         if (isa<Constant>(PN->getIncomingValue(i)))
1512           SplitCriticalEdge(PN->getIncomingBlock(i), BB);
1513     
1514     for (BasicBlock::iterator E = BB->end(); BBI != E; )
1515       if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
1516         OptimizeGEPExpression(GEPI, TLI.getTargetData());
1517   }
1518   
1519   FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
1520
1521   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
1522     SelectBasicBlock(I, MF, FuncInfo);
1523
1524   return true;
1525 }
1526
1527
1528 SDOperand SelectionDAGISel::
1529 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
1530   SDOperand Op = SDL.getValue(V);
1531   assert((Op.getOpcode() != ISD::CopyFromReg ||
1532           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
1533          "Copy from a reg to the same reg!");
1534   
1535   // If this type is not legal, we must make sure to not create an invalid
1536   // register use.
1537   MVT::ValueType SrcVT = Op.getValueType();
1538   MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
1539   SelectionDAG &DAG = SDL.DAG;
1540   if (SrcVT == DestVT) {
1541     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1542   } else if (SrcVT < DestVT) {
1543     // The src value is promoted to the register.
1544     if (MVT::isFloatingPoint(SrcVT))
1545       Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
1546     else
1547       Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
1548     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
1549   } else  {
1550     // The src value is expanded into multiple registers.
1551     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1552                                Op, DAG.getConstant(0, MVT::i32));
1553     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
1554                                Op, DAG.getConstant(1, MVT::i32));
1555     Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
1556     return DAG.getCopyToReg(Op, Reg+1, Hi);
1557   }
1558 }
1559
1560 void SelectionDAGISel::
1561 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
1562                std::vector<SDOperand> &UnorderedChains) {
1563   // If this is the entry block, emit arguments.
1564   Function &F = *BB->getParent();
1565   FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
1566   SDOperand OldRoot = SDL.DAG.getRoot();
1567   std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
1568
1569   unsigned a = 0;
1570   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
1571        AI != E; ++AI, ++a)
1572     if (!AI->use_empty()) {
1573       SDL.setValue(AI, Args[a]);
1574       
1575       // If this argument is live outside of the entry block, insert a copy from
1576       // whereever we got it to the vreg that other BB's will reference it as.
1577       if (FuncInfo.ValueMap.count(AI)) {
1578         SDOperand Copy =
1579           CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
1580         UnorderedChains.push_back(Copy);
1581       }
1582     }
1583
1584   // Next, if the function has live ins that need to be copied into vregs,
1585   // emit the copies now, into the top of the block.
1586   MachineFunction &MF = SDL.DAG.getMachineFunction();
1587   if (MF.livein_begin() != MF.livein_end()) {
1588     SSARegMap *RegMap = MF.getSSARegMap();
1589     const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
1590     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1591          E = MF.livein_end(); LI != E; ++LI)
1592       if (LI->second)
1593         MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
1594                          LI->first, RegMap->getRegClass(LI->second));
1595   }
1596     
1597   // Finally, if the target has anything special to do, allow it to do so.
1598   EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
1599 }
1600
1601
1602 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
1603        std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
1604                                     FunctionLoweringInfo &FuncInfo) {
1605   SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
1606
1607   std::vector<SDOperand> UnorderedChains;
1608
1609   // Lower any arguments needed in this block if this is the entry block.
1610   if (LLVMBB == &LLVMBB->getParent()->front())
1611     LowerArguments(LLVMBB, SDL, UnorderedChains);
1612
1613   BB = FuncInfo.MBBMap[LLVMBB];
1614   SDL.setCurrentBasicBlock(BB);
1615
1616   // Lower all of the non-terminator instructions.
1617   for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
1618        I != E; ++I)
1619     SDL.visit(*I);
1620
1621   // Ensure that all instructions which are used outside of their defining
1622   // blocks are available as virtual registers.
1623   for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
1624     if (!I->use_empty() && !isa<PHINode>(I)) {
1625       std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
1626       if (VMI != FuncInfo.ValueMap.end())
1627         UnorderedChains.push_back(
1628                            CopyValueToVirtualRegister(SDL, I, VMI->second));
1629     }
1630
1631   // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
1632   // ensure constants are generated when needed.  Remember the virtual registers
1633   // that need to be added to the Machine PHI nodes as input.  We cannot just
1634   // directly add them, because expansion might result in multiple MBB's for one
1635   // BB.  As such, the start of the BB might correspond to a different MBB than
1636   // the end.
1637   //
1638
1639   // Emit constants only once even if used by multiple PHI nodes.
1640   std::map<Constant*, unsigned> ConstantsOut;
1641
1642   // Check successor nodes PHI nodes that expect a constant to be available from
1643   // this block.
1644   TerminatorInst *TI = LLVMBB->getTerminator();
1645   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
1646     BasicBlock *SuccBB = TI->getSuccessor(succ);
1647     MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
1648     PHINode *PN;
1649
1650     // At this point we know that there is a 1-1 correspondence between LLVM PHI
1651     // nodes and Machine PHI nodes, but the incoming operands have not been
1652     // emitted yet.
1653     for (BasicBlock::iterator I = SuccBB->begin();
1654          (PN = dyn_cast<PHINode>(I)); ++I)
1655       if (!PN->use_empty()) {
1656         unsigned Reg;
1657         Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
1658         if (Constant *C = dyn_cast<Constant>(PHIOp)) {
1659           unsigned &RegOut = ConstantsOut[C];
1660           if (RegOut == 0) {
1661             RegOut = FuncInfo.CreateRegForValue(C);
1662             UnorderedChains.push_back(
1663                              CopyValueToVirtualRegister(SDL, C, RegOut));
1664           }
1665           Reg = RegOut;
1666         } else {
1667           Reg = FuncInfo.ValueMap[PHIOp];
1668           if (Reg == 0) {
1669             assert(isa<AllocaInst>(PHIOp) &&
1670                    FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
1671                    "Didn't codegen value into a register!??");
1672             Reg = FuncInfo.CreateRegForValue(PHIOp);
1673             UnorderedChains.push_back(
1674                              CopyValueToVirtualRegister(SDL, PHIOp, Reg));
1675           }
1676         }
1677
1678         // Remember that this register needs to added to the machine PHI node as
1679         // the input for this MBB.
1680         unsigned NumElements =
1681           TLI.getNumElements(TLI.getValueType(PN->getType()));
1682         for (unsigned i = 0, e = NumElements; i != e; ++i)
1683           PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
1684       }
1685   }
1686   ConstantsOut.clear();
1687
1688   // Turn all of the unordered chains into one factored node.
1689   if (!UnorderedChains.empty()) {
1690     SDOperand Root = SDL.getRoot();
1691     if (Root.getOpcode() != ISD::EntryToken) {
1692       unsigned i = 0, e = UnorderedChains.size();
1693       for (; i != e; ++i) {
1694         assert(UnorderedChains[i].Val->getNumOperands() > 1);
1695         if (UnorderedChains[i].Val->getOperand(0) == Root)
1696           break;  // Don't add the root if we already indirectly depend on it.
1697       }
1698         
1699       if (i == e)
1700         UnorderedChains.push_back(Root);
1701     }
1702     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
1703   }
1704
1705   // Lower the terminator after the copies are emitted.
1706   SDL.visit(*LLVMBB->getTerminator());
1707
1708   // Make sure the root of the DAG is up-to-date.
1709   DAG.setRoot(SDL.getRoot());
1710 }
1711
1712 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
1713                                         FunctionLoweringInfo &FuncInfo) {
1714   SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
1715   CurDAG = &DAG;
1716   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
1717
1718   // First step, lower LLVM code to some DAG.  This DAG may use operations and
1719   // types that are not supported by the target.
1720   BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
1721
1722   // Run the DAG combiner in pre-legalize mode.
1723   DAG.Combine(false);
1724   
1725   DEBUG(std::cerr << "Lowered selection DAG:\n");
1726   DEBUG(DAG.dump());
1727
1728   // Second step, hack on the DAG until it only uses operations and types that
1729   // the target supports.
1730   DAG.Legalize();
1731
1732   DEBUG(std::cerr << "Legalized selection DAG:\n");
1733   DEBUG(DAG.dump());
1734
1735   // Run the DAG combiner in post-legalize mode.
1736   DAG.Combine(true);
1737   
1738   if (ViewISelDAGs) DAG.viewGraph();
1739   
1740   // Third, instruction select all of the operations to machine code, adding the
1741   // code to the MachineBasicBlock.
1742   InstructionSelectBasicBlock(DAG);
1743
1744   DEBUG(std::cerr << "Selected machine code:\n");
1745   DEBUG(BB->dump());
1746
1747   // Next, now that we know what the last MBB the LLVM BB expanded is, update
1748   // PHI nodes in successors.
1749   for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
1750     MachineInstr *PHI = PHINodesToUpdate[i].first;
1751     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
1752            "This is not a machine PHI node that we are updating!");
1753     PHI->addRegOperand(PHINodesToUpdate[i].second);
1754     PHI->addMachineBasicBlockOperand(BB);
1755   }
1756
1757   // Finally, add the CFG edges from the last selected MBB to the successor
1758   // MBBs.
1759   TerminatorInst *TI = LLVMBB->getTerminator();
1760   for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1761     MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[TI->getSuccessor(i)];
1762     BB->addSuccessor(Succ0MBB);
1763   }
1764 }
1765
1766 //===----------------------------------------------------------------------===//
1767 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
1768 /// target node in the graph.
1769 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
1770   if (ViewSchedDAGs) DAG.viewGraph();
1771   ScheduleDAG *SL = NULL;
1772
1773   switch (ISHeuristic) {
1774   default: assert(0 && "Unrecognized scheduling heuristic");
1775   case noScheduling:
1776   case simpleScheduling:
1777   case simpleNoItinScheduling:
1778     SL = createSimpleDAGScheduler(ISHeuristic, DAG, BB);
1779     break;
1780   case listSchedulingBURR:
1781     SL = createBURRListDAGScheduler(DAG, BB);
1782   }
1783   BB = SL->Run();
1784 }