SelectionDAGISel can now natively handle Switch instructions, in the same
[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/InlineAsm.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/IntrinsicInst.h"
26 #include "llvm/CodeGen/IntrinsicLowering.h"
27 #include "llvm/CodeGen/MachineDebugInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/SelectionDAG.h"
32 #include "llvm/CodeGen/SSARegMap.h"
33 #include "llvm/Target/MRegisterInfo.h"
34 #include "llvm/Target/TargetData.h"
35 #include "llvm/Target/TargetFrameInfo.h"
36 #include "llvm/Target/TargetInstrInfo.h"
37 #include "llvm/Target/TargetLowering.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Debug.h"
43 #include <map>
44 #include <set>
45 #include <iostream>
46 #include <algorithm>
47 using namespace llvm;
48
49 #ifndef NDEBUG
50 static cl::opt<bool>
51 ViewISelDAGs("view-isel-dags", cl::Hidden,
52           cl::desc("Pop up a window to show isel dags as they are selected"));
53 static cl::opt<bool>
54 ViewSchedDAGs("view-sched-dags", cl::Hidden,
55           cl::desc("Pop up a window to show sched dags as they are processed"));
56 #else
57 static const bool ViewISelDAGs = 0;
58 static const bool ViewSchedDAGs = 0;
59 #endif
60
61 // Scheduling heuristics
62 enum SchedHeuristics {
63   defaultScheduling,      // Let the target specify its preference.
64   noScheduling,           // No scheduling, emit breadth first sequence.
65   simpleScheduling,       // Two pass, min. critical path, max. utilization.
66   simpleNoItinScheduling, // Same as above exact using generic latency.
67   listSchedulingBURR,     // Bottom up reg reduction list scheduling.
68   listSchedulingTD        // Top-down list scheduler.
69 };
70
71 namespace {
72   cl::opt<SchedHeuristics>
73   ISHeuristic(
74     "sched",
75     cl::desc("Choose scheduling style"),
76     cl::init(defaultScheduling),
77     cl::values(
78       clEnumValN(defaultScheduling, "default",
79                  "Target preferred scheduling style"),
80       clEnumValN(noScheduling, "none",
81                  "No scheduling: breadth first sequencing"),
82       clEnumValN(simpleScheduling, "simple",
83                  "Simple two pass scheduling: minimize critical path "
84                  "and maximize processor utilization"),
85       clEnumValN(simpleNoItinScheduling, "simple-noitin",
86                  "Simple two pass scheduling: Same as simple "
87                  "except using generic latency"),
88       clEnumValN(listSchedulingBURR, "list-burr",
89                  "Bottom up register reduction list scheduling"),
90       clEnumValN(listSchedulingTD, "list-td",
91                  "Top-down list scheduler"),
92       clEnumValEnd));
93 } // namespace
94
95 namespace {
96   /// RegsForValue - This struct represents the physical registers that a
97   /// particular value is assigned and the type information about the value.
98   /// This is needed because values can be promoted into larger registers and
99   /// expanded into multiple smaller registers than the value.
100   struct RegsForValue {
101     /// Regs - This list hold the register (for legal and promoted values)
102     /// or register set (for expanded values) that the value should be assigned
103     /// to.
104     std::vector<unsigned> Regs;
105     
106     /// RegVT - The value type of each register.
107     ///
108     MVT::ValueType RegVT;
109     
110     /// ValueVT - The value type of the LLVM value, which may be promoted from
111     /// RegVT or made from merging the two expanded parts.
112     MVT::ValueType ValueVT;
113     
114     RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
115     
116     RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
117       : RegVT(regvt), ValueVT(valuevt) {
118         Regs.push_back(Reg);
119     }
120     RegsForValue(const std::vector<unsigned> &regs, 
121                  MVT::ValueType regvt, MVT::ValueType valuevt)
122       : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
123     }
124     
125     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
126     /// this value and returns the result as a ValueVT value.  This uses 
127     /// Chain/Flag as the input and updates them for the output Chain/Flag.
128     SDOperand getCopyFromRegs(SelectionDAG &DAG,
129                               SDOperand &Chain, SDOperand &Flag) const;
130
131     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
132     /// specified value into the registers specified by this object.  This uses 
133     /// Chain/Flag as the input and updates them for the output Chain/Flag.
134     void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
135                        SDOperand &Chain, SDOperand &Flag) const;
136     
137     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
138     /// operand list.  This adds the code marker and includes the number of 
139     /// values added into it.
140     void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
141                               std::vector<SDOperand> &Ops) const;
142   };
143 }
144
145 namespace llvm {
146   //===--------------------------------------------------------------------===//
147   /// FunctionLoweringInfo - This contains information that is global to a
148   /// function that is used when lowering a region of the function.
149   class FunctionLoweringInfo {
150   public:
151     TargetLowering &TLI;
152     Function &Fn;
153     MachineFunction &MF;
154     SSARegMap *RegMap;
155
156     FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
157
158     /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
159     std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
160
161     /// ValueMap - Since we emit code for the function a basic block at a time,
162     /// we must remember which virtual registers hold the values for
163     /// cross-basic-block values.
164     std::map<const Value*, unsigned> ValueMap;
165
166     /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
167     /// the entry block.  This allows the allocas to be efficiently referenced
168     /// anywhere in the function.
169     std::map<const AllocaInst*, int> StaticAllocaMap;
170
171     unsigned MakeReg(MVT::ValueType VT) {
172       return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
173     }
174
175     unsigned CreateRegForValue(const Value *V);
176     
177     unsigned InitializeRegForValue(const Value *V) {
178       unsigned &R = ValueMap[V];
179       assert(R == 0 && "Already initialized this value register!");
180       return R = CreateRegForValue(V);
181     }
182   };
183 }
184
185 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
186 /// PHI nodes or outside of the basic block that defines it, or used by a 
187 /// switch instruction, which may expand to multiple basic blocks.
188 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
189   if (isa<PHINode>(I)) return true;
190   BasicBlock *BB = I->getParent();
191   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
192     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
193         isa<SwitchInst>(*UI))
194       return true;
195   return false;
196 }
197
198 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
199 /// entry block, return true.  This includes arguments used by switches, since
200 /// the switch may expand into multiple basic blocks.
201 static bool isOnlyUsedInEntryBlock(Argument *A) {
202   BasicBlock *Entry = A->getParent()->begin();
203   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
204     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
205       return false;  // Use not in entry block.
206   return true;
207 }
208
209 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
210                                            Function &fn, MachineFunction &mf)
211     : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
212
213   // Create a vreg for each argument register that is not dead and is used
214   // outside of the entry block for the function.
215   for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
216        AI != E; ++AI)
217     if (!isOnlyUsedInEntryBlock(AI))
218       InitializeRegForValue(AI);
219
220   // Initialize the mapping of values to registers.  This is only set up for
221   // instruction values that are used outside of the block that defines
222   // them.
223   Function::iterator BB = Fn.begin(), EB = Fn.end();
224   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
225     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
226       if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(AI->getArraySize())) {
227         const Type *Ty = AI->getAllocatedType();
228         uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
229         unsigned Align = 
230           std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
231                    AI->getAlignment());
232
233         // If the alignment of the value is smaller than the size of the value,
234         // and if the size of the value is particularly small (<= 8 bytes),
235         // round up to the size of the value for potentially better performance.
236         //
237         // FIXME: This could be made better with a preferred alignment hook in
238         // TargetData.  It serves primarily to 8-byte align doubles for X86.
239         if (Align < TySize && TySize <= 8) Align = TySize;
240         TySize *= CUI->getValue();   // Get total allocated size.
241         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
242         StaticAllocaMap[AI] =
243           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
244       }
245
246   for (; BB != EB; ++BB)
247     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
248       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
249         if (!isa<AllocaInst>(I) ||
250             !StaticAllocaMap.count(cast<AllocaInst>(I)))
251           InitializeRegForValue(I);
252
253   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
254   // also creates the initial PHI MachineInstrs, though none of the input
255   // operands are populated.
256   for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
257     MachineBasicBlock *MBB = new MachineBasicBlock(BB);
258     MBBMap[BB] = MBB;
259     MF.getBasicBlockList().push_back(MBB);
260
261     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
262     // appropriate.
263     PHINode *PN;
264     for (BasicBlock::iterator I = BB->begin();
265          (PN = dyn_cast<PHINode>(I)); ++I)
266       if (!PN->use_empty()) {
267         unsigned NumElements =
268           TLI.getNumElements(TLI.getValueType(PN->getType()));
269         unsigned PHIReg = ValueMap[PN];
270         assert(PHIReg &&"PHI node does not have an assigned virtual register!");
271         for (unsigned i = 0; i != NumElements; ++i)
272           BuildMI(MBB, TargetInstrInfo::PHI, PN->getNumOperands(), PHIReg+i);
273       }
274   }
275 }
276
277 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
278 /// the correctly promoted or expanded types.  Assign these registers
279 /// consecutive vreg numbers and return the first assigned number.
280 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
281   MVT::ValueType VT = TLI.getValueType(V->getType());
282   
283   // The number of multiples of registers that we need, to, e.g., split up
284   // a <2 x int64> -> 4 x i32 registers.
285   unsigned NumVectorRegs = 1;
286   
287   // If this is a packed type, figure out what type it will decompose into
288   // and how many of the elements it will use.
289   if (VT == MVT::Vector) {
290     const PackedType *PTy = cast<PackedType>(V->getType());
291     unsigned NumElts = PTy->getNumElements();
292     MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
293     
294     // Divide the input until we get to a supported size.  This will always
295     // end with a scalar if the target doesn't support vectors.
296     while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
297       NumElts >>= 1;
298       NumVectorRegs <<= 1;
299     }
300     if (NumElts == 1)
301       VT = EltTy;
302     else
303       VT = getVectorType(EltTy, NumElts);
304   }
305   
306   // The common case is that we will only create one register for this
307   // value.  If we have that case, create and return the virtual register.
308   unsigned NV = TLI.getNumElements(VT);
309   if (NV == 1) {
310     // If we are promoting this value, pick the next largest supported type.
311     MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
312     unsigned Reg = MakeReg(PromotedType);
313     // If this is a vector of supported or promoted types (e.g. 4 x i16),
314     // create all of the registers.
315     for (unsigned i = 1; i != NumVectorRegs; ++i)
316       MakeReg(PromotedType);
317     return Reg;
318   }
319   
320   // If this value is represented with multiple target registers, make sure
321   // to create enough consecutive registers of the right (smaller) type.
322   unsigned NT = VT-1;  // Find the type to use.
323   while (TLI.getNumElements((MVT::ValueType)NT) != 1)
324     --NT;
325   
326   unsigned R = MakeReg((MVT::ValueType)NT);
327   for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
328     MakeReg((MVT::ValueType)NT);
329   return R;
330 }
331
332 //===----------------------------------------------------------------------===//
333 /// SelectionDAGLowering - This is the common target-independent lowering
334 /// implementation that is parameterized by a TargetLowering object.
335 /// Also, targets can overload any lowering method.
336 ///
337 namespace llvm {
338 class SelectionDAGLowering {
339   MachineBasicBlock *CurMBB;
340
341   std::map<const Value*, SDOperand> NodeMap;
342
343   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
344   /// them up and then emit token factor nodes when possible.  This allows us to
345   /// get simple disambiguation between loads without worrying about alias
346   /// analysis.
347   std::vector<SDOperand> PendingLoads;
348
349   /// Case - A pair of values to record the Value for a switch case, and the
350   /// case's target basic block.  
351   typedef std::pair<Constant*, MachineBasicBlock*> Case;
352   typedef std::vector<Case>::iterator              CaseItr;
353   typedef std::pair<CaseItr, CaseItr>              CaseRange;
354
355   /// CaseRec - A struct with ctor used in lowering switches to a binary tree
356   /// of conditional branches.
357   struct CaseRec {
358     CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
359     CaseBB(bb), LT(lt), GE(ge), Range(r) {}
360
361     /// CaseBB - The MBB in which to emit the compare and branch
362     MachineBasicBlock *CaseBB;
363     /// LT, GE - If nonzero, we know the current case value must be less-than or
364     /// greater-than-or-equal-to these Constants.
365     Constant *LT;
366     Constant *GE;
367     /// Range - A pair of iterators representing the range of case values to be
368     /// processed at this point in the binary search tree.
369     CaseRange Range;
370   };
371   
372   /// The comparison function for sorting Case values.
373   struct CaseCmp {
374     bool operator () (const Case& C1, const Case& C2) {
375       if (const ConstantUInt* U1 = dyn_cast<const ConstantUInt>(C1.first))
376         return U1->getValue() < cast<const ConstantUInt>(C2.first)->getValue();
377       
378       const ConstantSInt* S1 = dyn_cast<const ConstantSInt>(C1.first);
379       return S1->getValue() < cast<const ConstantSInt>(C2.first)->getValue();
380     }
381   };
382   
383 public:
384   // TLI - This is information that describes the available target features we
385   // need for lowering.  This indicates when operations are unavailable,
386   // implemented with a libcall, etc.
387   TargetLowering &TLI;
388   SelectionDAG &DAG;
389   const TargetData &TD;
390
391   /// SwitchCases - Vector of CaseBlock structures used to communicate
392   /// SwitchInst code generation information.
393   std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
394   
395   /// FuncInfo - Information about the function as a whole.
396   ///
397   FunctionLoweringInfo &FuncInfo;
398
399   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
400                        FunctionLoweringInfo &funcinfo)
401     : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
402       FuncInfo(funcinfo) {
403   }
404
405   /// getRoot - Return the current virtual root of the Selection DAG.
406   ///
407   SDOperand getRoot() {
408     if (PendingLoads.empty())
409       return DAG.getRoot();
410
411     if (PendingLoads.size() == 1) {
412       SDOperand Root = PendingLoads[0];
413       DAG.setRoot(Root);
414       PendingLoads.clear();
415       return Root;
416     }
417
418     // Otherwise, we have to make a token factor node.
419     SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other, PendingLoads);
420     PendingLoads.clear();
421     DAG.setRoot(Root);
422     return Root;
423   }
424
425   void visit(Instruction &I) { visit(I.getOpcode(), I); }
426
427   void visit(unsigned Opcode, User &I) {
428     switch (Opcode) {
429     default: assert(0 && "Unknown instruction type encountered!");
430              abort();
431       // Build the switch statement using the Instruction.def file.
432 #define HANDLE_INST(NUM, OPCODE, CLASS) \
433     case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
434 #include "llvm/Instruction.def"
435     }
436   }
437
438   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
439
440   SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
441                         SDOperand SrcValue, SDOperand Root,
442                         bool isVolatile);
443
444   SDOperand getIntPtrConstant(uint64_t Val) {
445     return DAG.getConstant(Val, TLI.getPointerTy());
446   }
447
448   SDOperand getValue(const Value *V);
449
450   const SDOperand &setValue(const Value *V, SDOperand NewN) {
451     SDOperand &N = NodeMap[V];
452     assert(N.Val == 0 && "Already set a value for this node!");
453     return N = NewN;
454   }
455   
456   RegsForValue GetRegistersForValue(const std::string &ConstrCode,
457                                     MVT::ValueType VT,
458                                     bool OutReg, bool InReg,
459                                     std::set<unsigned> &OutputRegs, 
460                                     std::set<unsigned> &InputRegs);
461
462   // Terminator instructions.
463   void visitRet(ReturnInst &I);
464   void visitBr(BranchInst &I);
465   void visitSwitch(SwitchInst &I);
466   void visitUnreachable(UnreachableInst &I) { /* noop */ }
467
468   // Helper for visitSwitch
469   void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
470   
471   // These all get lowered before this pass.
472   void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
473   void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
474
475   void visitBinary(User &I, unsigned IntOp, unsigned FPOp, unsigned VecOp);
476   void visitShift(User &I, unsigned Opcode);
477   void visitAdd(User &I) { 
478     visitBinary(I, ISD::ADD, ISD::FADD, ISD::VADD); 
479   }
480   void visitSub(User &I);
481   void visitMul(User &I) { 
482     visitBinary(I, ISD::MUL, ISD::FMUL, ISD::VMUL); 
483   }
484   void visitDiv(User &I) {
485     const Type *Ty = I.getType();
486     visitBinary(I,
487                 Ty->isSigned() ? ISD::SDIV : ISD::UDIV, ISD::FDIV,
488                 Ty->isSigned() ? ISD::VSDIV : ISD::VUDIV);
489   }
490   void visitRem(User &I) {
491     const Type *Ty = I.getType();
492     visitBinary(I, Ty->isSigned() ? ISD::SREM : ISD::UREM, ISD::FREM, 0);
493   }
494   void visitAnd(User &I) { visitBinary(I, ISD::AND, 0, ISD::VAND); }
495   void visitOr (User &I) { visitBinary(I, ISD::OR,  0, ISD::VOR); }
496   void visitXor(User &I) { visitBinary(I, ISD::XOR, 0, ISD::VXOR); }
497   void visitShl(User &I) { visitShift(I, ISD::SHL); }
498   void visitShr(User &I) { 
499     visitShift(I, I.getType()->isUnsigned() ? ISD::SRL : ISD::SRA);
500   }
501
502   void visitSetCC(User &I, ISD::CondCode SignedOpc, ISD::CondCode UnsignedOpc);
503   void visitSetEQ(User &I) { visitSetCC(I, ISD::SETEQ, ISD::SETEQ); }
504   void visitSetNE(User &I) { visitSetCC(I, ISD::SETNE, ISD::SETNE); }
505   void visitSetLE(User &I) { visitSetCC(I, ISD::SETLE, ISD::SETULE); }
506   void visitSetGE(User &I) { visitSetCC(I, ISD::SETGE, ISD::SETUGE); }
507   void visitSetLT(User &I) { visitSetCC(I, ISD::SETLT, ISD::SETULT); }
508   void visitSetGT(User &I) { visitSetCC(I, ISD::SETGT, ISD::SETUGT); }
509
510   void visitExtractElement(ExtractElementInst &I);
511   void visitInsertElement(InsertElementInst &I);
512
513   void visitGetElementPtr(User &I);
514   void visitCast(User &I);
515   void visitSelect(User &I);
516
517   void visitMalloc(MallocInst &I);
518   void visitFree(FreeInst &I);
519   void visitAlloca(AllocaInst &I);
520   void visitLoad(LoadInst &I);
521   void visitStore(StoreInst &I);
522   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
523   void visitCall(CallInst &I);
524   void visitInlineAsm(CallInst &I);
525   const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
526   void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
527
528   void visitVAStart(CallInst &I);
529   void visitVAArg(VAArgInst &I);
530   void visitVAEnd(CallInst &I);
531   void visitVACopy(CallInst &I);
532   void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
533
534   void visitMemIntrinsic(CallInst &I, unsigned Op);
535
536   void visitUserOp1(Instruction &I) {
537     assert(0 && "UserOp1 should not exist at instruction selection time!");
538     abort();
539   }
540   void visitUserOp2(Instruction &I) {
541     assert(0 && "UserOp2 should not exist at instruction selection time!");
542     abort();
543   }
544 };
545 } // end namespace llvm
546
547 SDOperand SelectionDAGLowering::getValue(const Value *V) {
548   SDOperand &N = NodeMap[V];
549   if (N.Val) return N;
550   
551   const Type *VTy = V->getType();
552   MVT::ValueType VT = TLI.getValueType(VTy);
553   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
554     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
555       visit(CE->getOpcode(), *CE);
556       assert(N.Val && "visit didn't populate the ValueMap!");
557       return N;
558     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
559       return N = DAG.getGlobalAddress(GV, VT);
560     } else if (isa<ConstantPointerNull>(C)) {
561       return N = DAG.getConstant(0, TLI.getPointerTy());
562     } else if (isa<UndefValue>(C)) {
563       if (!isa<PackedType>(VTy))
564         return N = DAG.getNode(ISD::UNDEF, VT);
565
566       // Create a VBUILD_VECTOR of undef nodes.
567       const PackedType *PTy = cast<PackedType>(VTy);
568       unsigned NumElements = PTy->getNumElements();
569       MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
570
571       std::vector<SDOperand> Ops;
572       Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
573       
574       // Create a VConstant node with generic Vector type.
575       Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
576       Ops.push_back(DAG.getValueType(PVT));
577       return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
578     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
579       return N = DAG.getConstantFP(CFP->getValue(), VT);
580     } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
581       unsigned NumElements = PTy->getNumElements();
582       MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
583       
584       // Now that we know the number and type of the elements, push a
585       // Constant or ConstantFP node onto the ops list for each element of
586       // the packed constant.
587       std::vector<SDOperand> Ops;
588       if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
589         if (MVT::isFloatingPoint(PVT)) {
590           for (unsigned i = 0; i != NumElements; ++i) {
591             const ConstantFP *El = cast<ConstantFP>(CP->getOperand(i));
592             Ops.push_back(DAG.getConstantFP(El->getValue(), PVT));
593           }
594         } else {
595           for (unsigned i = 0; i != NumElements; ++i) {
596             const ConstantIntegral *El = 
597             cast<ConstantIntegral>(CP->getOperand(i));
598             Ops.push_back(DAG.getConstant(El->getRawValue(), PVT));
599           }
600         }
601       } else {
602         assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
603         SDOperand Op;
604         if (MVT::isFloatingPoint(PVT))
605           Op = DAG.getConstantFP(0, PVT);
606         else
607           Op = DAG.getConstant(0, PVT);
608         Ops.assign(NumElements, Op);
609       }
610       
611       // Create a VBUILD_VECTOR node with generic Vector type.
612       Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
613       Ops.push_back(DAG.getValueType(PVT));
614       return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, Ops);
615     } else {
616       // Canonicalize all constant ints to be unsigned.
617       return N = DAG.getConstant(cast<ConstantIntegral>(C)->getRawValue(),VT);
618     }
619   }
620       
621   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
622     std::map<const AllocaInst*, int>::iterator SI =
623     FuncInfo.StaticAllocaMap.find(AI);
624     if (SI != FuncInfo.StaticAllocaMap.end())
625       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
626   }
627       
628   std::map<const Value*, unsigned>::const_iterator VMI =
629       FuncInfo.ValueMap.find(V);
630   assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
631   
632   unsigned InReg = VMI->second;
633   
634   // If this type is not legal, make it so now.
635   if (VT == MVT::Vector) {
636     // FIXME: We only handle legal vectors right now.  We need a VBUILD_VECTOR
637     const PackedType *PTy = cast<PackedType>(VTy);
638     unsigned NumElements = PTy->getNumElements();
639     MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
640     MVT::ValueType TVT = MVT::getVectorType(PVT, NumElements);
641     assert(TLI.isTypeLegal(TVT) &&
642            "FIXME: Cannot handle illegal vector types here yet!");
643     VT = TVT;
644   }
645   
646   MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
647   
648   N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
649   if (DestVT < VT) {
650     // Source must be expanded.  This input value is actually coming from the
651     // register pair VMI->second and VMI->second+1.
652     N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
653                     DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
654   } else {
655     if (DestVT > VT) { // Promotion case
656       if (MVT::isFloatingPoint(VT))
657         N = DAG.getNode(ISD::FP_ROUND, VT, N);
658       else
659         N = DAG.getNode(ISD::TRUNCATE, VT, N);
660     }
661   }
662   
663   return N;
664 }
665
666
667 void SelectionDAGLowering::visitRet(ReturnInst &I) {
668   if (I.getNumOperands() == 0) {
669     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
670     return;
671   }
672   std::vector<SDOperand> NewValues;
673   NewValues.push_back(getRoot());
674   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
675     SDOperand RetOp = getValue(I.getOperand(i));
676     
677     // If this is an integer return value, we need to promote it ourselves to
678     // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
679     // than sign/zero.
680     if (MVT::isInteger(RetOp.getValueType()) && 
681         RetOp.getValueType() < MVT::i64) {
682       MVT::ValueType TmpVT;
683       if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
684         TmpVT = TLI.getTypeToTransformTo(MVT::i32);
685       else
686         TmpVT = MVT::i32;
687
688       if (I.getOperand(i)->getType()->isSigned())
689         RetOp = DAG.getNode(ISD::SIGN_EXTEND, TmpVT, RetOp);
690       else
691         RetOp = DAG.getNode(ISD::ZERO_EXTEND, TmpVT, RetOp);
692     }
693     NewValues.push_back(RetOp);
694   }
695   DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, NewValues));
696 }
697
698 void SelectionDAGLowering::visitBr(BranchInst &I) {
699   // Update machine-CFG edges.
700   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
701   CurMBB->addSuccessor(Succ0MBB);
702
703   // Figure out which block is immediately after the current one.
704   MachineBasicBlock *NextBlock = 0;
705   MachineFunction::iterator BBI = CurMBB;
706   if (++BBI != CurMBB->getParent()->end())
707     NextBlock = BBI;
708
709   if (I.isUnconditional()) {
710     // If this is not a fall-through branch, emit the branch.
711     if (Succ0MBB != NextBlock)
712       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
713                               DAG.getBasicBlock(Succ0MBB)));
714   } else {
715     MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
716     CurMBB->addSuccessor(Succ1MBB);
717
718     SDOperand Cond = getValue(I.getCondition());
719     if (Succ1MBB == NextBlock) {
720       // If the condition is false, fall through.  This means we should branch
721       // if the condition is true to Succ #0.
722       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
723                               Cond, DAG.getBasicBlock(Succ0MBB)));
724     } else if (Succ0MBB == NextBlock) {
725       // If the condition is true, fall through.  This means we should branch if
726       // the condition is false to Succ #1.  Invert the condition first.
727       SDOperand True = DAG.getConstant(1, Cond.getValueType());
728       Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
729       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(),
730                               Cond, DAG.getBasicBlock(Succ1MBB)));
731     } else {
732       std::vector<SDOperand> Ops;
733       Ops.push_back(getRoot());
734       // If the false case is the current basic block, then this is a self
735       // loop. We do not want to emit "Loop: ... brcond Out; br Loop", as it
736       // adds an extra instruction in the loop.  Instead, invert the
737       // condition and emit "Loop: ... br!cond Loop; br Out. 
738       if (CurMBB == Succ1MBB) {
739         std::swap(Succ0MBB, Succ1MBB);
740         SDOperand True = DAG.getConstant(1, Cond.getValueType());
741         Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
742       }
743       SDOperand True = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
744                                    DAG.getBasicBlock(Succ0MBB));
745       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, True, 
746                               DAG.getBasicBlock(Succ1MBB)));
747     }
748   }
749 }
750
751 /// visitSwitchCase - Emits the necessary code to represent a single node in
752 /// the binary search tree resulting from lowering a switch instruction.
753 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
754   SDOperand SwitchOp = getValue(CB.SwitchV);
755   SDOperand CaseOp = getValue(CB.CaseC);
756   SDOperand Cond = DAG.getSetCC(MVT::i1, SwitchOp, CaseOp, CB.CC);
757   
758   // Set NextBlock to be the MBB immediately after the current one, if any.
759   // This is used to avoid emitting unnecessary branches to the next block.
760   MachineBasicBlock *NextBlock = 0;
761   MachineFunction::iterator BBI = CurMBB;
762   if (++BBI != CurMBB->getParent()->end())
763     NextBlock = BBI;
764   
765   // If the lhs block is the next block, invert the condition so that we can
766   // fall through to the lhs instead of the rhs block.
767   if (CB.LHSBB == NextBlock) {
768     std::swap(CB.LHSBB, CB.RHSBB);
769     SDOperand True = DAG.getConstant(1, Cond.getValueType());
770     Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
771   }
772   SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
773                                  DAG.getBasicBlock(CB.LHSBB));
774   if (CB.RHSBB == NextBlock)
775     DAG.setRoot(BrCond);
776   else
777     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
778                             DAG.getBasicBlock(CB.RHSBB)));
779   // Update successor info
780   CurMBB->addSuccessor(CB.LHSBB);
781   CurMBB->addSuccessor(CB.RHSBB);
782 }
783
784 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
785   // Figure out which block is immediately after the current one.
786   MachineBasicBlock *NextBlock = 0;
787   MachineFunction::iterator BBI = CurMBB;
788   if (++BBI != CurMBB->getParent()->end())
789     NextBlock = BBI;
790   
791   // If there is only the default destination, branch to it if it is not the
792   // next basic block.  Otherwise, just fall through.
793   if (I.getNumOperands() == 2) {
794     // Update machine-CFG edges.
795     MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[I.getDefaultDest()];
796     // If this is not a fall-through branch, emit the branch.
797     if (DefaultMBB != NextBlock)
798       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
799                               DAG.getBasicBlock(DefaultMBB)));
800     return;
801   }
802   
803   // If there are any non-default case statements, create a vector of Cases
804   // representing each one, and sort the vector so that we can efficiently
805   // create a binary search tree from them.
806   std::vector<Case> Cases;
807   for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
808     MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
809     Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
810   }
811   std::sort(Cases.begin(), Cases.end(), CaseCmp());
812   
813   // Get the Value to be switched on and default basic blocks, which will be
814   // inserted into CaseBlock records, representing basic blocks in the binary
815   // search tree.
816   Value *SV = I.getOperand(0);
817   MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
818   
819   // Get the current MachineFunction and LLVM basic block, for use in creating
820   // and inserting new MBBs during the creation of the binary search tree.
821   MachineFunction *CurMF = CurMBB->getParent();
822   const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
823   
824   // Push the initial CaseRec onto the worklist
825   std::vector<CaseRec> CaseVec;
826   CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
827   
828   while (!CaseVec.empty()) {
829     // Grab a record representing a case range to process off the worklist
830     CaseRec CR = CaseVec.back();
831     CaseVec.pop_back();
832     
833     // Size is the number of Cases represented by this range.  If Size is 1,
834     // then we are processing a leaf of the binary search tree.  Otherwise,
835     // we need to pick a pivot, and push left and right ranges onto the 
836     // worklist.
837     unsigned Size = CR.Range.second - CR.Range.first;
838     
839     if (Size == 1) {
840       // Create a CaseBlock record representing a conditional branch to
841       // the Case's target mbb if the value being switched on SV is equal
842       // to C.  Otherwise, branch to default.
843       Constant *C = CR.Range.first->first;
844       MachineBasicBlock *Target = CR.Range.first->second;
845       SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default, 
846                                      CR.CaseBB);
847       // If the MBB representing the leaf node is the current MBB, then just
848       // call visitSwitchCase to emit the code into the current block.
849       // Otherwise, push the CaseBlock onto the vector to be later processed
850       // by SDISel, and insert the node's MBB before the next MBB.
851       if (CR.CaseBB == CurMBB)
852         visitSwitchCase(CB);
853       else {
854         SwitchCases.push_back(CB);
855         CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
856       }
857     } else {
858       // split case range at pivot
859       CaseItr Pivot = CR.Range.first + (Size / 2);
860       CaseRange LHSR(CR.Range.first, Pivot);
861       CaseRange RHSR(Pivot, CR.Range.second);
862       Constant *C = Pivot->first;
863       MachineBasicBlock *RHSBB = 0, *LHSBB = 0;
864       // We know that we branch to the LHS if the Value being switched on is
865       // less than the Pivot value, C.  We use this to optimize our binary 
866       // tree a bit, by recognizing that if SV is greater than or equal to the
867       // LHS's Case Value, and that Case Value is exactly one less than the 
868       // Pivot's Value, then we can branch directly to the LHS's Target,
869       // rather than creating a leaf node for it.
870       if ((LHSR.second - LHSR.first) == 1 &&
871           LHSR.first->first == CR.GE &&
872           cast<ConstantIntegral>(C)->getRawValue() ==
873           (cast<ConstantIntegral>(CR.GE)->getRawValue() + 1ULL)) {
874         LHSBB = LHSR.first->second;
875       } else {
876         LHSBB = new MachineBasicBlock(LLVMBB);
877         CaseVec.push_back(CaseRec(LHSBB,C,CR.GE,LHSR));
878       }
879       // Similar to the optimization above, if the Value being switched on is
880       // known to be less than the Constant CR.LT, and the current Case Value
881       // is CR.LT - 1, then we can branch directly to the target block for
882       // the current Case Value, rather than emitting a RHS leaf node for it.
883       if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
884           cast<ConstantIntegral>(RHSR.first->first)->getRawValue() ==
885           (cast<ConstantIntegral>(CR.LT)->getRawValue() - 1ULL)) {
886         RHSBB = RHSR.first->second;
887       } else {
888         RHSBB = new MachineBasicBlock(LLVMBB);
889         CaseVec.push_back(CaseRec(RHSBB,CR.LT,C,RHSR));
890       }
891       // Create a CaseBlock record representing a conditional branch to
892       // the LHS node if the value being switched on SV is less than C. 
893       // Otherwise, branch to LHS.
894       ISD::CondCode CC = C->getType()->isSigned() ? ISD::SETLT : ISD::SETULT;
895       SelectionDAGISel::CaseBlock CB(CC, SV, C, LHSBB, RHSBB, CR.CaseBB);
896       if (CR.CaseBB == CurMBB)
897         visitSwitchCase(CB);
898       else {
899         SwitchCases.push_back(CB);
900         CurMF->getBasicBlockList().insert(BBI, CR.CaseBB);
901       }
902     }
903   }
904 }
905
906 void SelectionDAGLowering::visitSub(User &I) {
907   // -0.0 - X --> fneg
908   if (I.getType()->isFloatingPoint()) {
909     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
910       if (CFP->isExactlyValue(-0.0)) {
911         SDOperand Op2 = getValue(I.getOperand(1));
912         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
913         return;
914       }
915   }
916   visitBinary(I, ISD::SUB, ISD::FSUB, ISD::VSUB);
917 }
918
919 void SelectionDAGLowering::visitBinary(User &I, unsigned IntOp, unsigned FPOp, 
920                                        unsigned VecOp) {
921   const Type *Ty = I.getType();
922   SDOperand Op1 = getValue(I.getOperand(0));
923   SDOperand Op2 = getValue(I.getOperand(1));
924
925   if (Ty->isIntegral()) {
926     setValue(&I, DAG.getNode(IntOp, Op1.getValueType(), Op1, Op2));
927   } else if (Ty->isFloatingPoint()) {
928     setValue(&I, DAG.getNode(FPOp, Op1.getValueType(), Op1, Op2));
929   } else {
930     const PackedType *PTy = cast<PackedType>(Ty);
931     SDOperand Num = DAG.getConstant(PTy->getNumElements(), MVT::i32);
932     SDOperand Typ = DAG.getValueType(TLI.getValueType(PTy->getElementType()));
933     setValue(&I, DAG.getNode(VecOp, MVT::Vector, Op1, Op2, Num, Typ));
934   }
935 }
936
937 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
938   SDOperand Op1 = getValue(I.getOperand(0));
939   SDOperand Op2 = getValue(I.getOperand(1));
940   
941   Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
942   
943   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
944 }
945
946 void SelectionDAGLowering::visitSetCC(User &I,ISD::CondCode SignedOpcode,
947                                       ISD::CondCode UnsignedOpcode) {
948   SDOperand Op1 = getValue(I.getOperand(0));
949   SDOperand Op2 = getValue(I.getOperand(1));
950   ISD::CondCode Opcode = SignedOpcode;
951   if (I.getOperand(0)->getType()->isUnsigned())
952     Opcode = UnsignedOpcode;
953   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
954 }
955
956 void SelectionDAGLowering::visitSelect(User &I) {
957   SDOperand Cond     = getValue(I.getOperand(0));
958   SDOperand TrueVal  = getValue(I.getOperand(1));
959   SDOperand FalseVal = getValue(I.getOperand(2));
960   setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
961                            TrueVal, FalseVal));
962 }
963
964 void SelectionDAGLowering::visitCast(User &I) {
965   SDOperand N = getValue(I.getOperand(0));
966   MVT::ValueType SrcVT = N.getValueType();
967   MVT::ValueType DestVT = TLI.getValueType(I.getType());
968
969   if (DestVT == MVT::Vector) {
970     // This is a cast to a vector from something else.  This is always a bit
971     // convert.  Get information about the input vector.
972     const PackedType *DestTy = cast<PackedType>(I.getType());
973     MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
974     setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N, 
975                              DAG.getConstant(DestTy->getNumElements(),MVT::i32),
976                              DAG.getValueType(EltVT)));
977   } else if (SrcVT == DestVT) {
978     setValue(&I, N);  // noop cast.
979   } else if (DestVT == MVT::i1) {
980     // Cast to bool is a comparison against zero, not truncation to zero.
981     SDOperand Zero = isInteger(SrcVT) ? DAG.getConstant(0, N.getValueType()) :
982                                        DAG.getConstantFP(0.0, N.getValueType());
983     setValue(&I, DAG.getSetCC(MVT::i1, N, Zero, ISD::SETNE));
984   } else if (isInteger(SrcVT)) {
985     if (isInteger(DestVT)) {        // Int -> Int cast
986       if (DestVT < SrcVT)   // Truncating cast?
987         setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
988       else if (I.getOperand(0)->getType()->isSigned())
989         setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
990       else
991         setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
992     } else if (isFloatingPoint(DestVT)) {           // Int -> FP cast
993       if (I.getOperand(0)->getType()->isSigned())
994         setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
995       else
996         setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
997     } else {
998       assert(0 && "Unknown cast!");
999     }
1000   } else if (isFloatingPoint(SrcVT)) {
1001     if (isFloatingPoint(DestVT)) {  // FP -> FP cast
1002       if (DestVT < SrcVT)   // Rounding cast?
1003         setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1004       else
1005         setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1006     } else if (isInteger(DestVT)) {        // FP -> Int cast.
1007       if (I.getType()->isSigned())
1008         setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1009       else
1010         setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1011     } else {
1012       assert(0 && "Unknown cast!");
1013     }
1014   } else {
1015     assert(SrcVT == MVT::Vector && "Unknown cast!");
1016     assert(DestVT != MVT::Vector && "Casts to vector already handled!");
1017     // This is a cast from a vector to something else.  This is always a bit
1018     // convert.  Get information about the input vector.
1019     setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1020   }
1021 }
1022
1023 void SelectionDAGLowering::visitInsertElement(InsertElementInst &I) {
1024   SDOperand InVec = getValue(I.getOperand(0));
1025   SDOperand InVal = getValue(I.getOperand(1));
1026   SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1027                                 getValue(I.getOperand(2)));
1028
1029   SDOperand Num = *(InVec.Val->op_end()-2);
1030   SDOperand Typ = *(InVec.Val->op_end()-1);
1031   setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1032                            InVec, InVal, InIdx, Num, Typ));
1033 }
1034
1035 void SelectionDAGLowering::visitExtractElement(ExtractElementInst &I) {
1036   SDOperand InVec = getValue(I.getOperand(0));
1037   SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1038                                 getValue(I.getOperand(1)));
1039   SDOperand Typ = *(InVec.Val->op_end()-1);
1040   setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1041                            TLI.getValueType(I.getType()), InVec, InIdx));
1042 }
1043
1044 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1045   SDOperand N = getValue(I.getOperand(0));
1046   const Type *Ty = I.getOperand(0)->getType();
1047   const Type *UIntPtrTy = TD.getIntPtrType();
1048
1049   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1050        OI != E; ++OI) {
1051     Value *Idx = *OI;
1052     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1053       unsigned Field = cast<ConstantUInt>(Idx)->getValue();
1054       if (Field) {
1055         // N = N + Offset
1056         uint64_t Offset = TD.getStructLayout(StTy)->MemberOffsets[Field];
1057         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1058                         getIntPtrConstant(Offset));
1059       }
1060       Ty = StTy->getElementType(Field);
1061     } else {
1062       Ty = cast<SequentialType>(Ty)->getElementType();
1063
1064       // If this is a constant subscript, handle it quickly.
1065       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1066         if (CI->getRawValue() == 0) continue;
1067
1068         uint64_t Offs;
1069         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
1070           Offs = (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
1071         else
1072           Offs = TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
1073         N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1074         continue;
1075       }
1076       
1077       // N = N + Idx * ElementSize;
1078       uint64_t ElementSize = TD.getTypeSize(Ty);
1079       SDOperand IdxN = getValue(Idx);
1080
1081       // If the index is smaller or larger than intptr_t, truncate or extend
1082       // it.
1083       if (IdxN.getValueType() < N.getValueType()) {
1084         if (Idx->getType()->isSigned())
1085           IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1086         else
1087           IdxN = DAG.getNode(ISD::ZERO_EXTEND, N.getValueType(), IdxN);
1088       } else if (IdxN.getValueType() > N.getValueType())
1089         IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1090
1091       // If this is a multiply by a power of two, turn it into a shl
1092       // immediately.  This is a very common case.
1093       if (isPowerOf2_64(ElementSize)) {
1094         unsigned Amt = Log2_64(ElementSize);
1095         IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1096                            DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1097         N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1098         continue;
1099       }
1100       
1101       SDOperand Scale = getIntPtrConstant(ElementSize);
1102       IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1103       N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1104     }
1105   }
1106   setValue(&I, N);
1107 }
1108
1109 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1110   // If this is a fixed sized alloca in the entry block of the function,
1111   // allocate it statically on the stack.
1112   if (FuncInfo.StaticAllocaMap.count(&I))
1113     return;   // getValue will auto-populate this.
1114
1115   const Type *Ty = I.getAllocatedType();
1116   uint64_t TySize = TLI.getTargetData().getTypeSize(Ty);
1117   unsigned Align = std::max((unsigned)TLI.getTargetData().getTypeAlignment(Ty),
1118                             I.getAlignment());
1119
1120   SDOperand AllocSize = getValue(I.getArraySize());
1121   MVT::ValueType IntPtr = TLI.getPointerTy();
1122   if (IntPtr < AllocSize.getValueType())
1123     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1124   else if (IntPtr > AllocSize.getValueType())
1125     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1126
1127   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1128                           getIntPtrConstant(TySize));
1129
1130   // Handle alignment.  If the requested alignment is less than or equal to the
1131   // stack alignment, ignore it and round the size of the allocation up to the
1132   // stack alignment size.  If the size is greater than the stack alignment, we
1133   // note this in the DYNAMIC_STACKALLOC node.
1134   unsigned StackAlign =
1135     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1136   if (Align <= StackAlign) {
1137     Align = 0;
1138     // Add SA-1 to the size.
1139     AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1140                             getIntPtrConstant(StackAlign-1));
1141     // Mask out the low bits for alignment purposes.
1142     AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1143                             getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1144   }
1145
1146   std::vector<MVT::ValueType> VTs;
1147   VTs.push_back(AllocSize.getValueType());
1148   VTs.push_back(MVT::Other);
1149   std::vector<SDOperand> Ops;
1150   Ops.push_back(getRoot());
1151   Ops.push_back(AllocSize);
1152   Ops.push_back(getIntPtrConstant(Align));
1153   SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, Ops);
1154   DAG.setRoot(setValue(&I, DSA).getValue(1));
1155
1156   // Inform the Frame Information that we have just allocated a variable-sized
1157   // object.
1158   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1159 }
1160
1161 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1162   SDOperand Ptr = getValue(I.getOperand(0));
1163
1164   SDOperand Root;
1165   if (I.isVolatile())
1166     Root = getRoot();
1167   else {
1168     // Do not serialize non-volatile loads against each other.
1169     Root = DAG.getRoot();
1170   }
1171
1172   setValue(&I, getLoadFrom(I.getType(), Ptr, DAG.getSrcValue(I.getOperand(0)),
1173                            Root, I.isVolatile()));
1174 }
1175
1176 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1177                                             SDOperand SrcValue, SDOperand Root,
1178                                             bool isVolatile) {
1179   SDOperand L;
1180   if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1181     MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1182     L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr, SrcValue);
1183   } else {
1184     L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SrcValue);
1185   }
1186
1187   if (isVolatile)
1188     DAG.setRoot(L.getValue(1));
1189   else
1190     PendingLoads.push_back(L.getValue(1));
1191   
1192   return L;
1193 }
1194
1195
1196 void SelectionDAGLowering::visitStore(StoreInst &I) {
1197   Value *SrcV = I.getOperand(0);
1198   SDOperand Src = getValue(SrcV);
1199   SDOperand Ptr = getValue(I.getOperand(1));
1200   DAG.setRoot(DAG.getNode(ISD::STORE, MVT::Other, getRoot(), Src, Ptr,
1201                           DAG.getSrcValue(I.getOperand(1))));
1202 }
1203
1204 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1205 /// access memory and has no other side effects at all.
1206 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1207 #define GET_NO_MEMORY_INTRINSICS
1208 #include "llvm/Intrinsics.gen"
1209 #undef GET_NO_MEMORY_INTRINSICS
1210   return false;
1211 }
1212
1213 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1214 /// node.
1215 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I, 
1216                                                 unsigned Intrinsic) {
1217   bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1218   
1219   // Build the operand list.
1220   std::vector<SDOperand> Ops;
1221   if (HasChain)   // If this intrinsic has side-effects, chainify it.
1222     Ops.push_back(getRoot());
1223   
1224   // Add the intrinsic ID as an integer operand.
1225   Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1226
1227   // Add all operands of the call to the operand list.
1228   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1229     SDOperand Op = getValue(I.getOperand(i));
1230     
1231     // If this is a vector type, force it to the right packed type.
1232     if (Op.getValueType() == MVT::Vector) {
1233       const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1234       MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1235       
1236       MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1237       assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1238       Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1239     }
1240     
1241     assert(TLI.isTypeLegal(Op.getValueType()) &&
1242            "Intrinsic uses a non-legal type?");
1243     Ops.push_back(Op);
1244   }
1245
1246   std::vector<MVT::ValueType> VTs;
1247   if (I.getType() != Type::VoidTy) {
1248     MVT::ValueType VT = TLI.getValueType(I.getType());
1249     if (VT == MVT::Vector) {
1250       const PackedType *DestTy = cast<PackedType>(I.getType());
1251       MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1252       
1253       VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1254       assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1255     }
1256     
1257     assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1258     VTs.push_back(VT);
1259   }
1260   if (HasChain)
1261     VTs.push_back(MVT::Other);
1262
1263   // Create the node.
1264   SDOperand Result = DAG.getNode(ISD::INTRINSIC, VTs, Ops);
1265   
1266   if (HasChain)
1267     DAG.setRoot(Result.getValue(Result.Val->getNumValues()-1));
1268   if (I.getType() != Type::VoidTy) {
1269     if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1270       MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1271       Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1272                            DAG.getConstant(PTy->getNumElements(), MVT::i32),
1273                            DAG.getValueType(EVT));
1274     } 
1275     setValue(&I, Result);
1276   }
1277 }
1278
1279 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
1280 /// we want to emit this as a call to a named external function, return the name
1281 /// otherwise lower it and return null.
1282 const char *
1283 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1284   switch (Intrinsic) {
1285   default:
1286     // By default, turn this into a target intrinsic node.
1287     visitTargetIntrinsic(I, Intrinsic);
1288     return 0;
1289   case Intrinsic::vastart:  visitVAStart(I); return 0;
1290   case Intrinsic::vaend:    visitVAEnd(I); return 0;
1291   case Intrinsic::vacopy:   visitVACopy(I); return 0;
1292   case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1293   case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
1294   case Intrinsic::setjmp:
1295     return "_setjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1296     break;
1297   case Intrinsic::longjmp:
1298     return "_longjmp"+!TLI.usesUnderscoreSetJmpLongJmp();
1299     break;
1300   case Intrinsic::memcpy_i32:
1301   case Intrinsic::memcpy_i64:
1302     visitMemIntrinsic(I, ISD::MEMCPY);
1303     return 0;
1304   case Intrinsic::memset_i32:
1305   case Intrinsic::memset_i64:
1306     visitMemIntrinsic(I, ISD::MEMSET);
1307     return 0;
1308   case Intrinsic::memmove_i32:
1309   case Intrinsic::memmove_i64:
1310     visitMemIntrinsic(I, ISD::MEMMOVE);
1311     return 0;
1312     
1313   case Intrinsic::dbg_stoppoint: {
1314     MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1315     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1316     if (DebugInfo && SPI.getContext() && DebugInfo->Verify(SPI.getContext())) {
1317       std::vector<SDOperand> Ops;
1318
1319       Ops.push_back(getRoot());
1320       Ops.push_back(getValue(SPI.getLineValue()));
1321       Ops.push_back(getValue(SPI.getColumnValue()));
1322
1323       DebugInfoDesc *DD = DebugInfo->getDescFor(SPI.getContext());
1324       assert(DD && "Not a debug information descriptor");
1325       CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1326       
1327       Ops.push_back(DAG.getString(CompileUnit->getFileName()));
1328       Ops.push_back(DAG.getString(CompileUnit->getDirectory()));
1329       
1330       DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops));
1331     }
1332
1333     return 0;
1334   }
1335   case Intrinsic::dbg_region_start: {
1336     MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1337     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1338     if (DebugInfo && RSI.getContext() && DebugInfo->Verify(RSI.getContext())) {
1339       std::vector<SDOperand> Ops;
1340
1341       unsigned LabelID = DebugInfo->RecordRegionStart(RSI.getContext());
1342       
1343       Ops.push_back(getRoot());
1344       Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1345
1346       DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1347     }
1348
1349     return 0;
1350   }
1351   case Intrinsic::dbg_region_end: {
1352     MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1353     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1354     if (DebugInfo && REI.getContext() && DebugInfo->Verify(REI.getContext())) {
1355       std::vector<SDOperand> Ops;
1356
1357       unsigned LabelID = DebugInfo->RecordRegionEnd(REI.getContext());
1358       
1359       Ops.push_back(getRoot());
1360       Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1361
1362       DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1363     }
1364
1365     return 0;
1366   }
1367   case Intrinsic::dbg_func_start: {
1368     MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1369     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
1370     if (DebugInfo && FSI.getSubprogram() &&
1371         DebugInfo->Verify(FSI.getSubprogram())) {
1372       std::vector<SDOperand> Ops;
1373
1374       unsigned LabelID = DebugInfo->RecordRegionStart(FSI.getSubprogram());
1375       
1376       Ops.push_back(getRoot());
1377       Ops.push_back(DAG.getConstant(LabelID, MVT::i32));
1378
1379       DAG.setRoot(DAG.getNode(ISD::DEBUG_LABEL, MVT::Other, Ops));
1380     }
1381
1382     return 0;
1383   }
1384   case Intrinsic::dbg_declare: {
1385     MachineDebugInfo *DebugInfo = DAG.getMachineDebugInfo();
1386     DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
1387     if (DebugInfo && DebugInfo->Verify(DI.getVariable())) {
1388       std::vector<SDOperand> Ops;
1389
1390       SDOperand AddressOp  = getValue(DI.getAddress());
1391       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp)) {
1392         DebugInfo->RecordVariable(DI.getVariable(), FI->getIndex());
1393       }
1394     }
1395
1396     return 0;
1397   }
1398     
1399   case Intrinsic::isunordered_f32:
1400   case Intrinsic::isunordered_f64:
1401     setValue(&I, DAG.getSetCC(MVT::i1,getValue(I.getOperand(1)),
1402                               getValue(I.getOperand(2)), ISD::SETUO));
1403     return 0;
1404     
1405   case Intrinsic::sqrt_f32:
1406   case Intrinsic::sqrt_f64:
1407     setValue(&I, DAG.getNode(ISD::FSQRT,
1408                              getValue(I.getOperand(1)).getValueType(),
1409                              getValue(I.getOperand(1))));
1410     return 0;
1411   case Intrinsic::pcmarker: {
1412     SDOperand Tmp = getValue(I.getOperand(1));
1413     DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
1414     return 0;
1415   }
1416   case Intrinsic::readcyclecounter: {
1417     std::vector<MVT::ValueType> VTs;
1418     VTs.push_back(MVT::i64);
1419     VTs.push_back(MVT::Other);
1420     std::vector<SDOperand> Ops;
1421     Ops.push_back(getRoot());
1422     SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER, VTs, Ops);
1423     setValue(&I, Tmp);
1424     DAG.setRoot(Tmp.getValue(1));
1425     return 0;
1426   }
1427   case Intrinsic::bswap_i16:
1428   case Intrinsic::bswap_i32:
1429   case Intrinsic::bswap_i64:
1430     setValue(&I, DAG.getNode(ISD::BSWAP,
1431                              getValue(I.getOperand(1)).getValueType(),
1432                              getValue(I.getOperand(1))));
1433     return 0;
1434   case Intrinsic::cttz_i8:
1435   case Intrinsic::cttz_i16:
1436   case Intrinsic::cttz_i32:
1437   case Intrinsic::cttz_i64:
1438     setValue(&I, DAG.getNode(ISD::CTTZ,
1439                              getValue(I.getOperand(1)).getValueType(),
1440                              getValue(I.getOperand(1))));
1441     return 0;
1442   case Intrinsic::ctlz_i8:
1443   case Intrinsic::ctlz_i16:
1444   case Intrinsic::ctlz_i32:
1445   case Intrinsic::ctlz_i64:
1446     setValue(&I, DAG.getNode(ISD::CTLZ,
1447                              getValue(I.getOperand(1)).getValueType(),
1448                              getValue(I.getOperand(1))));
1449     return 0;
1450   case Intrinsic::ctpop_i8:
1451   case Intrinsic::ctpop_i16:
1452   case Intrinsic::ctpop_i32:
1453   case Intrinsic::ctpop_i64:
1454     setValue(&I, DAG.getNode(ISD::CTPOP,
1455                              getValue(I.getOperand(1)).getValueType(),
1456                              getValue(I.getOperand(1))));
1457     return 0;
1458   case Intrinsic::stacksave: {
1459     std::vector<MVT::ValueType> VTs;
1460     VTs.push_back(TLI.getPointerTy());
1461     VTs.push_back(MVT::Other);
1462     std::vector<SDOperand> Ops;
1463     Ops.push_back(getRoot());
1464     SDOperand Tmp = DAG.getNode(ISD::STACKSAVE, VTs, Ops);
1465     setValue(&I, Tmp);
1466     DAG.setRoot(Tmp.getValue(1));
1467     return 0;
1468   }
1469   case Intrinsic::stackrestore: {
1470     SDOperand Tmp = getValue(I.getOperand(1));
1471     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
1472     return 0;
1473   }
1474   case Intrinsic::prefetch:
1475     // FIXME: Currently discarding prefetches.
1476     return 0;
1477   }
1478 }
1479
1480
1481 void SelectionDAGLowering::visitCall(CallInst &I) {
1482   const char *RenameFn = 0;
1483   if (Function *F = I.getCalledFunction()) {
1484     if (F->isExternal())
1485       if (unsigned IID = F->getIntrinsicID()) {
1486         RenameFn = visitIntrinsicCall(I, IID);
1487         if (!RenameFn)
1488           return;
1489       } else {    // Not an LLVM intrinsic.
1490         const std::string &Name = F->getName();
1491         if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
1492           if (I.getNumOperands() == 3 &&   // Basic sanity checks.
1493               I.getOperand(1)->getType()->isFloatingPoint() &&
1494               I.getType() == I.getOperand(1)->getType() &&
1495               I.getType() == I.getOperand(2)->getType()) {
1496             SDOperand LHS = getValue(I.getOperand(1));
1497             SDOperand RHS = getValue(I.getOperand(2));
1498             setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
1499                                      LHS, RHS));
1500             return;
1501           }
1502         } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
1503           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1504               I.getOperand(1)->getType()->isFloatingPoint() &&
1505               I.getType() == I.getOperand(1)->getType()) {
1506             SDOperand Tmp = getValue(I.getOperand(1));
1507             setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
1508             return;
1509           }
1510         } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
1511           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1512               I.getOperand(1)->getType()->isFloatingPoint() &&
1513               I.getType() == I.getOperand(1)->getType()) {
1514             SDOperand Tmp = getValue(I.getOperand(1));
1515             setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
1516             return;
1517           }
1518         } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
1519           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
1520               I.getOperand(1)->getType()->isFloatingPoint() &&
1521               I.getType() == I.getOperand(1)->getType()) {
1522             SDOperand Tmp = getValue(I.getOperand(1));
1523             setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
1524             return;
1525           }
1526         }
1527       }
1528   } else if (isa<InlineAsm>(I.getOperand(0))) {
1529     visitInlineAsm(I);
1530     return;
1531   }
1532
1533   SDOperand Callee;
1534   if (!RenameFn)
1535     Callee = getValue(I.getOperand(0));
1536   else
1537     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
1538   std::vector<std::pair<SDOperand, const Type*> > Args;
1539   Args.reserve(I.getNumOperands());
1540   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1541     Value *Arg = I.getOperand(i);
1542     SDOperand ArgNode = getValue(Arg);
1543     Args.push_back(std::make_pair(ArgNode, Arg->getType()));
1544   }
1545
1546   const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
1547   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1548
1549   std::pair<SDOperand,SDOperand> Result =
1550     TLI.LowerCallTo(getRoot(), I.getType(), FTy->isVarArg(), I.getCallingConv(),
1551                     I.isTailCall(), Callee, Args, DAG);
1552   if (I.getType() != Type::VoidTy)
1553     setValue(&I, Result.first);
1554   DAG.setRoot(Result.second);
1555 }
1556
1557 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
1558                                         SDOperand &Chain, SDOperand &Flag)const{
1559   SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
1560   Chain = Val.getValue(1);
1561   Flag  = Val.getValue(2);
1562   
1563   // If the result was expanded, copy from the top part.
1564   if (Regs.size() > 1) {
1565     assert(Regs.size() == 2 &&
1566            "Cannot expand to more than 2 elts yet!");
1567     SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
1568     Chain = Val.getValue(1);
1569     Flag  = Val.getValue(2);
1570     if (DAG.getTargetLoweringInfo().isLittleEndian())
1571       return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
1572     else
1573       return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
1574   }
1575
1576   // Otherwise, if the return value was promoted, truncate it to the
1577   // appropriate type.
1578   if (RegVT == ValueVT)
1579     return Val;
1580   
1581   if (MVT::isInteger(RegVT))
1582     return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
1583   else
1584     return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
1585 }
1586
1587 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
1588 /// specified value into the registers specified by this object.  This uses 
1589 /// Chain/Flag as the input and updates them for the output Chain/Flag.
1590 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
1591                                  SDOperand &Chain, SDOperand &Flag) const {
1592   if (Regs.size() == 1) {
1593     // If there is a single register and the types differ, this must be
1594     // a promotion.
1595     if (RegVT != ValueVT) {
1596       if (MVT::isInteger(RegVT))
1597         Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
1598       else
1599         Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
1600     }
1601     Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
1602     Flag = Chain.getValue(1);
1603   } else {
1604     std::vector<unsigned> R(Regs);
1605     if (!DAG.getTargetLoweringInfo().isLittleEndian())
1606       std::reverse(R.begin(), R.end());
1607     
1608     for (unsigned i = 0, e = R.size(); i != e; ++i) {
1609       SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val, 
1610                                    DAG.getConstant(i, MVT::i32));
1611       Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
1612       Flag = Chain.getValue(1);
1613     }
1614   }
1615 }
1616
1617 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
1618 /// operand list.  This adds the code marker and includes the number of 
1619 /// values added into it.
1620 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
1621                                         std::vector<SDOperand> &Ops) const {
1622   Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
1623   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
1624     Ops.push_back(DAG.getRegister(Regs[i], RegVT));
1625 }
1626
1627 /// isAllocatableRegister - If the specified register is safe to allocate, 
1628 /// i.e. it isn't a stack pointer or some other special register, return the
1629 /// register class for the register.  Otherwise, return null.
1630 static const TargetRegisterClass *
1631 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
1632                       const TargetLowering &TLI, const MRegisterInfo *MRI) {
1633   for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
1634        E = MRI->regclass_end(); RCI != E; ++RCI) {
1635     const TargetRegisterClass *RC = *RCI;
1636     // If none of the the value types for this register class are valid, we 
1637     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
1638     bool isLegal = false;
1639     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
1640          I != E; ++I) {
1641       if (TLI.isTypeLegal(*I)) {
1642         isLegal = true;
1643         break;
1644       }
1645     }
1646     
1647     if (!isLegal) continue;
1648     
1649     // NOTE: This isn't ideal.  In particular, this might allocate the
1650     // frame pointer in functions that need it (due to them not being taken
1651     // out of allocation, because a variable sized allocation hasn't been seen
1652     // yet).  This is a slight code pessimization, but should still work.
1653     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
1654          E = RC->allocation_order_end(MF); I != E; ++I)
1655       if (*I == Reg)
1656         return RC;
1657   }
1658   return 0;
1659 }    
1660
1661 RegsForValue SelectionDAGLowering::
1662 GetRegistersForValue(const std::string &ConstrCode,
1663                      MVT::ValueType VT, bool isOutReg, bool isInReg,
1664                      std::set<unsigned> &OutputRegs, 
1665                      std::set<unsigned> &InputRegs) {
1666   std::pair<unsigned, const TargetRegisterClass*> PhysReg = 
1667     TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
1668   std::vector<unsigned> Regs;
1669
1670   unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
1671   MVT::ValueType RegVT;
1672   MVT::ValueType ValueVT = VT;
1673   
1674   if (PhysReg.first) {
1675     if (VT == MVT::Other)
1676       ValueVT = *PhysReg.second->vt_begin();
1677     RegVT = VT;
1678     
1679     // This is a explicit reference to a physical register.
1680     Regs.push_back(PhysReg.first);
1681
1682     // If this is an expanded reference, add the rest of the regs to Regs.
1683     if (NumRegs != 1) {
1684       RegVT = *PhysReg.second->vt_begin();
1685       TargetRegisterClass::iterator I = PhysReg.second->begin();
1686       TargetRegisterClass::iterator E = PhysReg.second->end();
1687       for (; *I != PhysReg.first; ++I)
1688         assert(I != E && "Didn't find reg!"); 
1689       
1690       // Already added the first reg.
1691       --NumRegs; ++I;
1692       for (; NumRegs; --NumRegs, ++I) {
1693         assert(I != E && "Ran out of registers to allocate!");
1694         Regs.push_back(*I);
1695       }
1696     }
1697     return RegsForValue(Regs, RegVT, ValueVT);
1698   }
1699   
1700   // This is a reference to a register class.  Allocate NumRegs consecutive,
1701   // available, registers from the class.
1702   std::vector<unsigned> RegClassRegs =
1703     TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
1704
1705   const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
1706   MachineFunction &MF = *CurMBB->getParent();
1707   unsigned NumAllocated = 0;
1708   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
1709     unsigned Reg = RegClassRegs[i];
1710     // See if this register is available.
1711     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
1712         (isInReg  && InputRegs.count(Reg))) {    // Already used.
1713       // Make sure we find consecutive registers.
1714       NumAllocated = 0;
1715       continue;
1716     }
1717     
1718     // Check to see if this register is allocatable (i.e. don't give out the
1719     // stack pointer).
1720     const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
1721     if (!RC) {
1722       // Make sure we find consecutive registers.
1723       NumAllocated = 0;
1724       continue;
1725     }
1726     
1727     // Okay, this register is good, we can use it.
1728     ++NumAllocated;
1729
1730     // If we allocated enough consecutive   
1731     if (NumAllocated == NumRegs) {
1732       unsigned RegStart = (i-NumAllocated)+1;
1733       unsigned RegEnd   = i+1;
1734       // Mark all of the allocated registers used.
1735       for (unsigned i = RegStart; i != RegEnd; ++i) {
1736         unsigned Reg = RegClassRegs[i];
1737         Regs.push_back(Reg);
1738         if (isOutReg) OutputRegs.insert(Reg);    // Mark reg used.
1739         if (isInReg)  InputRegs.insert(Reg);     // Mark reg used.
1740       }
1741       
1742       return RegsForValue(Regs, *RC->vt_begin(), VT);
1743     }
1744   }
1745   
1746   // Otherwise, we couldn't allocate enough registers for this.
1747   return RegsForValue();
1748 }
1749
1750
1751 /// visitInlineAsm - Handle a call to an InlineAsm object.
1752 ///
1753 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
1754   InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
1755   
1756   SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
1757                                                  MVT::Other);
1758
1759   // Note, we treat inline asms both with and without side-effects as the same.
1760   // If an inline asm doesn't have side effects and doesn't access memory, we
1761   // could not choose to not chain it.
1762   bool hasSideEffects = IA->hasSideEffects();
1763
1764   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
1765   std::vector<MVT::ValueType> ConstraintVTs;
1766   
1767   /// AsmNodeOperands - A list of pairs.  The first element is a register, the
1768   /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
1769   /// if it is a def of that register.
1770   std::vector<SDOperand> AsmNodeOperands;
1771   AsmNodeOperands.push_back(SDOperand());  // reserve space for input chain
1772   AsmNodeOperands.push_back(AsmStr);
1773   
1774   SDOperand Chain = getRoot();
1775   SDOperand Flag;
1776   
1777   // We fully assign registers here at isel time.  This is not optimal, but
1778   // should work.  For register classes that correspond to LLVM classes, we
1779   // could let the LLVM RA do its thing, but we currently don't.  Do a prepass
1780   // over the constraints, collecting fixed registers that we know we can't use.
1781   std::set<unsigned> OutputRegs, InputRegs;
1782   unsigned OpNum = 1;
1783   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1784     assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1785     std::string &ConstraintCode = Constraints[i].Codes[0];
1786     
1787     MVT::ValueType OpVT;
1788
1789     // Compute the value type for each operand and add it to ConstraintVTs.
1790     switch (Constraints[i].Type) {
1791     case InlineAsm::isOutput:
1792       if (!Constraints[i].isIndirectOutput) {
1793         assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1794         OpVT = TLI.getValueType(I.getType());
1795       } else {
1796         const Type *OpTy = I.getOperand(OpNum)->getType();
1797         OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
1798         OpNum++;  // Consumes a call operand.
1799       }
1800       break;
1801     case InlineAsm::isInput:
1802       OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
1803       OpNum++;  // Consumes a call operand.
1804       break;
1805     case InlineAsm::isClobber:
1806       OpVT = MVT::Other;
1807       break;
1808     }
1809     
1810     ConstraintVTs.push_back(OpVT);
1811
1812     if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
1813       continue;  // Not assigned a fixed reg.
1814     
1815     // Build a list of regs that this operand uses.  This always has a single
1816     // element for promoted/expanded operands.
1817     RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
1818                                              false, false,
1819                                              OutputRegs, InputRegs);
1820     
1821     switch (Constraints[i].Type) {
1822     case InlineAsm::isOutput:
1823       // We can't assign any other output to this register.
1824       OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1825       // If this is an early-clobber output, it cannot be assigned to the same
1826       // value as the input reg.
1827       if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1828         InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1829       break;
1830     case InlineAsm::isInput:
1831       // We can't assign any other input to this register.
1832       InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1833       break;
1834     case InlineAsm::isClobber:
1835       // Clobbered regs cannot be used as inputs or outputs.
1836       InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1837       OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
1838       break;
1839     }
1840   }      
1841   
1842   // Loop over all of the inputs, copying the operand values into the
1843   // appropriate registers and processing the output regs.
1844   RegsForValue RetValRegs;
1845   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
1846   OpNum = 1;
1847   
1848   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
1849     assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
1850     std::string &ConstraintCode = Constraints[i].Codes[0];
1851
1852     switch (Constraints[i].Type) {
1853     case InlineAsm::isOutput: {
1854       TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1855       if (ConstraintCode.size() == 1)   // not a physreg name.
1856         CTy = TLI.getConstraintType(ConstraintCode[0]);
1857       
1858       if (CTy == TargetLowering::C_Memory) {
1859         // Memory output.
1860         SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1861         
1862         // Check that the operand (the address to store to) isn't a float.
1863         if (!MVT::isInteger(InOperandVal.getValueType()))
1864           assert(0 && "MATCH FAIL!");
1865         
1866         if (!Constraints[i].isIndirectOutput)
1867           assert(0 && "MATCH FAIL!");
1868
1869         OpNum++;  // Consumes a call operand.
1870         
1871         // Extend/truncate to the right pointer type if needed.
1872         MVT::ValueType PtrType = TLI.getPointerTy();
1873         if (InOperandVal.getValueType() < PtrType)
1874           InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1875         else if (InOperandVal.getValueType() > PtrType)
1876           InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1877         
1878         // Add information to the INLINEASM node to know about this output.
1879         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1880         AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1881         AsmNodeOperands.push_back(InOperandVal);
1882         break;
1883       }
1884
1885       // Otherwise, this is a register output.
1886       assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1887
1888       // If this is an early-clobber output, or if there is an input
1889       // constraint that matches this, we need to reserve the input register
1890       // so no other inputs allocate to it.
1891       bool UsesInputRegister = false;
1892       if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
1893         UsesInputRegister = true;
1894       
1895       // Copy the output from the appropriate register.  Find a register that
1896       // we can use.
1897       RegsForValue Regs =
1898         GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1899                              true, UsesInputRegister, 
1900                              OutputRegs, InputRegs);
1901       assert(!Regs.Regs.empty() && "Couldn't allocate output reg!");
1902
1903       if (!Constraints[i].isIndirectOutput) {
1904         assert(RetValRegs.Regs.empty() &&
1905                "Cannot have multiple output constraints yet!");
1906         assert(I.getType() != Type::VoidTy && "Bad inline asm!");
1907         RetValRegs = Regs;
1908       } else {
1909         IndirectStoresToEmit.push_back(std::make_pair(Regs, 
1910                                                       I.getOperand(OpNum)));
1911         OpNum++;  // Consumes a call operand.
1912       }
1913       
1914       // Add information to the INLINEASM node to know that this register is
1915       // set.
1916       Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
1917       break;
1918     }
1919     case InlineAsm::isInput: {
1920       SDOperand InOperandVal = getValue(I.getOperand(OpNum));
1921       OpNum++;  // Consumes a call operand.
1922       
1923       if (isdigit(ConstraintCode[0])) {    // Matching constraint?
1924         // If this is required to match an output register we have already set,
1925         // just use its register.
1926         unsigned OperandNo = atoi(ConstraintCode.c_str());
1927         
1928         // Scan until we find the definition we already emitted of this operand.
1929         // When we find it, create a RegsForValue operand.
1930         unsigned CurOp = 2;  // The first operand.
1931         for (; OperandNo; --OperandNo) {
1932           // Advance to the next operand.
1933           unsigned NumOps = 
1934             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1935           assert((NumOps & 7) == 2 /*REGDEF*/ &&
1936                  "Skipped past definitions?");
1937           CurOp += (NumOps>>3)+1;
1938         }
1939
1940         unsigned NumOps = 
1941           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
1942         assert((NumOps & 7) == 2 /*REGDEF*/ &&
1943                "Skipped past definitions?");
1944         
1945         // Add NumOps>>3 registers to MatchedRegs.
1946         RegsForValue MatchedRegs;
1947         MatchedRegs.ValueVT = InOperandVal.getValueType();
1948         MatchedRegs.RegVT   = AsmNodeOperands[CurOp+1].getValueType();
1949         for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
1950           unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
1951           MatchedRegs.Regs.push_back(Reg);
1952         }
1953         
1954         // Use the produced MatchedRegs object to 
1955         MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
1956         MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
1957         break;
1958       }
1959       
1960       TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
1961       if (ConstraintCode.size() == 1)   // not a physreg name.
1962         CTy = TLI.getConstraintType(ConstraintCode[0]);
1963         
1964       if (CTy == TargetLowering::C_Other) {
1965         if (!TLI.isOperandValidForConstraint(InOperandVal, ConstraintCode[0]))
1966           assert(0 && "MATCH FAIL!");
1967         
1968         // Add information to the INLINEASM node to know about this input.
1969         unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
1970         AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1971         AsmNodeOperands.push_back(InOperandVal);
1972         break;
1973       } else if (CTy == TargetLowering::C_Memory) {
1974         // Memory input.
1975         
1976         // Check that the operand isn't a float.
1977         if (!MVT::isInteger(InOperandVal.getValueType()))
1978           assert(0 && "MATCH FAIL!");
1979         
1980         // Extend/truncate to the right pointer type if needed.
1981         MVT::ValueType PtrType = TLI.getPointerTy();
1982         if (InOperandVal.getValueType() < PtrType)
1983           InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
1984         else if (InOperandVal.getValueType() > PtrType)
1985           InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
1986
1987         // Add information to the INLINEASM node to know about this input.
1988         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
1989         AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
1990         AsmNodeOperands.push_back(InOperandVal);
1991         break;
1992       }
1993         
1994       assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
1995
1996       // Copy the input into the appropriate registers.
1997       RegsForValue InRegs =
1998         GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
1999                              false, true, OutputRegs, InputRegs);
2000       // FIXME: should be match fail.
2001       assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2002
2003       InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag);
2004       
2005       InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2006       break;
2007     }
2008     case InlineAsm::isClobber: {
2009       RegsForValue ClobberedRegs =
2010         GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2011                              OutputRegs, InputRegs);
2012       // Add the clobbered value to the operand list, so that the register
2013       // allocator is aware that the physreg got clobbered.
2014       if (!ClobberedRegs.Regs.empty())
2015         ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2016       break;
2017     }
2018     }
2019   }
2020   
2021   // Finish up input operands.
2022   AsmNodeOperands[0] = Chain;
2023   if (Flag.Val) AsmNodeOperands.push_back(Flag);
2024   
2025   std::vector<MVT::ValueType> VTs;
2026   VTs.push_back(MVT::Other);
2027   VTs.push_back(MVT::Flag);
2028   Chain = DAG.getNode(ISD::INLINEASM, VTs, AsmNodeOperands);
2029   Flag = Chain.getValue(1);
2030
2031   // If this asm returns a register value, copy the result from that register
2032   // and set it as the value of the call.
2033   if (!RetValRegs.Regs.empty())
2034     setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2035   
2036   std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2037   
2038   // Process indirect outputs, first output all of the flagged copies out of
2039   // physregs.
2040   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2041     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2042     Value *Ptr = IndirectStoresToEmit[i].second;
2043     SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2044     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2045   }
2046   
2047   // Emit the non-flagged stores from the physregs.
2048   std::vector<SDOperand> OutChains;
2049   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2050     OutChains.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain, 
2051                                     StoresToEmit[i].first,
2052                                     getValue(StoresToEmit[i].second),
2053                                     DAG.getSrcValue(StoresToEmit[i].second)));
2054   if (!OutChains.empty())
2055     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains);
2056   DAG.setRoot(Chain);
2057 }
2058
2059
2060 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2061   SDOperand Src = getValue(I.getOperand(0));
2062
2063   MVT::ValueType IntPtr = TLI.getPointerTy();
2064
2065   if (IntPtr < Src.getValueType())
2066     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2067   else if (IntPtr > Src.getValueType())
2068     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2069
2070   // Scale the source by the type size.
2071   uint64_t ElementSize = TD.getTypeSize(I.getType()->getElementType());
2072   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2073                     Src, getIntPtrConstant(ElementSize));
2074
2075   std::vector<std::pair<SDOperand, const Type*> > Args;
2076   Args.push_back(std::make_pair(Src, TLI.getTargetData().getIntPtrType()));
2077
2078   std::pair<SDOperand,SDOperand> Result =
2079     TLI.LowerCallTo(getRoot(), I.getType(), false, CallingConv::C, true,
2080                     DAG.getExternalSymbol("malloc", IntPtr),
2081                     Args, DAG);
2082   setValue(&I, Result.first);  // Pointers always fit in registers
2083   DAG.setRoot(Result.second);
2084 }
2085
2086 void SelectionDAGLowering::visitFree(FreeInst &I) {
2087   std::vector<std::pair<SDOperand, const Type*> > Args;
2088   Args.push_back(std::make_pair(getValue(I.getOperand(0)),
2089                                 TLI.getTargetData().getIntPtrType()));
2090   MVT::ValueType IntPtr = TLI.getPointerTy();
2091   std::pair<SDOperand,SDOperand> Result =
2092     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, CallingConv::C, true,
2093                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2094   DAG.setRoot(Result.second);
2095 }
2096
2097 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2098 // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
2099 // instructions are special in various ways, which require special support to
2100 // insert.  The specified MachineInstr is created but not inserted into any
2101 // basic blocks, and the scheduler passes ownership of it to this method.
2102 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2103                                                        MachineBasicBlock *MBB) {
2104   std::cerr << "If a target marks an instruction with "
2105                "'usesCustomDAGSchedInserter', it must implement "
2106                "TargetLowering::InsertAtEndOfBasicBlock!\n";
2107   abort();
2108   return 0;  
2109 }
2110
2111 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2112   DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(), 
2113                           getValue(I.getOperand(1)), 
2114                           DAG.getSrcValue(I.getOperand(1))));
2115 }
2116
2117 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2118   SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2119                              getValue(I.getOperand(0)),
2120                              DAG.getSrcValue(I.getOperand(0)));
2121   setValue(&I, V);
2122   DAG.setRoot(V.getValue(1));
2123 }
2124
2125 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2126   DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2127                           getValue(I.getOperand(1)), 
2128                           DAG.getSrcValue(I.getOperand(1))));
2129 }
2130
2131 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2132   DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(), 
2133                           getValue(I.getOperand(1)), 
2134                           getValue(I.getOperand(2)),
2135                           DAG.getSrcValue(I.getOperand(1)),
2136                           DAG.getSrcValue(I.getOperand(2))));
2137 }
2138
2139 // It is always conservatively correct for llvm.returnaddress and
2140 // llvm.frameaddress to return 0.
2141 std::pair<SDOperand, SDOperand>
2142 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
2143                                         unsigned Depth, SelectionDAG &DAG) {
2144   return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
2145 }
2146
2147 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
2148   assert(0 && "LowerOperation not implemented for this target!");
2149   abort();
2150   return SDOperand();
2151 }
2152
2153 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
2154                                                  SelectionDAG &DAG) {
2155   assert(0 && "CustomPromoteOperation not implemented for this target!");
2156   abort();
2157   return SDOperand();
2158 }
2159
2160 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
2161   unsigned Depth = (unsigned)cast<ConstantUInt>(I.getOperand(1))->getValue();
2162   std::pair<SDOperand,SDOperand> Result =
2163     TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
2164   setValue(&I, Result.first);
2165   DAG.setRoot(Result.second);
2166 }
2167
2168 /// getMemsetValue - Vectorized representation of the memset value
2169 /// operand.
2170 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
2171                                 SelectionDAG &DAG) {
2172   MVT::ValueType CurVT = VT;
2173   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
2174     uint64_t Val   = C->getValue() & 255;
2175     unsigned Shift = 8;
2176     while (CurVT != MVT::i8) {
2177       Val = (Val << Shift) | Val;
2178       Shift <<= 1;
2179       CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2180     }
2181     return DAG.getConstant(Val, VT);
2182   } else {
2183     Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
2184     unsigned Shift = 8;
2185     while (CurVT != MVT::i8) {
2186       Value =
2187         DAG.getNode(ISD::OR, VT,
2188                     DAG.getNode(ISD::SHL, VT, Value,
2189                                 DAG.getConstant(Shift, MVT::i8)), Value);
2190       Shift <<= 1;
2191       CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
2192     }
2193
2194     return Value;
2195   }
2196 }
2197
2198 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
2199 /// used when a memcpy is turned into a memset when the source is a constant
2200 /// string ptr.
2201 static SDOperand getMemsetStringVal(MVT::ValueType VT,
2202                                     SelectionDAG &DAG, TargetLowering &TLI,
2203                                     std::string &Str, unsigned Offset) {
2204   MVT::ValueType CurVT = VT;
2205   uint64_t Val = 0;
2206   unsigned MSB = getSizeInBits(VT) / 8;
2207   if (TLI.isLittleEndian())
2208     Offset = Offset + MSB - 1;
2209   for (unsigned i = 0; i != MSB; ++i) {
2210     Val = (Val << 8) | Str[Offset];
2211     Offset += TLI.isLittleEndian() ? -1 : 1;
2212   }
2213   return DAG.getConstant(Val, VT);
2214 }
2215
2216 /// getMemBasePlusOffset - Returns base and offset node for the 
2217 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
2218                                       SelectionDAG &DAG, TargetLowering &TLI) {
2219   MVT::ValueType VT = Base.getValueType();
2220   return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
2221 }
2222
2223 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
2224 /// to replace the memset / memcpy is below the threshold. It also returns the
2225 /// types of the sequence of  memory ops to perform memset / memcpy.
2226 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
2227                                      unsigned Limit, uint64_t Size,
2228                                      unsigned Align, TargetLowering &TLI) {
2229   MVT::ValueType VT;
2230
2231   if (TLI.allowsUnalignedMemoryAccesses()) {
2232     VT = MVT::i64;
2233   } else {
2234     switch (Align & 7) {
2235     case 0:
2236       VT = MVT::i64;
2237       break;
2238     case 4:
2239       VT = MVT::i32;
2240       break;
2241     case 2:
2242       VT = MVT::i16;
2243       break;
2244     default:
2245       VT = MVT::i8;
2246       break;
2247     }
2248   }
2249
2250   MVT::ValueType LVT = MVT::i64;
2251   while (!TLI.isTypeLegal(LVT))
2252     LVT = (MVT::ValueType)((unsigned)LVT - 1);
2253   assert(MVT::isInteger(LVT));
2254
2255   if (VT > LVT)
2256     VT = LVT;
2257
2258   unsigned NumMemOps = 0;
2259   while (Size != 0) {
2260     unsigned VTSize = getSizeInBits(VT) / 8;
2261     while (VTSize > Size) {
2262       VT = (MVT::ValueType)((unsigned)VT - 1);
2263       VTSize >>= 1;
2264     }
2265     assert(MVT::isInteger(VT));
2266
2267     if (++NumMemOps > Limit)
2268       return false;
2269     MemOps.push_back(VT);
2270     Size -= VTSize;
2271   }
2272
2273   return true;
2274 }
2275
2276 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
2277   SDOperand Op1 = getValue(I.getOperand(1));
2278   SDOperand Op2 = getValue(I.getOperand(2));
2279   SDOperand Op3 = getValue(I.getOperand(3));
2280   SDOperand Op4 = getValue(I.getOperand(4));
2281   unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
2282   if (Align == 0) Align = 1;
2283
2284   if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
2285     std::vector<MVT::ValueType> MemOps;
2286
2287     // Expand memset / memcpy to a series of load / store ops
2288     // if the size operand falls below a certain threshold.
2289     std::vector<SDOperand> OutChains;
2290     switch (Op) {
2291     default: break;  // Do nothing for now.
2292     case ISD::MEMSET: {
2293       if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
2294                                    Size->getValue(), Align, TLI)) {
2295         unsigned NumMemOps = MemOps.size();
2296         unsigned Offset = 0;
2297         for (unsigned i = 0; i < NumMemOps; i++) {
2298           MVT::ValueType VT = MemOps[i];
2299           unsigned VTSize = getSizeInBits(VT) / 8;
2300           SDOperand Value = getMemsetValue(Op2, VT, DAG);
2301           SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, getRoot(),
2302                                         Value,
2303                                     getMemBasePlusOffset(Op1, Offset, DAG, TLI),
2304                                       DAG.getSrcValue(I.getOperand(1), Offset));
2305           OutChains.push_back(Store);
2306           Offset += VTSize;
2307         }
2308       }
2309       break;
2310     }
2311     case ISD::MEMCPY: {
2312       if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
2313                                    Size->getValue(), Align, TLI)) {
2314         unsigned NumMemOps = MemOps.size();
2315         unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
2316         GlobalAddressSDNode *G = NULL;
2317         std::string Str;
2318         bool CopyFromStr = false;
2319
2320         if (Op2.getOpcode() == ISD::GlobalAddress)
2321           G = cast<GlobalAddressSDNode>(Op2);
2322         else if (Op2.getOpcode() == ISD::ADD &&
2323                  Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
2324                  Op2.getOperand(1).getOpcode() == ISD::Constant) {
2325           G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
2326           SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
2327         }
2328         if (G) {
2329           GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
2330           if (GV) {
2331             Str = GV->getStringValue(false);
2332             if (!Str.empty()) {
2333               CopyFromStr = true;
2334               SrcOff += SrcDelta;
2335             }
2336           }
2337         }
2338
2339         for (unsigned i = 0; i < NumMemOps; i++) {
2340           MVT::ValueType VT = MemOps[i];
2341           unsigned VTSize = getSizeInBits(VT) / 8;
2342           SDOperand Value, Chain, Store;
2343
2344           if (CopyFromStr) {
2345             Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
2346             Chain = getRoot();
2347             Store =
2348               DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2349                           getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2350                           DAG.getSrcValue(I.getOperand(1), DstOff));
2351           } else {
2352             Value = DAG.getLoad(VT, getRoot(),
2353                         getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
2354                         DAG.getSrcValue(I.getOperand(2), SrcOff));
2355             Chain = Value.getValue(1);
2356             Store =
2357               DAG.getNode(ISD::STORE, MVT::Other, Chain, Value,
2358                           getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
2359                           DAG.getSrcValue(I.getOperand(1), DstOff));
2360           }
2361           OutChains.push_back(Store);
2362           SrcOff += VTSize;
2363           DstOff += VTSize;
2364         }
2365       }
2366       break;
2367     }
2368     }
2369
2370     if (!OutChains.empty()) {
2371       DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains));
2372       return;
2373     }
2374   }
2375
2376   std::vector<SDOperand> Ops;
2377   Ops.push_back(getRoot());
2378   Ops.push_back(Op1);
2379   Ops.push_back(Op2);
2380   Ops.push_back(Op3);
2381   Ops.push_back(Op4);
2382   DAG.setRoot(DAG.getNode(Op, MVT::Other, Ops));
2383 }
2384
2385 //===----------------------------------------------------------------------===//
2386 // SelectionDAGISel code
2387 //===----------------------------------------------------------------------===//
2388
2389 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
2390   return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
2391 }
2392
2393 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
2394   // FIXME: we only modify the CFG to split critical edges.  This
2395   // updates dom and loop info.
2396 }
2397
2398
2399 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
2400 /// casting to the type of GEPI.
2401 static Value *InsertGEPComputeCode(Value *&V, BasicBlock *BB, Instruction *GEPI,
2402                                    Value *Ptr, Value *PtrOffset) {
2403   if (V) return V;   // Already computed.
2404   
2405   BasicBlock::iterator InsertPt;
2406   if (BB == GEPI->getParent()) {
2407     // If insert into the GEP's block, insert right after the GEP.
2408     InsertPt = GEPI;
2409     ++InsertPt;
2410   } else {
2411     // Otherwise, insert at the top of BB, after any PHI nodes
2412     InsertPt = BB->begin();
2413     while (isa<PHINode>(InsertPt)) ++InsertPt;
2414   }
2415   
2416   // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
2417   // BB so that there is only one value live across basic blocks (the cast 
2418   // operand).
2419   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
2420     if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
2421       Ptr = new CastInst(CI->getOperand(0), CI->getType(), "", InsertPt);
2422   
2423   // Add the offset, cast it to the right type.
2424   Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
2425   Ptr = new CastInst(Ptr, GEPI->getType(), "", InsertPt);
2426   return V = Ptr;
2427 }
2428
2429
2430 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
2431 /// selection, we want to be a bit careful about some things.  In particular, if
2432 /// we have a GEP instruction that is used in a different block than it is
2433 /// defined, the addressing expression of the GEP cannot be folded into loads or
2434 /// stores that use it.  In this case, decompose the GEP and move constant
2435 /// indices into blocks that use it.
2436 static void OptimizeGEPExpression(GetElementPtrInst *GEPI,
2437                                   const TargetData &TD) {
2438   // If this GEP is only used inside the block it is defined in, there is no
2439   // need to rewrite it.
2440   bool isUsedOutsideDefBB = false;
2441   BasicBlock *DefBB = GEPI->getParent();
2442   for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end(); 
2443        UI != E; ++UI) {
2444     if (cast<Instruction>(*UI)->getParent() != DefBB) {
2445       isUsedOutsideDefBB = true;
2446       break;
2447     }
2448   }
2449   if (!isUsedOutsideDefBB) return;
2450
2451   // If this GEP has no non-zero constant indices, there is nothing we can do,
2452   // ignore it.
2453   bool hasConstantIndex = false;
2454   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2455        E = GEPI->op_end(); OI != E; ++OI) {
2456     if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI))
2457       if (CI->getRawValue()) {
2458         hasConstantIndex = true;
2459         break;
2460       }
2461   }
2462   // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
2463   if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0))) return;
2464   
2465   // Otherwise, decompose the GEP instruction into multiplies and adds.  Sum the
2466   // constant offset (which we now know is non-zero) and deal with it later.
2467   uint64_t ConstantOffset = 0;
2468   const Type *UIntPtrTy = TD.getIntPtrType();
2469   Value *Ptr = new CastInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
2470   const Type *Ty = GEPI->getOperand(0)->getType();
2471
2472   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
2473        E = GEPI->op_end(); OI != E; ++OI) {
2474     Value *Idx = *OI;
2475     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2476       unsigned Field = cast<ConstantUInt>(Idx)->getValue();
2477       if (Field)
2478         ConstantOffset += TD.getStructLayout(StTy)->MemberOffsets[Field];
2479       Ty = StTy->getElementType(Field);
2480     } else {
2481       Ty = cast<SequentialType>(Ty)->getElementType();
2482
2483       // Handle constant subscripts.
2484       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2485         if (CI->getRawValue() == 0) continue;
2486         
2487         if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(CI))
2488           ConstantOffset += (int64_t)TD.getTypeSize(Ty)*CSI->getValue();
2489         else
2490           ConstantOffset+=TD.getTypeSize(Ty)*cast<ConstantUInt>(CI)->getValue();
2491         continue;
2492       }
2493       
2494       // Ptr = Ptr + Idx * ElementSize;
2495       
2496       // Cast Idx to UIntPtrTy if needed.
2497       Idx = new CastInst(Idx, UIntPtrTy, "", GEPI);
2498       
2499       uint64_t ElementSize = TD.getTypeSize(Ty);
2500       // Mask off bits that should not be set.
2501       ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2502       Constant *SizeCst = ConstantUInt::get(UIntPtrTy, ElementSize);
2503
2504       // Multiply by the element size and add to the base.
2505       Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
2506       Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
2507     }
2508   }
2509   
2510   // Make sure that the offset fits in uintptr_t.
2511   ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
2512   Constant *PtrOffset = ConstantUInt::get(UIntPtrTy, ConstantOffset);
2513   
2514   // Okay, we have now emitted all of the variable index parts to the BB that
2515   // the GEP is defined in.  Loop over all of the using instructions, inserting
2516   // an "add Ptr, ConstantOffset" into each block that uses it and update the
2517   // instruction to use the newly computed value, making GEPI dead.  When the
2518   // user is a load or store instruction address, we emit the add into the user
2519   // block, otherwise we use a canonical version right next to the gep (these 
2520   // won't be foldable as addresses, so we might as well share the computation).
2521   
2522   std::map<BasicBlock*,Value*> InsertedExprs;
2523   while (!GEPI->use_empty()) {
2524     Instruction *User = cast<Instruction>(GEPI->use_back());
2525
2526     // If this use is not foldable into the addressing mode, use a version 
2527     // emitted in the GEP block.
2528     Value *NewVal;
2529     if (!isa<LoadInst>(User) &&
2530         (!isa<StoreInst>(User) || User->getOperand(0) == GEPI)) {
2531       NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI, 
2532                                     Ptr, PtrOffset);
2533     } else {
2534       // Otherwise, insert the code in the User's block so it can be folded into
2535       // any users in that block.
2536       NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()], 
2537                                     User->getParent(), GEPI, 
2538                                     Ptr, PtrOffset);
2539     }
2540     User->replaceUsesOfWith(GEPI, NewVal);
2541   }
2542   
2543   // Finally, the GEP is dead, remove it.
2544   GEPI->eraseFromParent();
2545 }
2546
2547 bool SelectionDAGISel::runOnFunction(Function &Fn) {
2548   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
2549   RegMap = MF.getSSARegMap();
2550   DEBUG(std::cerr << "\n\n\n=== " << Fn.getName() << "\n");
2551
2552   // First, split all critical edges for PHI nodes with incoming values that are
2553   // constants, this way the load of the constant into a vreg will not be placed
2554   // into MBBs that are used some other way.
2555   //
2556   // In this pass we also look for GEP instructions that are used across basic
2557   // blocks and rewrites them to improve basic-block-at-a-time selection.
2558   // 
2559   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
2560     PHINode *PN;
2561     BasicBlock::iterator BBI;
2562     for (BBI = BB->begin(); (PN = dyn_cast<PHINode>(BBI)); ++BBI)
2563       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
2564         if (isa<Constant>(PN->getIncomingValue(i)))
2565           SplitCriticalEdge(PN->getIncomingBlock(i), BB);
2566     
2567     for (BasicBlock::iterator E = BB->end(); BBI != E; )
2568       if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(BBI++))
2569         OptimizeGEPExpression(GEPI, TLI.getTargetData());
2570   }
2571   
2572   FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
2573
2574   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
2575     SelectBasicBlock(I, MF, FuncInfo);
2576
2577   return true;
2578 }
2579
2580
2581 SDOperand SelectionDAGISel::
2582 CopyValueToVirtualRegister(SelectionDAGLowering &SDL, Value *V, unsigned Reg) {
2583   SDOperand Op = SDL.getValue(V);
2584   assert((Op.getOpcode() != ISD::CopyFromReg ||
2585           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
2586          "Copy from a reg to the same reg!");
2587   
2588   // If this type is not legal, we must make sure to not create an invalid
2589   // register use.
2590   MVT::ValueType SrcVT = Op.getValueType();
2591   MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
2592   SelectionDAG &DAG = SDL.DAG;
2593   if (SrcVT == DestVT) {
2594     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2595   } else if (SrcVT == MVT::Vector) {
2596     // FIXME: THIS DOES NOT SUPPORT PROMOTED/EXPANDED ELEMENTS!
2597
2598     // Figure out the right, legal destination reg to copy into.
2599     const PackedType *PTy = cast<PackedType>(V->getType());
2600     unsigned NumElts = PTy->getNumElements();
2601     MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
2602     
2603     unsigned NumVectorRegs = 1;
2604
2605     // Divide the input until we get to a supported size.  This will always
2606     // end with a scalar if the target doesn't support vectors.
2607     while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
2608       NumElts >>= 1;
2609       NumVectorRegs <<= 1;
2610     }
2611     
2612     MVT::ValueType VT;
2613     if (NumElts == 1)
2614       VT = EltTy;
2615     else
2616       VT = getVectorType(EltTy, NumElts);
2617     
2618     // FIXME: THIS ASSUMES THAT THE INPUT VECTOR WILL BE LEGAL!
2619     Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
2620     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2621   } else if (SrcVT < DestVT) {
2622     // The src value is promoted to the register.
2623     if (MVT::isFloatingPoint(SrcVT))
2624       Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
2625     else
2626       Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
2627     return DAG.getCopyToReg(SDL.getRoot(), Reg, Op);
2628   } else  {
2629     // The src value is expanded into multiple registers.
2630     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2631                                Op, DAG.getConstant(0, MVT::i32));
2632     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
2633                                Op, DAG.getConstant(1, MVT::i32));
2634     Op = DAG.getCopyToReg(SDL.getRoot(), Reg, Lo);
2635     return DAG.getCopyToReg(Op, Reg+1, Hi);
2636   }
2637 }
2638
2639 void SelectionDAGISel::
2640 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
2641                std::vector<SDOperand> &UnorderedChains) {
2642   // If this is the entry block, emit arguments.
2643   Function &F = *BB->getParent();
2644   FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
2645   SDOperand OldRoot = SDL.DAG.getRoot();
2646   std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
2647
2648   unsigned a = 0;
2649   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
2650        AI != E; ++AI, ++a)
2651     if (!AI->use_empty()) {
2652       SDL.setValue(AI, Args[a]);
2653       
2654       // If this argument is live outside of the entry block, insert a copy from
2655       // whereever we got it to the vreg that other BB's will reference it as.
2656       if (FuncInfo.ValueMap.count(AI)) {
2657         SDOperand Copy =
2658           CopyValueToVirtualRegister(SDL, AI, FuncInfo.ValueMap[AI]);
2659         UnorderedChains.push_back(Copy);
2660       }
2661     }
2662
2663   // Next, if the function has live ins that need to be copied into vregs,
2664   // emit the copies now, into the top of the block.
2665   MachineFunction &MF = SDL.DAG.getMachineFunction();
2666   if (MF.livein_begin() != MF.livein_end()) {
2667     SSARegMap *RegMap = MF.getSSARegMap();
2668     const MRegisterInfo &MRI = *MF.getTarget().getRegisterInfo();
2669     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
2670          E = MF.livein_end(); LI != E; ++LI)
2671       if (LI->second)
2672         MRI.copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
2673                          LI->first, RegMap->getRegClass(LI->second));
2674   }
2675     
2676   // Finally, if the target has anything special to do, allow it to do so.
2677   EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
2678 }
2679
2680
2681 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
2682        std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
2683                                          FunctionLoweringInfo &FuncInfo) {
2684   SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
2685
2686   std::vector<SDOperand> UnorderedChains;
2687
2688   // Lower any arguments needed in this block if this is the entry block.
2689   if (LLVMBB == &LLVMBB->getParent()->front())
2690     LowerArguments(LLVMBB, SDL, UnorderedChains);
2691
2692   BB = FuncInfo.MBBMap[LLVMBB];
2693   SDL.setCurrentBasicBlock(BB);
2694
2695   // Lower all of the non-terminator instructions.
2696   for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
2697        I != E; ++I)
2698     SDL.visit(*I);
2699   
2700   // Ensure that all instructions which are used outside of their defining
2701   // blocks are available as virtual registers.
2702   for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
2703     if (!I->use_empty() && !isa<PHINode>(I)) {
2704       std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
2705       if (VMI != FuncInfo.ValueMap.end())
2706         UnorderedChains.push_back(
2707                            CopyValueToVirtualRegister(SDL, I, VMI->second));
2708     }
2709
2710   // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
2711   // ensure constants are generated when needed.  Remember the virtual registers
2712   // that need to be added to the Machine PHI nodes as input.  We cannot just
2713   // directly add them, because expansion might result in multiple MBB's for one
2714   // BB.  As such, the start of the BB might correspond to a different MBB than
2715   // the end.
2716   //
2717
2718   // Emit constants only once even if used by multiple PHI nodes.
2719   std::map<Constant*, unsigned> ConstantsOut;
2720
2721   // Check successor nodes PHI nodes that expect a constant to be available from
2722   // this block.
2723   TerminatorInst *TI = LLVMBB->getTerminator();
2724   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
2725     BasicBlock *SuccBB = TI->getSuccessor(succ);
2726     MachineBasicBlock::iterator MBBI = FuncInfo.MBBMap[SuccBB]->begin();
2727     PHINode *PN;
2728
2729     // At this point we know that there is a 1-1 correspondence between LLVM PHI
2730     // nodes and Machine PHI nodes, but the incoming operands have not been
2731     // emitted yet.
2732     for (BasicBlock::iterator I = SuccBB->begin();
2733          (PN = dyn_cast<PHINode>(I)); ++I)
2734       if (!PN->use_empty()) {
2735         unsigned Reg;
2736         Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
2737         if (Constant *C = dyn_cast<Constant>(PHIOp)) {
2738           unsigned &RegOut = ConstantsOut[C];
2739           if (RegOut == 0) {
2740             RegOut = FuncInfo.CreateRegForValue(C);
2741             UnorderedChains.push_back(
2742                              CopyValueToVirtualRegister(SDL, C, RegOut));
2743           }
2744           Reg = RegOut;
2745         } else {
2746           Reg = FuncInfo.ValueMap[PHIOp];
2747           if (Reg == 0) {
2748             assert(isa<AllocaInst>(PHIOp) &&
2749                    FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
2750                    "Didn't codegen value into a register!??");
2751             Reg = FuncInfo.CreateRegForValue(PHIOp);
2752             UnorderedChains.push_back(
2753                              CopyValueToVirtualRegister(SDL, PHIOp, Reg));
2754           }
2755         }
2756
2757         // Remember that this register needs to added to the machine PHI node as
2758         // the input for this MBB.
2759         unsigned NumElements =
2760           TLI.getNumElements(TLI.getValueType(PN->getType()));
2761         for (unsigned i = 0, e = NumElements; i != e; ++i)
2762           PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
2763       }
2764   }
2765   ConstantsOut.clear();
2766
2767   // Turn all of the unordered chains into one factored node.
2768   if (!UnorderedChains.empty()) {
2769     SDOperand Root = SDL.getRoot();
2770     if (Root.getOpcode() != ISD::EntryToken) {
2771       unsigned i = 0, e = UnorderedChains.size();
2772       for (; i != e; ++i) {
2773         assert(UnorderedChains[i].Val->getNumOperands() > 1);
2774         if (UnorderedChains[i].Val->getOperand(0) == Root)
2775           break;  // Don't add the root if we already indirectly depend on it.
2776       }
2777         
2778       if (i == e)
2779         UnorderedChains.push_back(Root);
2780     }
2781     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, UnorderedChains));
2782   }
2783
2784   // Lower the terminator after the copies are emitted.
2785   SDL.visit(*LLVMBB->getTerminator());
2786
2787   // Copy over any CaseBlock records that may now exist due to SwitchInst
2788   // lowering.
2789   SwitchCases.clear();
2790   SwitchCases = SDL.SwitchCases;
2791   
2792   // Make sure the root of the DAG is up-to-date.
2793   DAG.setRoot(SDL.getRoot());
2794 }
2795
2796 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
2797   // Run the DAG combiner in pre-legalize mode.
2798   DAG.Combine(false);
2799   
2800   DEBUG(std::cerr << "Lowered selection DAG:\n");
2801   DEBUG(DAG.dump());
2802   
2803   // Second step, hack on the DAG until it only uses operations and types that
2804   // the target supports.
2805   DAG.Legalize();
2806   
2807   DEBUG(std::cerr << "Legalized selection DAG:\n");
2808   DEBUG(DAG.dump());
2809   
2810   // Run the DAG combiner in post-legalize mode.
2811   DAG.Combine(true);
2812   
2813   if (ViewISelDAGs) DAG.viewGraph();
2814   
2815   // Third, instruction select all of the operations to machine code, adding the
2816   // code to the MachineBasicBlock.
2817   InstructionSelectBasicBlock(DAG);
2818   
2819   DEBUG(std::cerr << "Selected machine code:\n");
2820   DEBUG(BB->dump());
2821 }  
2822
2823 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
2824                                         FunctionLoweringInfo &FuncInfo) {
2825   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
2826   {
2827     SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2828     CurDAG = &DAG;
2829   
2830     // First step, lower LLVM code to some DAG.  This DAG may use operations and
2831     // types that are not supported by the target.
2832     BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
2833
2834     // Second step, emit the lowered DAG as machine code.
2835     CodeGenAndEmitDAG(DAG);
2836   }
2837   
2838   // Next, now that we know what the last MBB the LLVM BB expanded is, update
2839   // PHI nodes in successors.
2840   if (SwitchCases.empty()) {
2841     for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
2842       MachineInstr *PHI = PHINodesToUpdate[i].first;
2843       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2844              "This is not a machine PHI node that we are updating!");
2845       PHI->addRegOperand(PHINodesToUpdate[i].second);
2846       PHI->addMachineBasicBlockOperand(BB);
2847     }
2848     return;
2849   }
2850   
2851   // If we generated any switch lowering information, build and codegen any
2852   // additional DAGs necessary.
2853   for(unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
2854     SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineDebugInfo>());
2855     CurDAG = &SDAG;
2856     SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
2857     // Set the current basic block to the mbb we wish to insert the code into
2858     BB = SwitchCases[i].ThisBB;
2859     SDL.setCurrentBasicBlock(BB);
2860     // Emit the code
2861     SDL.visitSwitchCase(SwitchCases[i]);
2862     SDAG.setRoot(SDL.getRoot());
2863     CodeGenAndEmitDAG(SDAG);
2864     // Iterate over the phi nodes, if there is a phi node in a successor of this
2865     // block (for instance, the default block), then add a pair of operands to
2866     // the phi node for this block, as if we were coming from the original
2867     // BB before switch expansion.
2868     for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
2869       MachineInstr *PHI = PHINodesToUpdate[pi].first;
2870       MachineBasicBlock *PHIBB = PHI->getParent();
2871       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
2872              "This is not a machine PHI node that we are updating!");
2873       if (PHIBB == SwitchCases[i].LHSBB || PHIBB == SwitchCases[i].RHSBB) {
2874         PHI->addRegOperand(PHINodesToUpdate[pi].second);
2875         PHI->addMachineBasicBlockOperand(BB);
2876       }
2877     }
2878   }
2879 }
2880
2881 //===----------------------------------------------------------------------===//
2882 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
2883 /// target node in the graph.
2884 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
2885   if (ViewSchedDAGs) DAG.viewGraph();
2886   ScheduleDAG *SL = NULL;
2887
2888   switch (ISHeuristic) {
2889   default: assert(0 && "Unrecognized scheduling heuristic");
2890   case defaultScheduling:
2891     if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
2892       SL = createSimpleDAGScheduler(noScheduling, DAG, BB);
2893     else /* TargetLowering::SchedulingForRegPressure */
2894       SL = createBURRListDAGScheduler(DAG, BB);
2895     break;
2896   case noScheduling:
2897     SL = createBFS_DAGScheduler(DAG, BB);
2898     break;
2899   case simpleScheduling:
2900     SL = createSimpleDAGScheduler(false, DAG, BB);
2901     break;
2902   case simpleNoItinScheduling:
2903     SL = createSimpleDAGScheduler(true, DAG, BB);
2904     break;
2905   case listSchedulingBURR:
2906     SL = createBURRListDAGScheduler(DAG, BB);
2907     break;
2908   case listSchedulingTD:
2909     SL = createTDListDAGScheduler(DAG, BB, CreateTargetHazardRecognizer());
2910     break;
2911   }
2912   BB = SL->Run();
2913   delete SL;
2914 }
2915
2916 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
2917   return new HazardRecognizer();
2918 }
2919
2920 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2921 /// by tblgen.  Others should not call it.
2922 void SelectionDAGISel::
2923 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
2924   std::vector<SDOperand> InOps;
2925   std::swap(InOps, Ops);
2926
2927   Ops.push_back(InOps[0]);  // input chain.
2928   Ops.push_back(InOps[1]);  // input asm string.
2929
2930   const char *AsmStr = cast<ExternalSymbolSDNode>(InOps[1])->getSymbol();
2931   unsigned i = 2, e = InOps.size();
2932   if (InOps[e-1].getValueType() == MVT::Flag)
2933     --e;  // Don't process a flag operand if it is here.
2934   
2935   while (i != e) {
2936     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
2937     if ((Flags & 7) != 4 /*MEM*/) {
2938       // Just skip over this operand, copying the operands verbatim.
2939       Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
2940       i += (Flags >> 3) + 1;
2941     } else {
2942       assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
2943       // Otherwise, this is a memory operand.  Ask the target to select it.
2944       std::vector<SDOperand> SelOps;
2945       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
2946         std::cerr << "Could not match memory address.  Inline asm failure!\n";
2947         exit(1);
2948       }
2949       
2950       // Add this to the output node.
2951       Ops.push_back(DAG.getConstant(4/*MEM*/ | (SelOps.size() << 3), MVT::i32));
2952       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2953       i += 2;
2954     }
2955   }
2956   
2957   // Add the flag input back if present.
2958   if (e != InOps.size())
2959     Ops.push_back(InOps.back());
2960 }