Propagate changes from my local tree. This patch includes:
[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/Analysis/AliasAnalysis.h"
16 #include "llvm/CodeGen/SelectionDAGISel.h"
17 #include "llvm/CodeGen/ScheduleDAG.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineJumpTableInfo.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/SchedulerRegistry.h"
33 #include "llvm/CodeGen/SelectionDAG.h"
34 #include "llvm/CodeGen/SSARegMap.h"
35 #include "llvm/Target/MRegisterInfo.h"
36 #include "llvm/Target/TargetAsmInfo.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetFrameInfo.h"
39 #include "llvm/Target/TargetInstrInfo.h"
40 #include "llvm/Target/TargetLowering.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Support/MathExtras.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/Compiler.h"
47 #include <algorithm>
48 using namespace llvm;
49
50 #ifndef NDEBUG
51 static cl::opt<bool>
52 ViewISelDAGs("view-isel-dags", cl::Hidden,
53           cl::desc("Pop up a window to show isel dags as they are selected"));
54 static cl::opt<bool>
55 ViewSchedDAGs("view-sched-dags", cl::Hidden,
56           cl::desc("Pop up a window to show sched dags as they are processed"));
57 #else
58 static const bool ViewISelDAGs = 0, ViewSchedDAGs = 0;
59 #endif
60
61
62 //===---------------------------------------------------------------------===//
63 ///
64 /// RegisterScheduler class - Track the registration of instruction schedulers.
65 ///
66 //===---------------------------------------------------------------------===//
67 MachinePassRegistry RegisterScheduler::Registry;
68
69 //===---------------------------------------------------------------------===//
70 ///
71 /// ISHeuristic command line option for instruction schedulers.
72 ///
73 //===---------------------------------------------------------------------===//
74 namespace {
75   cl::opt<RegisterScheduler::FunctionPassCtor, false,
76           RegisterPassParser<RegisterScheduler> >
77   ISHeuristic("sched",
78               cl::init(&createDefaultScheduler),
79               cl::desc("Instruction schedulers available:"));
80
81   static RegisterScheduler
82   defaultListDAGScheduler("default", "  Best scheduler for the target",
83                           createDefaultScheduler);
84 } // namespace
85
86 namespace {
87   /// RegsForValue - This struct represents the physical registers that a
88   /// particular value is assigned and the type information about the value.
89   /// This is needed because values can be promoted into larger registers and
90   /// expanded into multiple smaller registers than the value.
91   struct VISIBILITY_HIDDEN RegsForValue {
92     /// Regs - This list hold the register (for legal and promoted values)
93     /// or register set (for expanded values) that the value should be assigned
94     /// to.
95     std::vector<unsigned> Regs;
96     
97     /// RegVT - The value type of each register.
98     ///
99     MVT::ValueType RegVT;
100     
101     /// ValueVT - The value type of the LLVM value, which may be promoted from
102     /// RegVT or made from merging the two expanded parts.
103     MVT::ValueType ValueVT;
104     
105     RegsForValue() : RegVT(MVT::Other), ValueVT(MVT::Other) {}
106     
107     RegsForValue(unsigned Reg, MVT::ValueType regvt, MVT::ValueType valuevt)
108       : RegVT(regvt), ValueVT(valuevt) {
109         Regs.push_back(Reg);
110     }
111     RegsForValue(const std::vector<unsigned> &regs, 
112                  MVT::ValueType regvt, MVT::ValueType valuevt)
113       : Regs(regs), RegVT(regvt), ValueVT(valuevt) {
114     }
115     
116     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
117     /// this value and returns the result as a ValueVT value.  This uses 
118     /// Chain/Flag as the input and updates them for the output Chain/Flag.
119     SDOperand getCopyFromRegs(SelectionDAG &DAG,
120                               SDOperand &Chain, SDOperand &Flag) const;
121
122     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
123     /// specified value into the registers specified by this object.  This uses 
124     /// Chain/Flag as the input and updates them for the output Chain/Flag.
125     void getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
126                        SDOperand &Chain, SDOperand &Flag,
127                        MVT::ValueType PtrVT) const;
128     
129     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
130     /// operand list.  This adds the code marker and includes the number of 
131     /// values added into it.
132     void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
133                               std::vector<SDOperand> &Ops) const;
134   };
135 }
136
137 namespace llvm {
138   //===--------------------------------------------------------------------===//
139   /// createDefaultScheduler - This creates an instruction scheduler appropriate
140   /// for the target.
141   ScheduleDAG* createDefaultScheduler(SelectionDAGISel *IS,
142                                       SelectionDAG *DAG,
143                                       MachineBasicBlock *BB) {
144     TargetLowering &TLI = IS->getTargetLowering();
145     
146     if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency) {
147       return createTDListDAGScheduler(IS, DAG, BB);
148     } else {
149       assert(TLI.getSchedulingPreference() ==
150            TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
151       return createBURRListDAGScheduler(IS, DAG, BB);
152     }
153   }
154
155
156   //===--------------------------------------------------------------------===//
157   /// FunctionLoweringInfo - This contains information that is global to a
158   /// function that is used when lowering a region of the function.
159   class FunctionLoweringInfo {
160   public:
161     TargetLowering &TLI;
162     Function &Fn;
163     MachineFunction &MF;
164     SSARegMap *RegMap;
165
166     FunctionLoweringInfo(TargetLowering &TLI, Function &Fn,MachineFunction &MF);
167
168     /// MBBMap - A mapping from LLVM basic blocks to their machine code entry.
169     std::map<const BasicBlock*, MachineBasicBlock *> MBBMap;
170
171     /// ValueMap - Since we emit code for the function a basic block at a time,
172     /// we must remember which virtual registers hold the values for
173     /// cross-basic-block values.
174     std::map<const Value*, unsigned> ValueMap;
175
176     /// StaticAllocaMap - Keep track of frame indices for fixed sized allocas in
177     /// the entry block.  This allows the allocas to be efficiently referenced
178     /// anywhere in the function.
179     std::map<const AllocaInst*, int> StaticAllocaMap;
180
181     unsigned MakeReg(MVT::ValueType VT) {
182       return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
183     }
184     
185     /// isExportedInst - Return true if the specified value is an instruction
186     /// exported from its block.
187     bool isExportedInst(const Value *V) {
188       return ValueMap.count(V);
189     }
190
191     unsigned CreateRegForValue(const Value *V);
192     
193     unsigned InitializeRegForValue(const Value *V) {
194       unsigned &R = ValueMap[V];
195       assert(R == 0 && "Already initialized this value register!");
196       return R = CreateRegForValue(V);
197     }
198   };
199 }
200
201 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
202 /// PHI nodes or outside of the basic block that defines it, or used by a 
203 /// switch instruction, which may expand to multiple basic blocks.
204 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
205   if (isa<PHINode>(I)) return true;
206   BasicBlock *BB = I->getParent();
207   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
208     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
209         // FIXME: Remove switchinst special case.
210         isa<SwitchInst>(*UI))
211       return true;
212   return false;
213 }
214
215 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
216 /// entry block, return true.  This includes arguments used by switches, since
217 /// the switch may expand into multiple basic blocks.
218 static bool isOnlyUsedInEntryBlock(Argument *A) {
219   BasicBlock *Entry = A->getParent()->begin();
220   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
221     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
222       return false;  // Use not in entry block.
223   return true;
224 }
225
226 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli,
227                                            Function &fn, MachineFunction &mf)
228     : TLI(tli), Fn(fn), MF(mf), RegMap(MF.getSSARegMap()) {
229
230   // Create a vreg for each argument register that is not dead and is used
231   // outside of the entry block for the function.
232   for (Function::arg_iterator AI = Fn.arg_begin(), E = Fn.arg_end();
233        AI != E; ++AI)
234     if (!isOnlyUsedInEntryBlock(AI))
235       InitializeRegForValue(AI);
236
237   // Initialize the mapping of values to registers.  This is only set up for
238   // instruction values that are used outside of the block that defines
239   // them.
240   Function::iterator BB = Fn.begin(), EB = Fn.end();
241   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
242     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
243       if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
244         const Type *Ty = AI->getAllocatedType();
245         uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
246         unsigned Align = 
247           std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
248                    AI->getAlignment());
249
250         TySize *= CUI->getZExtValue();   // Get total allocated size.
251         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
252         StaticAllocaMap[AI] =
253           MF.getFrameInfo()->CreateStackObject((unsigned)TySize, Align);
254       }
255
256   for (; BB != EB; ++BB)
257     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
258       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
259         if (!isa<AllocaInst>(I) ||
260             !StaticAllocaMap.count(cast<AllocaInst>(I)))
261           InitializeRegForValue(I);
262
263   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
264   // also creates the initial PHI MachineInstrs, though none of the input
265   // operands are populated.
266   for (BB = Fn.begin(), EB = Fn.end(); BB != EB; ++BB) {
267     MachineBasicBlock *MBB = new MachineBasicBlock(BB);
268     MBBMap[BB] = MBB;
269     MF.getBasicBlockList().push_back(MBB);
270
271     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
272     // appropriate.
273     PHINode *PN;
274     for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
275       if (PN->use_empty()) continue;
276       
277       MVT::ValueType VT = TLI.getValueType(PN->getType());
278       unsigned NumElements;
279       if (VT != MVT::Vector)
280         NumElements = TLI.getNumElements(VT);
281       else {
282         MVT::ValueType VT1,VT2;
283         NumElements = 
284           TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
285                                      VT1, VT2);
286       }
287       unsigned PHIReg = ValueMap[PN];
288       assert(PHIReg && "PHI node does not have an assigned virtual register!");
289       const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
290       for (unsigned i = 0; i != NumElements; ++i)
291         BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
292     }
293   }
294 }
295
296 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
297 /// the correctly promoted or expanded types.  Assign these registers
298 /// consecutive vreg numbers and return the first assigned number.
299 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
300   MVT::ValueType VT = TLI.getValueType(V->getType());
301   
302   // The number of multiples of registers that we need, to, e.g., split up
303   // a <2 x int64> -> 4 x i32 registers.
304   unsigned NumVectorRegs = 1;
305   
306   // If this is a packed type, figure out what type it will decompose into
307   // and how many of the elements it will use.
308   if (VT == MVT::Vector) {
309     const PackedType *PTy = cast<PackedType>(V->getType());
310     unsigned NumElts = PTy->getNumElements();
311     MVT::ValueType EltTy = TLI.getValueType(PTy->getElementType());
312     
313     // Divide the input until we get to a supported size.  This will always
314     // end with a scalar if the target doesn't support vectors.
315     while (NumElts > 1 && !TLI.isTypeLegal(getVectorType(EltTy, NumElts))) {
316       NumElts >>= 1;
317       NumVectorRegs <<= 1;
318     }
319     if (NumElts == 1)
320       VT = EltTy;
321     else
322       VT = getVectorType(EltTy, NumElts);
323   }
324   
325   // The common case is that we will only create one register for this
326   // value.  If we have that case, create and return the virtual register.
327   unsigned NV = TLI.getNumElements(VT);
328   if (NV == 1) {
329     // If we are promoting this value, pick the next largest supported type.
330     MVT::ValueType PromotedType = TLI.getTypeToTransformTo(VT);
331     unsigned Reg = MakeReg(PromotedType);
332     // If this is a vector of supported or promoted types (e.g. 4 x i16),
333     // create all of the registers.
334     for (unsigned i = 1; i != NumVectorRegs; ++i)
335       MakeReg(PromotedType);
336     return Reg;
337   }
338   
339   // If this value is represented with multiple target registers, make sure
340   // to create enough consecutive registers of the right (smaller) type.
341   VT = TLI.getTypeToExpandTo(VT);
342   unsigned R = MakeReg(VT);
343   for (unsigned i = 1; i != NV*NumVectorRegs; ++i)
344     MakeReg(VT);
345   return R;
346 }
347
348 //===----------------------------------------------------------------------===//
349 /// SelectionDAGLowering - This is the common target-independent lowering
350 /// implementation that is parameterized by a TargetLowering object.
351 /// Also, targets can overload any lowering method.
352 ///
353 namespace llvm {
354 class SelectionDAGLowering {
355   MachineBasicBlock *CurMBB;
356
357   std::map<const Value*, SDOperand> NodeMap;
358
359   /// PendingLoads - Loads are not emitted to the program immediately.  We bunch
360   /// them up and then emit token factor nodes when possible.  This allows us to
361   /// get simple disambiguation between loads without worrying about alias
362   /// analysis.
363   std::vector<SDOperand> PendingLoads;
364
365   /// Case - A pair of values to record the Value for a switch case, and the
366   /// case's target basic block.  
367   typedef std::pair<Constant*, MachineBasicBlock*> Case;
368   typedef std::vector<Case>::iterator              CaseItr;
369   typedef std::pair<CaseItr, CaseItr>              CaseRange;
370
371   /// CaseRec - A struct with ctor used in lowering switches to a binary tree
372   /// of conditional branches.
373   struct CaseRec {
374     CaseRec(MachineBasicBlock *bb, Constant *lt, Constant *ge, CaseRange r) :
375     CaseBB(bb), LT(lt), GE(ge), Range(r) {}
376
377     /// CaseBB - The MBB in which to emit the compare and branch
378     MachineBasicBlock *CaseBB;
379     /// LT, GE - If nonzero, we know the current case value must be less-than or
380     /// greater-than-or-equal-to these Constants.
381     Constant *LT;
382     Constant *GE;
383     /// Range - A pair of iterators representing the range of case values to be
384     /// processed at this point in the binary search tree.
385     CaseRange Range;
386   };
387   
388   /// The comparison function for sorting Case values.
389   struct CaseCmp {
390     bool operator () (const Case& C1, const Case& C2) {
391       assert(isa<ConstantInt>(C1.first) && isa<ConstantInt>(C2.first));
392       return cast<const ConstantInt>(C1.first)->getSExtValue() <
393         cast<const ConstantInt>(C2.first)->getSExtValue();
394     }
395   };
396   
397 public:
398   // TLI - This is information that describes the available target features we
399   // need for lowering.  This indicates when operations are unavailable,
400   // implemented with a libcall, etc.
401   TargetLowering &TLI;
402   SelectionDAG &DAG;
403   const TargetData *TD;
404
405   /// SwitchCases - Vector of CaseBlock structures used to communicate
406   /// SwitchInst code generation information.
407   std::vector<SelectionDAGISel::CaseBlock> SwitchCases;
408   SelectionDAGISel::JumpTable JT;
409   
410   /// FuncInfo - Information about the function as a whole.
411   ///
412   FunctionLoweringInfo &FuncInfo;
413
414   SelectionDAGLowering(SelectionDAG &dag, TargetLowering &tli,
415                        FunctionLoweringInfo &funcinfo)
416     : TLI(tli), DAG(dag), TD(DAG.getTarget().getTargetData()),
417       JT(0,0,0,0), FuncInfo(funcinfo) {
418   }
419
420   /// getRoot - Return the current virtual root of the Selection DAG.
421   ///
422   SDOperand getRoot() {
423     if (PendingLoads.empty())
424       return DAG.getRoot();
425
426     if (PendingLoads.size() == 1) {
427       SDOperand Root = PendingLoads[0];
428       DAG.setRoot(Root);
429       PendingLoads.clear();
430       return Root;
431     }
432
433     // Otherwise, we have to make a token factor node.
434     SDOperand Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
435                                  &PendingLoads[0], PendingLoads.size());
436     PendingLoads.clear();
437     DAG.setRoot(Root);
438     return Root;
439   }
440
441   SDOperand CopyValueToVirtualRegister(Value *V, unsigned Reg);
442
443   void visit(Instruction &I) { visit(I.getOpcode(), I); }
444
445   void visit(unsigned Opcode, User &I) {
446     // Note: this doesn't use InstVisitor, because it has to work with
447     // ConstantExpr's in addition to instructions.
448     switch (Opcode) {
449     default: assert(0 && "Unknown instruction type encountered!");
450              abort();
451       // Build the switch statement using the Instruction.def file.
452 #define HANDLE_INST(NUM, OPCODE, CLASS) \
453     case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
454 #include "llvm/Instruction.def"
455     }
456   }
457
458   void setCurrentBasicBlock(MachineBasicBlock *MBB) { CurMBB = MBB; }
459
460   SDOperand getLoadFrom(const Type *Ty, SDOperand Ptr,
461                         const Value *SV, SDOperand Root,
462                         bool isVolatile);
463
464   SDOperand getIntPtrConstant(uint64_t Val) {
465     return DAG.getConstant(Val, TLI.getPointerTy());
466   }
467
468   SDOperand getValue(const Value *V);
469
470   const SDOperand &setValue(const Value *V, SDOperand NewN) {
471     SDOperand &N = NodeMap[V];
472     assert(N.Val == 0 && "Already set a value for this node!");
473     return N = NewN;
474   }
475   
476   RegsForValue GetRegistersForValue(const std::string &ConstrCode,
477                                     MVT::ValueType VT,
478                                     bool OutReg, bool InReg,
479                                     std::set<unsigned> &OutputRegs, 
480                                     std::set<unsigned> &InputRegs);
481
482   void FindMergedConditions(Value *Cond, MachineBasicBlock *TBB,
483                             MachineBasicBlock *FBB, MachineBasicBlock *CurBB,
484                             unsigned Opc);
485   bool isExportableFromCurrentBlock(Value *V, const BasicBlock *FromBB);
486   void ExportFromCurrentBlock(Value *V);
487     
488   // Terminator instructions.
489   void visitRet(ReturnInst &I);
490   void visitBr(BranchInst &I);
491   void visitSwitch(SwitchInst &I);
492   void visitUnreachable(UnreachableInst &I) { /* noop */ }
493
494   // Helper for visitSwitch
495   void visitSwitchCase(SelectionDAGISel::CaseBlock &CB);
496   void visitJumpTable(SelectionDAGISel::JumpTable &JT);
497   
498   // These all get lowered before this pass.
499   void visitInvoke(InvokeInst &I) { assert(0 && "TODO"); }
500   void visitUnwind(UnwindInst &I) { assert(0 && "TODO"); }
501
502   void visitScalarBinary(User &I, unsigned OpCode);
503   void visitVectorBinary(User &I, unsigned OpCode);
504   void visitEitherBinary(User &I, unsigned ScalarOp, unsigned VectorOp);
505   void visitShift(User &I, unsigned Opcode);
506   void visitAdd(User &I) { 
507     if (isa<PackedType>(I.getType()))
508       visitVectorBinary(I, ISD::VADD);
509     else if (I.getType()->isFloatingPoint())
510       visitScalarBinary(I, ISD::FADD);
511     else
512       visitScalarBinary(I, ISD::ADD);
513   }
514   void visitSub(User &I);
515   void visitMul(User &I) {
516     if (isa<PackedType>(I.getType()))
517       visitVectorBinary(I, ISD::VMUL);
518     else if (I.getType()->isFloatingPoint())
519       visitScalarBinary(I, ISD::FMUL);
520     else
521       visitScalarBinary(I, ISD::MUL);
522   }
523   void visitURem(User &I) { visitScalarBinary(I, ISD::UREM); }
524   void visitSRem(User &I) { visitScalarBinary(I, ISD::SREM); }
525   void visitFRem(User &I) { visitScalarBinary(I, ISD::FREM); }
526   void visitUDiv(User &I) { visitEitherBinary(I, ISD::UDIV, ISD::VUDIV); }
527   void visitSDiv(User &I) { visitEitherBinary(I, ISD::SDIV, ISD::VSDIV); }
528   void visitFDiv(User &I) { visitEitherBinary(I, ISD::FDIV, ISD::VSDIV); }
529   void visitAnd (User &I) { visitEitherBinary(I, ISD::AND,  ISD::VAND ); }
530   void visitOr  (User &I) { visitEitherBinary(I, ISD::OR,   ISD::VOR  ); }
531   void visitXor (User &I) { visitEitherBinary(I, ISD::XOR,  ISD::VXOR ); }
532   void visitShl (User &I) { visitShift(I, ISD::SHL); }
533   void visitLShr(User &I) { visitShift(I, ISD::SRL); }
534   void visitAShr(User &I) { visitShift(I, ISD::SRA); }
535   void visitICmp(User &I);
536   void visitFCmp(User &I);
537   // Visit the conversion instructions
538   void visitTrunc(User &I);
539   void visitZExt(User &I);
540   void visitSExt(User &I);
541   void visitFPTrunc(User &I);
542   void visitFPExt(User &I);
543   void visitFPToUI(User &I);
544   void visitFPToSI(User &I);
545   void visitUIToFP(User &I);
546   void visitSIToFP(User &I);
547   void visitPtrToInt(User &I);
548   void visitIntToPtr(User &I);
549   void visitBitCast(User &I);
550
551   void visitExtractElement(User &I);
552   void visitInsertElement(User &I);
553   void visitShuffleVector(User &I);
554
555   void visitGetElementPtr(User &I);
556   void visitSelect(User &I);
557
558   void visitMalloc(MallocInst &I);
559   void visitFree(FreeInst &I);
560   void visitAlloca(AllocaInst &I);
561   void visitLoad(LoadInst &I);
562   void visitStore(StoreInst &I);
563   void visitPHI(PHINode &I) { } // PHI nodes are handled specially.
564   void visitCall(CallInst &I);
565   void visitInlineAsm(CallInst &I);
566   const char *visitIntrinsicCall(CallInst &I, unsigned Intrinsic);
567   void visitTargetIntrinsic(CallInst &I, unsigned Intrinsic);
568
569   void visitVAStart(CallInst &I);
570   void visitVAArg(VAArgInst &I);
571   void visitVAEnd(CallInst &I);
572   void visitVACopy(CallInst &I);
573   void visitFrameReturnAddress(CallInst &I, bool isFrameAddress);
574
575   void visitMemIntrinsic(CallInst &I, unsigned Op);
576
577   void visitUserOp1(Instruction &I) {
578     assert(0 && "UserOp1 should not exist at instruction selection time!");
579     abort();
580   }
581   void visitUserOp2(Instruction &I) {
582     assert(0 && "UserOp2 should not exist at instruction selection time!");
583     abort();
584   }
585 };
586 } // end namespace llvm
587
588 SDOperand SelectionDAGLowering::getValue(const Value *V) {
589   SDOperand &N = NodeMap[V];
590   if (N.Val) return N;
591   
592   const Type *VTy = V->getType();
593   MVT::ValueType VT = TLI.getValueType(VTy);
594   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
595     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
596       visit(CE->getOpcode(), *CE);
597       assert(N.Val && "visit didn't populate the ValueMap!");
598       return N;
599     } else if (GlobalValue *GV = dyn_cast<GlobalValue>(C)) {
600       return N = DAG.getGlobalAddress(GV, VT);
601     } else if (isa<ConstantPointerNull>(C)) {
602       return N = DAG.getConstant(0, TLI.getPointerTy());
603     } else if (isa<UndefValue>(C)) {
604       if (!isa<PackedType>(VTy))
605         return N = DAG.getNode(ISD::UNDEF, VT);
606
607       // Create a VBUILD_VECTOR of undef nodes.
608       const PackedType *PTy = cast<PackedType>(VTy);
609       unsigned NumElements = PTy->getNumElements();
610       MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
611
612       SmallVector<SDOperand, 8> Ops;
613       Ops.assign(NumElements, DAG.getNode(ISD::UNDEF, PVT));
614       
615       // Create a VConstant node with generic Vector type.
616       Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
617       Ops.push_back(DAG.getValueType(PVT));
618       return N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector,
619                              &Ops[0], Ops.size());
620     } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
621       return N = DAG.getConstantFP(CFP->getValue(), VT);
622     } else if (const PackedType *PTy = dyn_cast<PackedType>(VTy)) {
623       unsigned NumElements = PTy->getNumElements();
624       MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
625       
626       // Now that we know the number and type of the elements, push a
627       // Constant or ConstantFP node onto the ops list for each element of
628       // the packed constant.
629       SmallVector<SDOperand, 8> Ops;
630       if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C)) {
631         for (unsigned i = 0; i != NumElements; ++i)
632           Ops.push_back(getValue(CP->getOperand(i)));
633       } else {
634         assert(isa<ConstantAggregateZero>(C) && "Unknown packed constant!");
635         SDOperand Op;
636         if (MVT::isFloatingPoint(PVT))
637           Op = DAG.getConstantFP(0, PVT);
638         else
639           Op = DAG.getConstant(0, PVT);
640         Ops.assign(NumElements, Op);
641       }
642       
643       // Create a VBUILD_VECTOR node with generic Vector type.
644       Ops.push_back(DAG.getConstant(NumElements, MVT::i32));
645       Ops.push_back(DAG.getValueType(PVT));
646       return N = DAG.getNode(ISD::VBUILD_VECTOR,MVT::Vector,&Ops[0],Ops.size());
647     } else {
648       // Canonicalize all constant ints to be unsigned.
649       return N = DAG.getConstant(cast<ConstantInt>(C)->getZExtValue(),VT);
650     }
651   }
652       
653   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
654     std::map<const AllocaInst*, int>::iterator SI =
655     FuncInfo.StaticAllocaMap.find(AI);
656     if (SI != FuncInfo.StaticAllocaMap.end())
657       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
658   }
659       
660   std::map<const Value*, unsigned>::const_iterator VMI =
661       FuncInfo.ValueMap.find(V);
662   assert(VMI != FuncInfo.ValueMap.end() && "Value not in map!");
663   
664   unsigned InReg = VMI->second;
665   
666   // If this type is not legal, make it so now.
667   if (VT != MVT::Vector) {
668     if (TLI.getTypeAction(VT) == TargetLowering::Expand) {
669       // Source must be expanded.  This input value is actually coming from the
670       // register pair VMI->second and VMI->second+1.
671       MVT::ValueType DestVT = TLI.getTypeToExpandTo(VT);
672       unsigned NumVals = TLI.getNumElements(VT);
673       N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
674       if (NumVals == 1)
675         N = DAG.getNode(ISD::BIT_CONVERT, VT, N);
676       else {
677         assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
678         N = DAG.getNode(ISD::BUILD_PAIR, VT, N,
679                        DAG.getCopyFromReg(DAG.getEntryNode(), InReg+1, DestVT));
680       }
681     } else {
682       MVT::ValueType DestVT = TLI.getTypeToTransformTo(VT);
683       N = DAG.getCopyFromReg(DAG.getEntryNode(), InReg, DestVT);
684       if (TLI.getTypeAction(VT) == TargetLowering::Promote) // Promotion case
685         N = MVT::isFloatingPoint(VT)
686           ? DAG.getNode(ISD::FP_ROUND, VT, N)
687           : DAG.getNode(ISD::TRUNCATE, VT, N);
688     }
689   } else {
690     // Otherwise, if this is a vector, make it available as a generic vector
691     // here.
692     MVT::ValueType PTyElementVT, PTyLegalElementVT;
693     const PackedType *PTy = cast<PackedType>(VTy);
694     unsigned NE = TLI.getPackedTypeBreakdown(PTy, PTyElementVT,
695                                              PTyLegalElementVT);
696
697     // Build a VBUILD_VECTOR with the input registers.
698     SmallVector<SDOperand, 8> Ops;
699     if (PTyElementVT == PTyLegalElementVT) {
700       // If the value types are legal, just VBUILD the CopyFromReg nodes.
701       for (unsigned i = 0; i != NE; ++i)
702         Ops.push_back(DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 
703                                          PTyElementVT));
704     } else if (PTyElementVT < PTyLegalElementVT) {
705       // If the register was promoted, use TRUNCATE of FP_ROUND as appropriate.
706       for (unsigned i = 0; i != NE; ++i) {
707         SDOperand Op = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 
708                                           PTyElementVT);
709         if (MVT::isFloatingPoint(PTyElementVT))
710           Op = DAG.getNode(ISD::FP_ROUND, PTyElementVT, Op);
711         else
712           Op = DAG.getNode(ISD::TRUNCATE, PTyElementVT, Op);
713         Ops.push_back(Op);
714       }
715     } else {
716       // If the register was expanded, use BUILD_PAIR.
717       assert((NE & 1) == 0 && "Must expand into a multiple of 2 elements!");
718       for (unsigned i = 0; i != NE/2; ++i) {
719         SDOperand Op0 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 
720                                            PTyElementVT);
721         SDOperand Op1 = DAG.getCopyFromReg(DAG.getEntryNode(), InReg++, 
722                                            PTyElementVT);
723         Ops.push_back(DAG.getNode(ISD::BUILD_PAIR, VT, Op0, Op1));
724       }
725     }
726     
727     Ops.push_back(DAG.getConstant(NE, MVT::i32));
728     Ops.push_back(DAG.getValueType(PTyLegalElementVT));
729     N = DAG.getNode(ISD::VBUILD_VECTOR, MVT::Vector, &Ops[0], Ops.size());
730     
731     // Finally, use a VBIT_CONVERT to make this available as the appropriate
732     // vector type.
733     N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N, 
734                     DAG.getConstant(PTy->getNumElements(),
735                                     MVT::i32),
736                     DAG.getValueType(TLI.getValueType(PTy->getElementType())));
737   }
738   
739   return N;
740 }
741
742
743 void SelectionDAGLowering::visitRet(ReturnInst &I) {
744   if (I.getNumOperands() == 0) {
745     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getRoot()));
746     return;
747   }
748   SmallVector<SDOperand, 8> NewValues;
749   NewValues.push_back(getRoot());
750   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
751     SDOperand RetOp = getValue(I.getOperand(i));
752     
753     // If this is an integer return value, we need to promote it ourselves to
754     // the full width of a register, since LegalizeOp will use ANY_EXTEND rather
755     // than sign/zero.
756     // FIXME: C calling convention requires the return type to be promoted to
757     // at least 32-bit. But this is not necessary for non-C calling conventions.
758     if (MVT::isInteger(RetOp.getValueType()) && 
759         RetOp.getValueType() < MVT::i64) {
760       MVT::ValueType TmpVT;
761       if (TLI.getTypeAction(MVT::i32) == TargetLowering::Promote)
762         TmpVT = TLI.getTypeToTransformTo(MVT::i32);
763       else
764         TmpVT = MVT::i32;
765       const FunctionType *FTy = I.getParent()->getParent()->getFunctionType();
766       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
767       if (FTy->paramHasAttr(0, FunctionType::SExtAttribute))
768         ExtendKind = ISD::SIGN_EXTEND;
769       if (FTy->paramHasAttr(0, FunctionType::ZExtAttribute))
770         ExtendKind = ISD::ZERO_EXTEND;
771       RetOp = DAG.getNode(ExtendKind, TmpVT, RetOp);
772     }
773     NewValues.push_back(RetOp);
774     NewValues.push_back(DAG.getConstant(false, MVT::i32));
775   }
776   DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
777                           &NewValues[0], NewValues.size()));
778 }
779
780 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
781 /// the current basic block, add it to ValueMap now so that we'll get a
782 /// CopyTo/FromReg.
783 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
784   // No need to export constants.
785   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
786   
787   // Already exported?
788   if (FuncInfo.isExportedInst(V)) return;
789
790   unsigned Reg = FuncInfo.InitializeRegForValue(V);
791   PendingLoads.push_back(CopyValueToVirtualRegister(V, Reg));
792 }
793
794 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
795                                                     const BasicBlock *FromBB) {
796   // The operands of the setcc have to be in this block.  We don't know
797   // how to export them from some other block.
798   if (Instruction *VI = dyn_cast<Instruction>(V)) {
799     // Can export from current BB.
800     if (VI->getParent() == FromBB)
801       return true;
802     
803     // Is already exported, noop.
804     return FuncInfo.isExportedInst(V);
805   }
806   
807   // If this is an argument, we can export it if the BB is the entry block or
808   // if it is already exported.
809   if (isa<Argument>(V)) {
810     if (FromBB == &FromBB->getParent()->getEntryBlock())
811       return true;
812
813     // Otherwise, can only export this if it is already exported.
814     return FuncInfo.isExportedInst(V);
815   }
816   
817   // Otherwise, constants can always be exported.
818   return true;
819 }
820
821 static bool InBlock(const Value *V, const BasicBlock *BB) {
822   if (const Instruction *I = dyn_cast<Instruction>(V))
823     return I->getParent() == BB;
824   return true;
825 }
826
827 /// FindMergedConditions - If Cond is an expression like 
828 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
829                                                 MachineBasicBlock *TBB,
830                                                 MachineBasicBlock *FBB,
831                                                 MachineBasicBlock *CurBB,
832                                                 unsigned Opc) {
833   // If this node is not part of the or/and tree, emit it as a branch.
834   Instruction *BOp = dyn_cast<Instruction>(Cond);
835
836   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 
837       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
838       BOp->getParent() != CurBB->getBasicBlock() ||
839       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
840       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
841     const BasicBlock *BB = CurBB->getBasicBlock();
842     
843     // If the leaf of the tree is a comparison, merge the condition into 
844     // the caseblock.
845     if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
846         // The operands of the cmp have to be in this block.  We don't know
847         // how to export them from some other block.  If this is the first block
848         // of the sequence, no exporting is needed.
849         (CurBB == CurMBB ||
850          (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
851           isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
852       BOp = cast<Instruction>(Cond);
853       ISD::CondCode Condition;
854       if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
855         switch (IC->getPredicate()) {
856         default: assert(0 && "Unknown icmp predicate opcode!");
857         case ICmpInst::ICMP_EQ:  Condition = ISD::SETEQ;  break;
858         case ICmpInst::ICMP_NE:  Condition = ISD::SETNE;  break;
859         case ICmpInst::ICMP_SLE: Condition = ISD::SETLE;  break;
860         case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
861         case ICmpInst::ICMP_SGE: Condition = ISD::SETGE;  break;
862         case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
863         case ICmpInst::ICMP_SLT: Condition = ISD::SETLT;  break;
864         case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
865         case ICmpInst::ICMP_SGT: Condition = ISD::SETGT;  break;
866         case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
867         }
868       } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
869         ISD::CondCode FPC, FOC;
870         switch (FC->getPredicate()) {
871         default: assert(0 && "Unknown fcmp predicate opcode!");
872         case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
873         case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
874         case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
875         case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
876         case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
877         case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
878         case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
879         case FCmpInst::FCMP_ORD:   FOC = ISD::SETEQ; FPC = ISD::SETO;   break;
880         case FCmpInst::FCMP_UNO:   FOC = ISD::SETNE; FPC = ISD::SETUO;  break;
881         case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
882         case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
883         case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
884         case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
885         case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
886         case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
887         case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
888         }
889         if (FiniteOnlyFPMath())
890           Condition = FOC;
891         else 
892           Condition = FPC;
893       } else {
894         assert(0 && "Unknown compare instruction");
895       }
896       
897       SelectionDAGISel::CaseBlock CB(Condition, BOp->getOperand(0), 
898                                      BOp->getOperand(1), TBB, FBB, CurBB);
899       SwitchCases.push_back(CB);
900       return;
901     }
902     
903     // Create a CaseBlock record representing this branch.
904     SelectionDAGISel::CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
905                                    TBB, FBB, CurBB);
906     SwitchCases.push_back(CB);
907     return;
908   }
909   
910   
911   //  Create TmpBB after CurBB.
912   MachineFunction::iterator BBI = CurBB;
913   MachineBasicBlock *TmpBB = new MachineBasicBlock(CurBB->getBasicBlock());
914   CurBB->getParent()->getBasicBlockList().insert(++BBI, TmpBB);
915   
916   if (Opc == Instruction::Or) {
917     // Codegen X | Y as:
918     //   jmp_if_X TBB
919     //   jmp TmpBB
920     // TmpBB:
921     //   jmp_if_Y TBB
922     //   jmp FBB
923     //
924   
925     // Emit the LHS condition.
926     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
927   
928     // Emit the RHS condition into TmpBB.
929     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
930   } else {
931     assert(Opc == Instruction::And && "Unknown merge op!");
932     // Codegen X & Y as:
933     //   jmp_if_X TmpBB
934     //   jmp FBB
935     // TmpBB:
936     //   jmp_if_Y TBB
937     //   jmp FBB
938     //
939     //  This requires creation of TmpBB after CurBB.
940     
941     // Emit the LHS condition.
942     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
943     
944     // Emit the RHS condition into TmpBB.
945     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
946   }
947 }
948
949 /// If the set of cases should be emitted as a series of branches, return true.
950 /// If we should emit this as a bunch of and/or'd together conditions, return
951 /// false.
952 static bool 
953 ShouldEmitAsBranches(const std::vector<SelectionDAGISel::CaseBlock> &Cases) {
954   if (Cases.size() != 2) return true;
955   
956   // If this is two comparisons of the same values or'd or and'd together, they
957   // will get folded into a single comparison, so don't emit two blocks.
958   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
959        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
960       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
961        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
962     return false;
963   }
964   
965   return true;
966 }
967
968 void SelectionDAGLowering::visitBr(BranchInst &I) {
969   // Update machine-CFG edges.
970   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
971
972   // Figure out which block is immediately after the current one.
973   MachineBasicBlock *NextBlock = 0;
974   MachineFunction::iterator BBI = CurMBB;
975   if (++BBI != CurMBB->getParent()->end())
976     NextBlock = BBI;
977
978   if (I.isUnconditional()) {
979     // If this is not a fall-through branch, emit the branch.
980     if (Succ0MBB != NextBlock)
981       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
982                               DAG.getBasicBlock(Succ0MBB)));
983
984     // Update machine-CFG edges.
985     CurMBB->addSuccessor(Succ0MBB);
986
987     return;
988   }
989
990   // If this condition is one of the special cases we handle, do special stuff
991   // now.
992   Value *CondVal = I.getCondition();
993   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
994
995   // If this is a series of conditions that are or'd or and'd together, emit
996   // this as a sequence of branches instead of setcc's with and/or operations.
997   // For example, instead of something like:
998   //     cmp A, B
999   //     C = seteq 
1000   //     cmp D, E
1001   //     F = setle 
1002   //     or C, F
1003   //     jnz foo
1004   // Emit:
1005   //     cmp A, B
1006   //     je foo
1007   //     cmp D, E
1008   //     jle foo
1009   //
1010   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1011     if (BOp->hasOneUse() && 
1012         (BOp->getOpcode() == Instruction::And ||
1013          BOp->getOpcode() == Instruction::Or)) {
1014       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1015       // If the compares in later blocks need to use values not currently
1016       // exported from this block, export them now.  This block should always
1017       // be the first entry.
1018       assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1019       
1020       // Allow some cases to be rejected.
1021       if (ShouldEmitAsBranches(SwitchCases)) {
1022         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1023           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1024           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1025         }
1026         
1027         // Emit the branch for this block.
1028         visitSwitchCase(SwitchCases[0]);
1029         SwitchCases.erase(SwitchCases.begin());
1030         return;
1031       }
1032       
1033       // Okay, we decided not to do this, remove any inserted MBB's and clear
1034       // SwitchCases.
1035       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1036         CurMBB->getParent()->getBasicBlockList().erase(SwitchCases[i].ThisBB);
1037       
1038       SwitchCases.clear();
1039     }
1040   }
1041   
1042   // Create a CaseBlock record representing this branch.
1043   SelectionDAGISel::CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1044                                  Succ0MBB, Succ1MBB, CurMBB);
1045   // Use visitSwitchCase to actually insert the fast branch sequence for this
1046   // cond branch.
1047   visitSwitchCase(CB);
1048 }
1049
1050 /// visitSwitchCase - Emits the necessary code to represent a single node in
1051 /// the binary search tree resulting from lowering a switch instruction.
1052 void SelectionDAGLowering::visitSwitchCase(SelectionDAGISel::CaseBlock &CB) {
1053   SDOperand Cond;
1054   SDOperand CondLHS = getValue(CB.CmpLHS);
1055   
1056   // Build the setcc now, fold "(X == true)" to X and "(X == false)" to !X to
1057   // handle common cases produced by branch lowering.
1058   if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1059     Cond = CondLHS;
1060   else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1061     SDOperand True = DAG.getConstant(1, CondLHS.getValueType());
1062     Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1063   } else
1064     Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1065   
1066   // Set NextBlock to be the MBB immediately after the current one, if any.
1067   // This is used to avoid emitting unnecessary branches to the next block.
1068   MachineBasicBlock *NextBlock = 0;
1069   MachineFunction::iterator BBI = CurMBB;
1070   if (++BBI != CurMBB->getParent()->end())
1071     NextBlock = BBI;
1072   
1073   // If the lhs block is the next block, invert the condition so that we can
1074   // fall through to the lhs instead of the rhs block.
1075   if (CB.TrueBB == NextBlock) {
1076     std::swap(CB.TrueBB, CB.FalseBB);
1077     SDOperand True = DAG.getConstant(1, Cond.getValueType());
1078     Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1079   }
1080   SDOperand BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getRoot(), Cond,
1081                                  DAG.getBasicBlock(CB.TrueBB));
1082   if (CB.FalseBB == NextBlock)
1083     DAG.setRoot(BrCond);
1084   else
1085     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
1086                             DAG.getBasicBlock(CB.FalseBB)));
1087   // Update successor info
1088   CurMBB->addSuccessor(CB.TrueBB);
1089   CurMBB->addSuccessor(CB.FalseBB);
1090 }
1091
1092 void SelectionDAGLowering::visitJumpTable(SelectionDAGISel::JumpTable &JT) {
1093   // Emit the code for the jump table
1094   MVT::ValueType PTy = TLI.getPointerTy();
1095   SDOperand Index = DAG.getCopyFromReg(getRoot(), JT.Reg, PTy);
1096   SDOperand Table = DAG.getJumpTable(JT.JTI, PTy);
1097   DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1098                           Table, Index));
1099   return;
1100 }
1101
1102 void SelectionDAGLowering::visitSwitch(SwitchInst &I) {
1103   // Figure out which block is immediately after the current one.
1104   MachineBasicBlock *NextBlock = 0;
1105   MachineFunction::iterator BBI = CurMBB;
1106
1107   if (++BBI != CurMBB->getParent()->end())
1108     NextBlock = BBI;
1109   
1110   MachineBasicBlock *Default = FuncInfo.MBBMap[I.getDefaultDest()];
1111
1112   // If there is only the default destination, branch to it if it is not the
1113   // next basic block.  Otherwise, just fall through.
1114   if (I.getNumOperands() == 2) {
1115     // Update machine-CFG edges.
1116
1117     // If this is not a fall-through branch, emit the branch.
1118     if (Default != NextBlock)
1119       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getRoot(),
1120                               DAG.getBasicBlock(Default)));
1121
1122     CurMBB->addSuccessor(Default);
1123     return;
1124   }
1125   
1126   // If there are any non-default case statements, create a vector of Cases
1127   // representing each one, and sort the vector so that we can efficiently
1128   // create a binary search tree from them.
1129   std::vector<Case> Cases;
1130
1131   for (unsigned i = 1; i < I.getNumSuccessors(); ++i) {
1132     MachineBasicBlock *SMBB = FuncInfo.MBBMap[I.getSuccessor(i)];
1133     Cases.push_back(Case(I.getSuccessorValue(i), SMBB));
1134   }
1135
1136   std::sort(Cases.begin(), Cases.end(), CaseCmp());
1137   
1138   // Get the Value to be switched on and default basic blocks, which will be
1139   // inserted into CaseBlock records, representing basic blocks in the binary
1140   // search tree.
1141   Value *SV = I.getOperand(0);
1142
1143   // Get the MachineFunction which holds the current MBB.  This is used during
1144   // emission of jump tables, and when inserting any additional MBBs necessary
1145   // to represent the switch.
1146   MachineFunction *CurMF = CurMBB->getParent();
1147   const BasicBlock *LLVMBB = CurMBB->getBasicBlock();
1148   
1149   // If the switch has few cases (two or less) emit a series of specific
1150   // tests.
1151   if (Cases.size() < 3) {
1152     // TODO: If any two of the cases has the same destination, and if one value
1153     // is the same as the other, but has one bit unset that the other has set,
1154     // use bit manipulation to do two compares at once.  For example:
1155     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1156     
1157     // Rearrange the case blocks so that the last one falls through if possible.
1158     if (NextBlock && Default != NextBlock && Cases.back().second != NextBlock) {
1159       // The last case block won't fall through into 'NextBlock' if we emit the
1160       // branches in this order.  See if rearranging a case value would help.
1161       for (unsigned i = 0, e = Cases.size()-1; i != e; ++i) {
1162         if (Cases[i].second == NextBlock) {
1163           std::swap(Cases[i], Cases.back());
1164           break;
1165         }
1166       }
1167     }
1168     
1169     // Create a CaseBlock record representing a conditional branch to
1170     // the Case's target mbb if the value being switched on SV is equal
1171     // to C.
1172     MachineBasicBlock *CurBlock = CurMBB;
1173     for (unsigned i = 0, e = Cases.size(); i != e; ++i) {
1174       MachineBasicBlock *FallThrough;
1175       if (i != e-1) {
1176         FallThrough = new MachineBasicBlock(CurMBB->getBasicBlock());
1177         CurMF->getBasicBlockList().insert(BBI, FallThrough);
1178       } else {
1179         // If the last case doesn't match, go to the default block.
1180         FallThrough = Default;
1181       }
1182       
1183       SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, Cases[i].first,
1184                                      Cases[i].second, FallThrough, CurBlock);
1185     
1186       // If emitting the first comparison, just call visitSwitchCase to emit the
1187       // code into the current block.  Otherwise, push the CaseBlock onto the
1188       // vector to be later processed by SDISel, and insert the node's MBB
1189       // before the next MBB.
1190       if (CurBlock == CurMBB)
1191         visitSwitchCase(CB);
1192       else
1193         SwitchCases.push_back(CB);
1194       
1195       CurBlock = FallThrough;
1196     }
1197     return;
1198   }
1199
1200   // If the switch has more than 5 blocks, and at least 31.25% dense, and the 
1201   // target supports indirect branches, then emit a jump table rather than 
1202   // lowering the switch to a binary tree of conditional branches.
1203   if ((TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1204        TLI.isOperationLegal(ISD::BRIND, MVT::Other)) &&
1205       Cases.size() > 5) {
1206     uint64_t First =cast<ConstantInt>(Cases.front().first)->getZExtValue();
1207     uint64_t Last  = cast<ConstantInt>(Cases.back().first)->getZExtValue();
1208     double Density = (double)Cases.size() / (double)((Last - First) + 1ULL);
1209     
1210     if (Density >= 0.3125) {
1211       // Create a new basic block to hold the code for loading the address
1212       // of the jump table, and jumping to it.  Update successor information;
1213       // we will either branch to the default case for the switch, or the jump
1214       // table.
1215       MachineBasicBlock *JumpTableBB = new MachineBasicBlock(LLVMBB);
1216       CurMF->getBasicBlockList().insert(BBI, JumpTableBB);
1217       CurMBB->addSuccessor(Default);
1218       CurMBB->addSuccessor(JumpTableBB);
1219       
1220       // Subtract the lowest switch case value from the value being switched on
1221       // and conditional branch to default mbb if the result is greater than the
1222       // difference between smallest and largest cases.
1223       SDOperand SwitchOp = getValue(SV);
1224       MVT::ValueType VT = SwitchOp.getValueType();
1225       SDOperand SUB = DAG.getNode(ISD::SUB, VT, SwitchOp, 
1226                                   DAG.getConstant(First, VT));
1227
1228       // The SDNode we just created, which holds the value being switched on
1229       // minus the the smallest case value, needs to be copied to a virtual
1230       // register so it can be used as an index into the jump table in a 
1231       // subsequent basic block.  This value may be smaller or larger than the
1232       // target's pointer type, and therefore require extension or truncating.
1233       if (VT > TLI.getPointerTy())
1234         SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1235       else
1236         SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1237
1238       unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1239       SDOperand CopyTo = DAG.getCopyToReg(getRoot(), JumpTableReg, SwitchOp);
1240       
1241       // Emit the range check for the jump table, and branch to the default
1242       // block for the switch statement if the value being switched on exceeds
1243       // the largest case in the switch.
1244       SDOperand CMP = DAG.getSetCC(TLI.getSetCCResultTy(), SUB,
1245                                    DAG.getConstant(Last-First,VT), ISD::SETUGT);
1246       DAG.setRoot(DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP, 
1247                               DAG.getBasicBlock(Default)));
1248
1249       // Build a vector of destination BBs, corresponding to each target
1250       // of the jump table.  If the value of the jump table slot corresponds to
1251       // a case statement, push the case's BB onto the vector, otherwise, push
1252       // the default BB.
1253       std::vector<MachineBasicBlock*> DestBBs;
1254       uint64_t TEI = First;
1255       for (CaseItr ii = Cases.begin(), ee = Cases.end(); ii != ee; ++TEI)
1256         if (cast<ConstantInt>(ii->first)->getZExtValue() == TEI) {
1257           DestBBs.push_back(ii->second);
1258           ++ii;
1259         } else {
1260           DestBBs.push_back(Default);
1261         }
1262       
1263       // Update successor info.  Add one edge to each unique successor.
1264       // Vector bool would be better, but vector<bool> is really slow.
1265       std::vector<unsigned char> SuccsHandled;
1266       SuccsHandled.resize(CurMBB->getParent()->getNumBlockIDs());
1267       
1268       for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 
1269            E = DestBBs.end(); I != E; ++I) {
1270         if (!SuccsHandled[(*I)->getNumber()]) {
1271           SuccsHandled[(*I)->getNumber()] = true;
1272           JumpTableBB->addSuccessor(*I);
1273         }
1274       }
1275       
1276       // Create a jump table index for this jump table, or return an existing
1277       // one.
1278       unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1279       
1280       // Set the jump table information so that we can codegen it as a second
1281       // MachineBasicBlock
1282       JT.Reg = JumpTableReg;
1283       JT.JTI = JTI;
1284       JT.MBB = JumpTableBB;
1285       JT.Default = Default;
1286       return;
1287     }
1288   }
1289   
1290   // Push the initial CaseRec onto the worklist
1291   std::vector<CaseRec> CaseVec;
1292   CaseVec.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1293   
1294   while (!CaseVec.empty()) {
1295     // Grab a record representing a case range to process off the worklist
1296     CaseRec CR = CaseVec.back();
1297     CaseVec.pop_back();
1298     
1299     // Size is the number of Cases represented by this range.  If Size is 1,
1300     // then we are processing a leaf of the binary search tree.  Otherwise,
1301     // we need to pick a pivot, and push left and right ranges onto the 
1302     // worklist.
1303     unsigned Size = CR.Range.second - CR.Range.first;
1304     
1305     if (Size == 1) {
1306       // Create a CaseBlock record representing a conditional branch to
1307       // the Case's target mbb if the value being switched on SV is equal
1308       // to C.  Otherwise, branch to default.
1309       Constant *C = CR.Range.first->first;
1310       MachineBasicBlock *Target = CR.Range.first->second;
1311       SelectionDAGISel::CaseBlock CB(ISD::SETEQ, SV, C, Target, Default, 
1312                                      CR.CaseBB);
1313
1314       // If the MBB representing the leaf node is the current MBB, then just
1315       // call visitSwitchCase to emit the code into the current block.
1316       // Otherwise, push the CaseBlock onto the vector to be later processed
1317       // by SDISel, and insert the node's MBB before the next MBB.
1318       if (CR.CaseBB == CurMBB)
1319         visitSwitchCase(CB);
1320       else
1321         SwitchCases.push_back(CB);
1322     } else {
1323       // split case range at pivot
1324       CaseItr Pivot = CR.Range.first + (Size / 2);
1325       CaseRange LHSR(CR.Range.first, Pivot);
1326       CaseRange RHSR(Pivot, CR.Range.second);
1327       Constant *C = Pivot->first;
1328       MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1329
1330       // We know that we branch to the LHS if the Value being switched on is
1331       // less than the Pivot value, C.  We use this to optimize our binary 
1332       // tree a bit, by recognizing that if SV is greater than or equal to the
1333       // LHS's Case Value, and that Case Value is exactly one less than the 
1334       // Pivot's Value, then we can branch directly to the LHS's Target,
1335       // rather than creating a leaf node for it.
1336       if ((LHSR.second - LHSR.first) == 1 &&
1337           LHSR.first->first == CR.GE &&
1338           cast<ConstantInt>(C)->getZExtValue() ==
1339           (cast<ConstantInt>(CR.GE)->getZExtValue() + 1ULL)) {
1340         TrueBB = LHSR.first->second;
1341       } else {
1342         TrueBB = new MachineBasicBlock(LLVMBB);
1343         CurMF->getBasicBlockList().insert(BBI, TrueBB);
1344         CaseVec.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1345       }
1346
1347       // Similar to the optimization above, if the Value being switched on is
1348       // known to be less than the Constant CR.LT, and the current Case Value
1349       // is CR.LT - 1, then we can branch directly to the target block for
1350       // the current Case Value, rather than emitting a RHS leaf node for it.
1351       if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1352           cast<ConstantInt>(RHSR.first->first)->getZExtValue() ==
1353           (cast<ConstantInt>(CR.LT)->getZExtValue() - 1ULL)) {
1354         FalseBB = RHSR.first->second;
1355       } else {
1356         FalseBB = new MachineBasicBlock(LLVMBB);
1357         CurMF->getBasicBlockList().insert(BBI, FalseBB);
1358         CaseVec.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1359       }
1360
1361       // Create a CaseBlock record representing a conditional branch to
1362       // the LHS node if the value being switched on SV is less than C. 
1363       // Otherwise, branch to LHS.
1364       ISD::CondCode CC =  ISD::SETLT;
1365       SelectionDAGISel::CaseBlock CB(CC, SV, C, TrueBB, FalseBB, CR.CaseBB);
1366
1367       if (CR.CaseBB == CurMBB)
1368         visitSwitchCase(CB);
1369       else
1370         SwitchCases.push_back(CB);
1371     }
1372   }
1373 }
1374
1375 void SelectionDAGLowering::visitSub(User &I) {
1376   // -0.0 - X --> fneg
1377   const Type *Ty = I.getType();
1378   if (isa<PackedType>(Ty)) {
1379     visitVectorBinary(I, ISD::VSUB);
1380   } else if (Ty->isFloatingPoint()) {
1381     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
1382       if (CFP->isExactlyValue(-0.0)) {
1383         SDOperand Op2 = getValue(I.getOperand(1));
1384         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
1385         return;
1386       }
1387     visitScalarBinary(I, ISD::FSUB);
1388   } else 
1389     visitScalarBinary(I, ISD::SUB);
1390 }
1391
1392 void SelectionDAGLowering::visitScalarBinary(User &I, unsigned OpCode) {
1393   SDOperand Op1 = getValue(I.getOperand(0));
1394   SDOperand Op2 = getValue(I.getOperand(1));
1395   
1396   setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
1397 }
1398
1399 void
1400 SelectionDAGLowering::visitVectorBinary(User &I, unsigned OpCode) {
1401   assert(isa<PackedType>(I.getType()));
1402   const PackedType *Ty = cast<PackedType>(I.getType());
1403   SDOperand Typ = DAG.getValueType(TLI.getValueType(Ty->getElementType()));
1404
1405   setValue(&I, DAG.getNode(OpCode, MVT::Vector,
1406                            getValue(I.getOperand(0)),
1407                            getValue(I.getOperand(1)),
1408                            DAG.getConstant(Ty->getNumElements(), MVT::i32),
1409                            Typ));
1410 }
1411
1412 void SelectionDAGLowering::visitEitherBinary(User &I, unsigned ScalarOp,
1413                                              unsigned VectorOp) {
1414   if (isa<PackedType>(I.getType()))
1415     visitVectorBinary(I, VectorOp);
1416   else
1417     visitScalarBinary(I, ScalarOp);
1418 }
1419
1420 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
1421   SDOperand Op1 = getValue(I.getOperand(0));
1422   SDOperand Op2 = getValue(I.getOperand(1));
1423   
1424   Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
1425   
1426   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
1427 }
1428
1429 void SelectionDAGLowering::visitICmp(User &I) {
1430   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
1431   if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
1432     predicate = IC->getPredicate();
1433   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
1434     predicate = ICmpInst::Predicate(IC->getPredicate());
1435   SDOperand Op1 = getValue(I.getOperand(0));
1436   SDOperand Op2 = getValue(I.getOperand(1));
1437   ISD::CondCode Opcode;
1438   switch (predicate) {
1439     case ICmpInst::ICMP_EQ  : Opcode = ISD::SETEQ; break;
1440     case ICmpInst::ICMP_NE  : Opcode = ISD::SETNE; break;
1441     case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
1442     case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
1443     case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
1444     case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
1445     case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
1446     case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
1447     case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
1448     case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
1449     default:
1450       assert(!"Invalid ICmp predicate value");
1451       Opcode = ISD::SETEQ;
1452       break;
1453   }
1454   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
1455 }
1456
1457 void SelectionDAGLowering::visitFCmp(User &I) {
1458   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
1459   if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
1460     predicate = FC->getPredicate();
1461   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
1462     predicate = FCmpInst::Predicate(FC->getPredicate());
1463   SDOperand Op1 = getValue(I.getOperand(0));
1464   SDOperand Op2 = getValue(I.getOperand(1));
1465   ISD::CondCode Condition, FOC, FPC;
1466   switch (predicate) {
1467     case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1468     case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1469     case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1470     case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1471     case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1472     case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1473     case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1474     case FCmpInst::FCMP_ORD:   FOC = ISD::SETEQ; FPC = ISD::SETO;   break;
1475     case FCmpInst::FCMP_UNO:   FOC = ISD::SETNE; FPC = ISD::SETUO;  break;
1476     case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1477     case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1478     case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1479     case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1480     case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1481     case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1482     case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
1483     default:
1484       assert(!"Invalid FCmp predicate value");
1485       FOC = FPC = ISD::SETFALSE;
1486       break;
1487   }
1488   if (FiniteOnlyFPMath())
1489     Condition = FOC;
1490   else 
1491     Condition = FPC;
1492   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
1493 }
1494
1495 void SelectionDAGLowering::visitSelect(User &I) {
1496   SDOperand Cond     = getValue(I.getOperand(0));
1497   SDOperand TrueVal  = getValue(I.getOperand(1));
1498   SDOperand FalseVal = getValue(I.getOperand(2));
1499   if (!isa<PackedType>(I.getType())) {
1500     setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
1501                              TrueVal, FalseVal));
1502   } else {
1503     setValue(&I, DAG.getNode(ISD::VSELECT, MVT::Vector, Cond, TrueVal, FalseVal,
1504                              *(TrueVal.Val->op_end()-2),
1505                              *(TrueVal.Val->op_end()-1)));
1506   }
1507 }
1508
1509
1510 void SelectionDAGLowering::visitTrunc(User &I) {
1511   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
1512   SDOperand N = getValue(I.getOperand(0));
1513   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1514   setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1515 }
1516
1517 void SelectionDAGLowering::visitZExt(User &I) {
1518   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1519   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
1520   SDOperand N = getValue(I.getOperand(0));
1521   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1522   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1523 }
1524
1525 void SelectionDAGLowering::visitSExt(User &I) {
1526   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
1527   // SExt also can't be a cast to bool for same reason. So, nothing much to do
1528   SDOperand N = getValue(I.getOperand(0));
1529   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1530   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
1531 }
1532
1533 void SelectionDAGLowering::visitFPTrunc(User &I) {
1534   // FPTrunc is never a no-op cast, no need to check
1535   SDOperand N = getValue(I.getOperand(0));
1536   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1537   setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N));
1538 }
1539
1540 void SelectionDAGLowering::visitFPExt(User &I){ 
1541   // FPTrunc is never a no-op cast, no need to check
1542   SDOperand N = getValue(I.getOperand(0));
1543   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1544   setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
1545 }
1546
1547 void SelectionDAGLowering::visitFPToUI(User &I) { 
1548   // FPToUI is never a no-op cast, no need to check
1549   SDOperand N = getValue(I.getOperand(0));
1550   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1551   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
1552 }
1553
1554 void SelectionDAGLowering::visitFPToSI(User &I) {
1555   // FPToSI is never a no-op cast, no need to check
1556   SDOperand N = getValue(I.getOperand(0));
1557   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1558   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
1559 }
1560
1561 void SelectionDAGLowering::visitUIToFP(User &I) { 
1562   // UIToFP is never a no-op cast, no need to check
1563   SDOperand N = getValue(I.getOperand(0));
1564   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1565   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
1566 }
1567
1568 void SelectionDAGLowering::visitSIToFP(User &I){ 
1569   // UIToFP is never a no-op cast, no need to check
1570   SDOperand N = getValue(I.getOperand(0));
1571   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1572   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
1573 }
1574
1575 void SelectionDAGLowering::visitPtrToInt(User &I) {
1576   // What to do depends on the size of the integer and the size of the pointer.
1577   // We can either truncate, zero extend, or no-op, accordingly.
1578   SDOperand N = getValue(I.getOperand(0));
1579   MVT::ValueType SrcVT = N.getValueType();
1580   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1581   SDOperand Result;
1582   if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1583     Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
1584   else 
1585     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1586     Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
1587   setValue(&I, Result);
1588 }
1589
1590 void SelectionDAGLowering::visitIntToPtr(User &I) {
1591   // What to do depends on the size of the integer and the size of the pointer.
1592   // We can either truncate, zero extend, or no-op, accordingly.
1593   SDOperand N = getValue(I.getOperand(0));
1594   MVT::ValueType SrcVT = N.getValueType();
1595   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1596   if (MVT::getSizeInBits(DestVT) < MVT::getSizeInBits(SrcVT))
1597     setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
1598   else 
1599     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
1600     setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
1601 }
1602
1603 void SelectionDAGLowering::visitBitCast(User &I) { 
1604   SDOperand N = getValue(I.getOperand(0));
1605   MVT::ValueType DestVT = TLI.getValueType(I.getType());
1606   if (DestVT == MVT::Vector) {
1607     // This is a cast to a vector from something else.  
1608     // Get information about the output vector.
1609     const PackedType *DestTy = cast<PackedType>(I.getType());
1610     MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1611     setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N, 
1612                              DAG.getConstant(DestTy->getNumElements(),MVT::i32),
1613                              DAG.getValueType(EltVT)));
1614     return;
1615   } 
1616   MVT::ValueType SrcVT = N.getValueType();
1617   if (SrcVT == MVT::Vector) {
1618     // This is a cast from a vctor to something else. 
1619     // Get information about the input vector.
1620     setValue(&I, DAG.getNode(ISD::VBIT_CONVERT, DestVT, N));
1621     return;
1622   }
1623
1624   // BitCast assures us that source and destination are the same size so this 
1625   // is either a BIT_CONVERT or a no-op.
1626   if (DestVT != N.getValueType())
1627     setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
1628   else
1629     setValue(&I, N); // noop cast.
1630 }
1631
1632 void SelectionDAGLowering::visitInsertElement(User &I) {
1633   SDOperand InVec = getValue(I.getOperand(0));
1634   SDOperand InVal = getValue(I.getOperand(1));
1635   SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1636                                 getValue(I.getOperand(2)));
1637
1638   SDOperand Num = *(InVec.Val->op_end()-2);
1639   SDOperand Typ = *(InVec.Val->op_end()-1);
1640   setValue(&I, DAG.getNode(ISD::VINSERT_VECTOR_ELT, MVT::Vector,
1641                            InVec, InVal, InIdx, Num, Typ));
1642 }
1643
1644 void SelectionDAGLowering::visitExtractElement(User &I) {
1645   SDOperand InVec = getValue(I.getOperand(0));
1646   SDOperand InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
1647                                 getValue(I.getOperand(1)));
1648   SDOperand Typ = *(InVec.Val->op_end()-1);
1649   setValue(&I, DAG.getNode(ISD::VEXTRACT_VECTOR_ELT,
1650                            TLI.getValueType(I.getType()), InVec, InIdx));
1651 }
1652
1653 void SelectionDAGLowering::visitShuffleVector(User &I) {
1654   SDOperand V1   = getValue(I.getOperand(0));
1655   SDOperand V2   = getValue(I.getOperand(1));
1656   SDOperand Mask = getValue(I.getOperand(2));
1657
1658   SDOperand Num = *(V1.Val->op_end()-2);
1659   SDOperand Typ = *(V2.Val->op_end()-1);
1660   setValue(&I, DAG.getNode(ISD::VVECTOR_SHUFFLE, MVT::Vector,
1661                            V1, V2, Mask, Num, Typ));
1662 }
1663
1664
1665 void SelectionDAGLowering::visitGetElementPtr(User &I) {
1666   SDOperand N = getValue(I.getOperand(0));
1667   const Type *Ty = I.getOperand(0)->getType();
1668
1669   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
1670        OI != E; ++OI) {
1671     Value *Idx = *OI;
1672     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
1673       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
1674       if (Field) {
1675         // N = N + Offset
1676         uint64_t Offset = TD->getStructLayout(StTy)->MemberOffsets[Field];
1677         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
1678                         getIntPtrConstant(Offset));
1679       }
1680       Ty = StTy->getElementType(Field);
1681     } else {
1682       Ty = cast<SequentialType>(Ty)->getElementType();
1683
1684       // If this is a constant subscript, handle it quickly.
1685       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
1686         if (CI->getZExtValue() == 0) continue;
1687         uint64_t Offs = 
1688             TD->getTypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
1689         N = DAG.getNode(ISD::ADD, N.getValueType(), N, getIntPtrConstant(Offs));
1690         continue;
1691       }
1692       
1693       // N = N + Idx * ElementSize;
1694       uint64_t ElementSize = TD->getTypeSize(Ty);
1695       SDOperand IdxN = getValue(Idx);
1696
1697       // If the index is smaller or larger than intptr_t, truncate or extend
1698       // it.
1699       if (IdxN.getValueType() < N.getValueType()) {
1700         IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
1701       } else if (IdxN.getValueType() > N.getValueType())
1702         IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
1703
1704       // If this is a multiply by a power of two, turn it into a shl
1705       // immediately.  This is a very common case.
1706       if (isPowerOf2_64(ElementSize)) {
1707         unsigned Amt = Log2_64(ElementSize);
1708         IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
1709                            DAG.getConstant(Amt, TLI.getShiftAmountTy()));
1710         N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1711         continue;
1712       }
1713       
1714       SDOperand Scale = getIntPtrConstant(ElementSize);
1715       IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
1716       N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
1717     }
1718   }
1719   setValue(&I, N);
1720 }
1721
1722 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
1723   // If this is a fixed sized alloca in the entry block of the function,
1724   // allocate it statically on the stack.
1725   if (FuncInfo.StaticAllocaMap.count(&I))
1726     return;   // getValue will auto-populate this.
1727
1728   const Type *Ty = I.getAllocatedType();
1729   uint64_t TySize = TLI.getTargetData()->getTypeSize(Ty);
1730   unsigned Align =
1731     std::max((unsigned)TLI.getTargetData()->getTypeAlignmentPref(Ty),
1732              I.getAlignment());
1733
1734   SDOperand AllocSize = getValue(I.getArraySize());
1735   MVT::ValueType IntPtr = TLI.getPointerTy();
1736   if (IntPtr < AllocSize.getValueType())
1737     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
1738   else if (IntPtr > AllocSize.getValueType())
1739     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
1740
1741   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
1742                           getIntPtrConstant(TySize));
1743
1744   // Handle alignment.  If the requested alignment is less than or equal to the
1745   // stack alignment, ignore it and round the size of the allocation up to the
1746   // stack alignment size.  If the size is greater than the stack alignment, we
1747   // note this in the DYNAMIC_STACKALLOC node.
1748   unsigned StackAlign =
1749     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1750   if (Align <= StackAlign) {
1751     Align = 0;
1752     // Add SA-1 to the size.
1753     AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
1754                             getIntPtrConstant(StackAlign-1));
1755     // Mask out the low bits for alignment purposes.
1756     AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
1757                             getIntPtrConstant(~(uint64_t)(StackAlign-1)));
1758   }
1759
1760   SDOperand Ops[] = { getRoot(), AllocSize, getIntPtrConstant(Align) };
1761   const MVT::ValueType *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
1762                                                     MVT::Other);
1763   SDOperand DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
1764   DAG.setRoot(setValue(&I, DSA).getValue(1));
1765
1766   // Inform the Frame Information that we have just allocated a variable-sized
1767   // object.
1768   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
1769 }
1770
1771 void SelectionDAGLowering::visitLoad(LoadInst &I) {
1772   SDOperand Ptr = getValue(I.getOperand(0));
1773
1774   SDOperand Root;
1775   if (I.isVolatile())
1776     Root = getRoot();
1777   else {
1778     // Do not serialize non-volatile loads against each other.
1779     Root = DAG.getRoot();
1780   }
1781
1782   setValue(&I, getLoadFrom(I.getType(), Ptr, I.getOperand(0),
1783                            Root, I.isVolatile()));
1784 }
1785
1786 SDOperand SelectionDAGLowering::getLoadFrom(const Type *Ty, SDOperand Ptr,
1787                                             const Value *SV, SDOperand Root,
1788                                             bool isVolatile) {
1789   SDOperand L;
1790   if (const PackedType *PTy = dyn_cast<PackedType>(Ty)) {
1791     MVT::ValueType PVT = TLI.getValueType(PTy->getElementType());
1792     L = DAG.getVecLoad(PTy->getNumElements(), PVT, Root, Ptr,
1793                        DAG.getSrcValue(SV));
1794   } else {
1795     L = DAG.getLoad(TLI.getValueType(Ty), Root, Ptr, SV, 0, isVolatile);
1796   }
1797
1798   if (isVolatile)
1799     DAG.setRoot(L.getValue(1));
1800   else
1801     PendingLoads.push_back(L.getValue(1));
1802   
1803   return L;
1804 }
1805
1806
1807 void SelectionDAGLowering::visitStore(StoreInst &I) {
1808   Value *SrcV = I.getOperand(0);
1809   SDOperand Src = getValue(SrcV);
1810   SDOperand Ptr = getValue(I.getOperand(1));
1811   DAG.setRoot(DAG.getStore(getRoot(), Src, Ptr, I.getOperand(1), 0,
1812                            I.isVolatile()));
1813 }
1814
1815 /// IntrinsicCannotAccessMemory - Return true if the specified intrinsic cannot
1816 /// access memory and has no other side effects at all.
1817 static bool IntrinsicCannotAccessMemory(unsigned IntrinsicID) {
1818 #define GET_NO_MEMORY_INTRINSICS
1819 #include "llvm/Intrinsics.gen"
1820 #undef GET_NO_MEMORY_INTRINSICS
1821   return false;
1822 }
1823
1824 // IntrinsicOnlyReadsMemory - Return true if the specified intrinsic doesn't
1825 // have any side-effects or if it only reads memory.
1826 static bool IntrinsicOnlyReadsMemory(unsigned IntrinsicID) {
1827 #define GET_SIDE_EFFECT_INFO
1828 #include "llvm/Intrinsics.gen"
1829 #undef GET_SIDE_EFFECT_INFO
1830   return false;
1831 }
1832
1833 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
1834 /// node.
1835 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I, 
1836                                                 unsigned Intrinsic) {
1837   bool HasChain = !IntrinsicCannotAccessMemory(Intrinsic);
1838   bool OnlyLoad = HasChain && IntrinsicOnlyReadsMemory(Intrinsic);
1839   
1840   // Build the operand list.
1841   SmallVector<SDOperand, 8> Ops;
1842   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
1843     if (OnlyLoad) {
1844       // We don't need to serialize loads against other loads.
1845       Ops.push_back(DAG.getRoot());
1846     } else { 
1847       Ops.push_back(getRoot());
1848     }
1849   }
1850   
1851   // Add the intrinsic ID as an integer operand.
1852   Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
1853
1854   // Add all operands of the call to the operand list.
1855   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
1856     SDOperand Op = getValue(I.getOperand(i));
1857     
1858     // If this is a vector type, force it to the right packed type.
1859     if (Op.getValueType() == MVT::Vector) {
1860       const PackedType *OpTy = cast<PackedType>(I.getOperand(i)->getType());
1861       MVT::ValueType EltVT = TLI.getValueType(OpTy->getElementType());
1862       
1863       MVT::ValueType VVT = MVT::getVectorType(EltVT, OpTy->getNumElements());
1864       assert(VVT != MVT::Other && "Intrinsic uses a non-legal type?");
1865       Op = DAG.getNode(ISD::VBIT_CONVERT, VVT, Op);
1866     }
1867     
1868     assert(TLI.isTypeLegal(Op.getValueType()) &&
1869            "Intrinsic uses a non-legal type?");
1870     Ops.push_back(Op);
1871   }
1872
1873   std::vector<MVT::ValueType> VTs;
1874   if (I.getType() != Type::VoidTy) {
1875     MVT::ValueType VT = TLI.getValueType(I.getType());
1876     if (VT == MVT::Vector) {
1877       const PackedType *DestTy = cast<PackedType>(I.getType());
1878       MVT::ValueType EltVT = TLI.getValueType(DestTy->getElementType());
1879       
1880       VT = MVT::getVectorType(EltVT, DestTy->getNumElements());
1881       assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
1882     }
1883     
1884     assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
1885     VTs.push_back(VT);
1886   }
1887   if (HasChain)
1888     VTs.push_back(MVT::Other);
1889
1890   const MVT::ValueType *VTList = DAG.getNodeValueTypes(VTs);
1891
1892   // Create the node.
1893   SDOperand Result;
1894   if (!HasChain)
1895     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
1896                          &Ops[0], Ops.size());
1897   else if (I.getType() != Type::VoidTy)
1898     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
1899                          &Ops[0], Ops.size());
1900   else
1901     Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
1902                          &Ops[0], Ops.size());
1903
1904   if (HasChain) {
1905     SDOperand Chain = Result.getValue(Result.Val->getNumValues()-1);
1906     if (OnlyLoad)
1907       PendingLoads.push_back(Chain);
1908     else
1909       DAG.setRoot(Chain);
1910   }
1911   if (I.getType() != Type::VoidTy) {
1912     if (const PackedType *PTy = dyn_cast<PackedType>(I.getType())) {
1913       MVT::ValueType EVT = TLI.getValueType(PTy->getElementType());
1914       Result = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Result,
1915                            DAG.getConstant(PTy->getNumElements(), MVT::i32),
1916                            DAG.getValueType(EVT));
1917     } 
1918     setValue(&I, Result);
1919   }
1920 }
1921
1922 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
1923 /// we want to emit this as a call to a named external function, return the name
1924 /// otherwise lower it and return null.
1925 const char *
1926 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
1927   switch (Intrinsic) {
1928   default:
1929     // By default, turn this into a target intrinsic node.
1930     visitTargetIntrinsic(I, Intrinsic);
1931     return 0;
1932   case Intrinsic::vastart:  visitVAStart(I); return 0;
1933   case Intrinsic::vaend:    visitVAEnd(I); return 0;
1934   case Intrinsic::vacopy:   visitVACopy(I); return 0;
1935   case Intrinsic::returnaddress: visitFrameReturnAddress(I, false); return 0;
1936   case Intrinsic::frameaddress:  visitFrameReturnAddress(I, true); return 0;
1937   case Intrinsic::setjmp:
1938     return "_setjmp"+!TLI.usesUnderscoreSetJmp();
1939     break;
1940   case Intrinsic::longjmp:
1941     return "_longjmp"+!TLI.usesUnderscoreLongJmp();
1942     break;
1943   case Intrinsic::memcpy_i32:
1944   case Intrinsic::memcpy_i64:
1945     visitMemIntrinsic(I, ISD::MEMCPY);
1946     return 0;
1947   case Intrinsic::memset_i32:
1948   case Intrinsic::memset_i64:
1949     visitMemIntrinsic(I, ISD::MEMSET);
1950     return 0;
1951   case Intrinsic::memmove_i32:
1952   case Intrinsic::memmove_i64:
1953     visitMemIntrinsic(I, ISD::MEMMOVE);
1954     return 0;
1955     
1956   case Intrinsic::dbg_stoppoint: {
1957     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1958     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
1959     if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
1960       SDOperand Ops[5];
1961
1962       Ops[0] = getRoot();
1963       Ops[1] = getValue(SPI.getLineValue());
1964       Ops[2] = getValue(SPI.getColumnValue());
1965
1966       DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
1967       assert(DD && "Not a debug information descriptor");
1968       CompileUnitDesc *CompileUnit = cast<CompileUnitDesc>(DD);
1969       
1970       Ops[3] = DAG.getString(CompileUnit->getFileName());
1971       Ops[4] = DAG.getString(CompileUnit->getDirectory());
1972       
1973       DAG.setRoot(DAG.getNode(ISD::LOCATION, MVT::Other, Ops, 5));
1974     }
1975
1976     return 0;
1977   }
1978   case Intrinsic::dbg_region_start: {
1979     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1980     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
1981     if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
1982       unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
1983       DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other, getRoot(),
1984                               DAG.getConstant(LabelID, MVT::i32)));
1985     }
1986
1987     return 0;
1988   }
1989   case Intrinsic::dbg_region_end: {
1990     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
1991     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
1992     if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
1993       unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
1994       DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
1995                               getRoot(), DAG.getConstant(LabelID, MVT::i32)));
1996     }
1997
1998     return 0;
1999   }
2000   case Intrinsic::dbg_func_start: {
2001     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2002     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2003     if (MMI && FSI.getSubprogram() &&
2004         MMI->Verify(FSI.getSubprogram())) {
2005       unsigned LabelID = MMI->RecordRegionStart(FSI.getSubprogram());
2006       DAG.setRoot(DAG.getNode(ISD::LABEL, MVT::Other,
2007                   getRoot(), DAG.getConstant(LabelID, MVT::i32)));
2008     }
2009
2010     return 0;
2011   }
2012   case Intrinsic::dbg_declare: {
2013     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2014     DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2015     if (MMI && DI.getVariable() && MMI->Verify(DI.getVariable())) {
2016       SDOperand AddressOp  = getValue(DI.getAddress());
2017       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(AddressOp))
2018         MMI->RecordVariable(DI.getVariable(), FI->getIndex());
2019     }
2020
2021     return 0;
2022   }
2023     
2024   case Intrinsic::sqrt_f32:
2025   case Intrinsic::sqrt_f64:
2026     setValue(&I, DAG.getNode(ISD::FSQRT,
2027                              getValue(I.getOperand(1)).getValueType(),
2028                              getValue(I.getOperand(1))));
2029     return 0;
2030   case Intrinsic::powi_f32:
2031   case Intrinsic::powi_f64:
2032     setValue(&I, DAG.getNode(ISD::FPOWI,
2033                              getValue(I.getOperand(1)).getValueType(),
2034                              getValue(I.getOperand(1)),
2035                              getValue(I.getOperand(2))));
2036     return 0;
2037   case Intrinsic::pcmarker: {
2038     SDOperand Tmp = getValue(I.getOperand(1));
2039     DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
2040     return 0;
2041   }
2042   case Intrinsic::readcyclecounter: {
2043     SDOperand Op = getRoot();
2044     SDOperand Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
2045                                 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
2046                                 &Op, 1);
2047     setValue(&I, Tmp);
2048     DAG.setRoot(Tmp.getValue(1));
2049     return 0;
2050   }
2051   case Intrinsic::bswap_i16:
2052   case Intrinsic::bswap_i32:
2053   case Intrinsic::bswap_i64:
2054     setValue(&I, DAG.getNode(ISD::BSWAP,
2055                              getValue(I.getOperand(1)).getValueType(),
2056                              getValue(I.getOperand(1))));
2057     return 0;
2058   case Intrinsic::cttz_i8:
2059   case Intrinsic::cttz_i16:
2060   case Intrinsic::cttz_i32:
2061   case Intrinsic::cttz_i64:
2062     setValue(&I, DAG.getNode(ISD::CTTZ,
2063                              getValue(I.getOperand(1)).getValueType(),
2064                              getValue(I.getOperand(1))));
2065     return 0;
2066   case Intrinsic::ctlz_i8:
2067   case Intrinsic::ctlz_i16:
2068   case Intrinsic::ctlz_i32:
2069   case Intrinsic::ctlz_i64:
2070     setValue(&I, DAG.getNode(ISD::CTLZ,
2071                              getValue(I.getOperand(1)).getValueType(),
2072                              getValue(I.getOperand(1))));
2073     return 0;
2074   case Intrinsic::ctpop_i8:
2075   case Intrinsic::ctpop_i16:
2076   case Intrinsic::ctpop_i32:
2077   case Intrinsic::ctpop_i64:
2078     setValue(&I, DAG.getNode(ISD::CTPOP,
2079                              getValue(I.getOperand(1)).getValueType(),
2080                              getValue(I.getOperand(1))));
2081     return 0;
2082   case Intrinsic::stacksave: {
2083     SDOperand Op = getRoot();
2084     SDOperand Tmp = DAG.getNode(ISD::STACKSAVE,
2085               DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
2086     setValue(&I, Tmp);
2087     DAG.setRoot(Tmp.getValue(1));
2088     return 0;
2089   }
2090   case Intrinsic::stackrestore: {
2091     SDOperand Tmp = getValue(I.getOperand(1));
2092     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
2093     return 0;
2094   }
2095   case Intrinsic::prefetch:
2096     // FIXME: Currently discarding prefetches.
2097     return 0;
2098   }
2099 }
2100
2101
2102 void SelectionDAGLowering::visitCall(CallInst &I) {
2103   const char *RenameFn = 0;
2104   if (Function *F = I.getCalledFunction()) {
2105     if (F->isExternal())
2106       if (unsigned IID = F->getIntrinsicID()) {
2107         RenameFn = visitIntrinsicCall(I, IID);
2108         if (!RenameFn)
2109           return;
2110       } else {    // Not an LLVM intrinsic.
2111         const std::string &Name = F->getName();
2112         if (Name[0] == 'c' && (Name == "copysign" || Name == "copysignf")) {
2113           if (I.getNumOperands() == 3 &&   // Basic sanity checks.
2114               I.getOperand(1)->getType()->isFloatingPoint() &&
2115               I.getType() == I.getOperand(1)->getType() &&
2116               I.getType() == I.getOperand(2)->getType()) {
2117             SDOperand LHS = getValue(I.getOperand(1));
2118             SDOperand RHS = getValue(I.getOperand(2));
2119             setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
2120                                      LHS, RHS));
2121             return;
2122           }
2123         } else if (Name[0] == 'f' && (Name == "fabs" || Name == "fabsf")) {
2124           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
2125               I.getOperand(1)->getType()->isFloatingPoint() &&
2126               I.getType() == I.getOperand(1)->getType()) {
2127             SDOperand Tmp = getValue(I.getOperand(1));
2128             setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
2129             return;
2130           }
2131         } else if (Name[0] == 's' && (Name == "sin" || Name == "sinf")) {
2132           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
2133               I.getOperand(1)->getType()->isFloatingPoint() &&
2134               I.getType() == I.getOperand(1)->getType()) {
2135             SDOperand Tmp = getValue(I.getOperand(1));
2136             setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
2137             return;
2138           }
2139         } else if (Name[0] == 'c' && (Name == "cos" || Name == "cosf")) {
2140           if (I.getNumOperands() == 2 &&   // Basic sanity checks.
2141               I.getOperand(1)->getType()->isFloatingPoint() &&
2142               I.getType() == I.getOperand(1)->getType()) {
2143             SDOperand Tmp = getValue(I.getOperand(1));
2144             setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
2145             return;
2146           }
2147         }
2148       }
2149   } else if (isa<InlineAsm>(I.getOperand(0))) {
2150     visitInlineAsm(I);
2151     return;
2152   }
2153
2154   const PointerType *PT = cast<PointerType>(I.getCalledValue()->getType());
2155   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
2156
2157   SDOperand Callee;
2158   if (!RenameFn)
2159     Callee = getValue(I.getOperand(0));
2160   else
2161     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
2162   TargetLowering::ArgListTy Args;
2163   TargetLowering::ArgListEntry Entry;
2164   Args.reserve(I.getNumOperands());
2165   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2166     Value *Arg = I.getOperand(i);
2167     SDOperand ArgNode = getValue(Arg);
2168     Entry.Node = ArgNode; Entry.Ty = Arg->getType();
2169     Entry.isSigned = FTy->paramHasAttr(i, FunctionType::SExtAttribute);
2170     Entry.isInReg  = FTy->paramHasAttr(i, FunctionType::InRegAttribute);
2171     Entry.isSRet   = FTy->paramHasAttr(i, FunctionType::StructRetAttribute);
2172     Args.push_back(Entry);
2173   }
2174
2175   std::pair<SDOperand,SDOperand> Result =
2176     TLI.LowerCallTo(getRoot(), I.getType(), 
2177                     FTy->paramHasAttr(0,FunctionType::SExtAttribute),
2178                     FTy->isVarArg(), I.getCallingConv(), I.isTailCall(), 
2179                     Callee, Args, DAG);
2180   if (I.getType() != Type::VoidTy)
2181     setValue(&I, Result.first);
2182   DAG.setRoot(Result.second);
2183 }
2184
2185 SDOperand RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
2186                                         SDOperand &Chain, SDOperand &Flag)const{
2187   SDOperand Val = DAG.getCopyFromReg(Chain, Regs[0], RegVT, Flag);
2188   Chain = Val.getValue(1);
2189   Flag  = Val.getValue(2);
2190   
2191   // If the result was expanded, copy from the top part.
2192   if (Regs.size() > 1) {
2193     assert(Regs.size() == 2 &&
2194            "Cannot expand to more than 2 elts yet!");
2195     SDOperand Hi = DAG.getCopyFromReg(Chain, Regs[1], RegVT, Flag);
2196     Chain = Hi.getValue(1);
2197     Flag  = Hi.getValue(2);
2198     if (DAG.getTargetLoweringInfo().isLittleEndian())
2199       return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Val, Hi);
2200     else
2201       return DAG.getNode(ISD::BUILD_PAIR, ValueVT, Hi, Val);
2202   }
2203
2204   // Otherwise, if the return value was promoted or extended, truncate it to the
2205   // appropriate type.
2206   if (RegVT == ValueVT)
2207     return Val;
2208   
2209   if (MVT::isInteger(RegVT)) {
2210     if (ValueVT < RegVT)
2211       return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
2212     else
2213       return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
2214   } else {
2215     return DAG.getNode(ISD::FP_ROUND, ValueVT, Val);
2216   }
2217 }
2218
2219 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
2220 /// specified value into the registers specified by this object.  This uses 
2221 /// Chain/Flag as the input and updates them for the output Chain/Flag.
2222 void RegsForValue::getCopyToRegs(SDOperand Val, SelectionDAG &DAG,
2223                                  SDOperand &Chain, SDOperand &Flag,
2224                                  MVT::ValueType PtrVT) const {
2225   if (Regs.size() == 1) {
2226     // If there is a single register and the types differ, this must be
2227     // a promotion.
2228     if (RegVT != ValueVT) {
2229       if (MVT::isInteger(RegVT)) {
2230         if (RegVT < ValueVT)
2231           Val = DAG.getNode(ISD::TRUNCATE, RegVT, Val);
2232         else
2233           Val = DAG.getNode(ISD::ANY_EXTEND, RegVT, Val);
2234       } else
2235         Val = DAG.getNode(ISD::FP_EXTEND, RegVT, Val);
2236     }
2237     Chain = DAG.getCopyToReg(Chain, Regs[0], Val, Flag);
2238     Flag = Chain.getValue(1);
2239   } else {
2240     std::vector<unsigned> R(Regs);
2241     if (!DAG.getTargetLoweringInfo().isLittleEndian())
2242       std::reverse(R.begin(), R.end());
2243     
2244     for (unsigned i = 0, e = R.size(); i != e; ++i) {
2245       SDOperand Part = DAG.getNode(ISD::EXTRACT_ELEMENT, RegVT, Val, 
2246                                    DAG.getConstant(i, PtrVT));
2247       Chain = DAG.getCopyToReg(Chain, R[i], Part, Flag);
2248       Flag = Chain.getValue(1);
2249     }
2250   }
2251 }
2252
2253 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
2254 /// operand list.  This adds the code marker and includes the number of 
2255 /// values added into it.
2256 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
2257                                         std::vector<SDOperand> &Ops) const {
2258   Ops.push_back(DAG.getConstant(Code | (Regs.size() << 3), MVT::i32));
2259   for (unsigned i = 0, e = Regs.size(); i != e; ++i)
2260     Ops.push_back(DAG.getRegister(Regs[i], RegVT));
2261 }
2262
2263 /// isAllocatableRegister - If the specified register is safe to allocate, 
2264 /// i.e. it isn't a stack pointer or some other special register, return the
2265 /// register class for the register.  Otherwise, return null.
2266 static const TargetRegisterClass *
2267 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
2268                       const TargetLowering &TLI, const MRegisterInfo *MRI) {
2269   MVT::ValueType FoundVT = MVT::Other;
2270   const TargetRegisterClass *FoundRC = 0;
2271   for (MRegisterInfo::regclass_iterator RCI = MRI->regclass_begin(),
2272        E = MRI->regclass_end(); RCI != E; ++RCI) {
2273     MVT::ValueType ThisVT = MVT::Other;
2274
2275     const TargetRegisterClass *RC = *RCI;
2276     // If none of the the value types for this register class are valid, we 
2277     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2278     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
2279          I != E; ++I) {
2280       if (TLI.isTypeLegal(*I)) {
2281         // If we have already found this register in a different register class,
2282         // choose the one with the largest VT specified.  For example, on
2283         // PowerPC, we favor f64 register classes over f32.
2284         if (FoundVT == MVT::Other || 
2285             MVT::getSizeInBits(FoundVT) < MVT::getSizeInBits(*I)) {
2286           ThisVT = *I;
2287           break;
2288         }
2289       }
2290     }
2291     
2292     if (ThisVT == MVT::Other) continue;
2293     
2294     // NOTE: This isn't ideal.  In particular, this might allocate the
2295     // frame pointer in functions that need it (due to them not being taken
2296     // out of allocation, because a variable sized allocation hasn't been seen
2297     // yet).  This is a slight code pessimization, but should still work.
2298     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
2299          E = RC->allocation_order_end(MF); I != E; ++I)
2300       if (*I == Reg) {
2301         // We found a matching register class.  Keep looking at others in case
2302         // we find one with larger registers that this physreg is also in.
2303         FoundRC = RC;
2304         FoundVT = ThisVT;
2305         break;
2306       }
2307   }
2308   return FoundRC;
2309 }    
2310
2311 RegsForValue SelectionDAGLowering::
2312 GetRegistersForValue(const std::string &ConstrCode,
2313                      MVT::ValueType VT, bool isOutReg, bool isInReg,
2314                      std::set<unsigned> &OutputRegs, 
2315                      std::set<unsigned> &InputRegs) {
2316   std::pair<unsigned, const TargetRegisterClass*> PhysReg = 
2317     TLI.getRegForInlineAsmConstraint(ConstrCode, VT);
2318   std::vector<unsigned> Regs;
2319
2320   unsigned NumRegs = VT != MVT::Other ? TLI.getNumElements(VT) : 1;
2321   MVT::ValueType RegVT;
2322   MVT::ValueType ValueVT = VT;
2323   
2324   // If this is a constraint for a specific physical register, like {r17},
2325   // assign it now.
2326   if (PhysReg.first) {
2327     if (VT == MVT::Other)
2328       ValueVT = *PhysReg.second->vt_begin();
2329     
2330     // Get the actual register value type.  This is important, because the user
2331     // may have asked for (e.g.) the AX register in i32 type.  We need to
2332     // remember that AX is actually i16 to get the right extension.
2333     RegVT = *PhysReg.second->vt_begin();
2334     
2335     // This is a explicit reference to a physical register.
2336     Regs.push_back(PhysReg.first);
2337
2338     // If this is an expanded reference, add the rest of the regs to Regs.
2339     if (NumRegs != 1) {
2340       TargetRegisterClass::iterator I = PhysReg.second->begin();
2341       TargetRegisterClass::iterator E = PhysReg.second->end();
2342       for (; *I != PhysReg.first; ++I)
2343         assert(I != E && "Didn't find reg!"); 
2344       
2345       // Already added the first reg.
2346       --NumRegs; ++I;
2347       for (; NumRegs; --NumRegs, ++I) {
2348         assert(I != E && "Ran out of registers to allocate!");
2349         Regs.push_back(*I);
2350       }
2351     }
2352     return RegsForValue(Regs, RegVT, ValueVT);
2353   }
2354   
2355   // Otherwise, if this was a reference to an LLVM register class, create vregs
2356   // for this reference.
2357   std::vector<unsigned> RegClassRegs;
2358   if (PhysReg.second) {
2359     // If this is an early clobber or tied register, our regalloc doesn't know
2360     // how to maintain the constraint.  If it isn't, go ahead and create vreg
2361     // and let the regalloc do the right thing.
2362     if (!isOutReg || !isInReg) {
2363       if (VT == MVT::Other)
2364         ValueVT = *PhysReg.second->vt_begin();
2365       RegVT = *PhysReg.second->vt_begin();
2366
2367       // Create the appropriate number of virtual registers.
2368       SSARegMap *RegMap = DAG.getMachineFunction().getSSARegMap();
2369       for (; NumRegs; --NumRegs)
2370         Regs.push_back(RegMap->createVirtualRegister(PhysReg.second));
2371       
2372       return RegsForValue(Regs, RegVT, ValueVT);
2373     }
2374     
2375     // Otherwise, we can't allocate it.  Let the code below figure out how to
2376     // maintain these constraints.
2377     RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
2378     
2379   } else {
2380     // This is a reference to a register class that doesn't directly correspond
2381     // to an LLVM register class.  Allocate NumRegs consecutive, available,
2382     // registers from the class.
2383     RegClassRegs = TLI.getRegClassForInlineAsmConstraint(ConstrCode, VT);
2384   }
2385
2386   const MRegisterInfo *MRI = DAG.getTarget().getRegisterInfo();
2387   MachineFunction &MF = *CurMBB->getParent();
2388   unsigned NumAllocated = 0;
2389   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
2390     unsigned Reg = RegClassRegs[i];
2391     // See if this register is available.
2392     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
2393         (isInReg  && InputRegs.count(Reg))) {    // Already used.
2394       // Make sure we find consecutive registers.
2395       NumAllocated = 0;
2396       continue;
2397     }
2398     
2399     // Check to see if this register is allocatable (i.e. don't give out the
2400     // stack pointer).
2401     const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, MRI);
2402     if (!RC) {
2403       // Make sure we find consecutive registers.
2404       NumAllocated = 0;
2405       continue;
2406     }
2407     
2408     // Okay, this register is good, we can use it.
2409     ++NumAllocated;
2410
2411     // If we allocated enough consecutive   
2412     if (NumAllocated == NumRegs) {
2413       unsigned RegStart = (i-NumAllocated)+1;
2414       unsigned RegEnd   = i+1;
2415       // Mark all of the allocated registers used.
2416       for (unsigned i = RegStart; i != RegEnd; ++i) {
2417         unsigned Reg = RegClassRegs[i];
2418         Regs.push_back(Reg);
2419         if (isOutReg) OutputRegs.insert(Reg);    // Mark reg used.
2420         if (isInReg)  InputRegs.insert(Reg);     // Mark reg used.
2421       }
2422       
2423       return RegsForValue(Regs, *RC->vt_begin(), VT);
2424     }
2425   }
2426   
2427   // Otherwise, we couldn't allocate enough registers for this.
2428   return RegsForValue();
2429 }
2430
2431
2432 /// visitInlineAsm - Handle a call to an InlineAsm object.
2433 ///
2434 void SelectionDAGLowering::visitInlineAsm(CallInst &I) {
2435   InlineAsm *IA = cast<InlineAsm>(I.getOperand(0));
2436   
2437   SDOperand AsmStr = DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
2438                                                  MVT::Other);
2439
2440   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
2441   std::vector<MVT::ValueType> ConstraintVTs;
2442   
2443   /// AsmNodeOperands - A list of pairs.  The first element is a register, the
2444   /// second is a bitfield where bit #0 is set if it is a use and bit #1 is set
2445   /// if it is a def of that register.
2446   std::vector<SDOperand> AsmNodeOperands;
2447   AsmNodeOperands.push_back(SDOperand());  // reserve space for input chain
2448   AsmNodeOperands.push_back(AsmStr);
2449   
2450   SDOperand Chain = getRoot();
2451   SDOperand Flag;
2452   
2453   // We fully assign registers here at isel time.  This is not optimal, but
2454   // should work.  For register classes that correspond to LLVM classes, we
2455   // could let the LLVM RA do its thing, but we currently don't.  Do a prepass
2456   // over the constraints, collecting fixed registers that we know we can't use.
2457   std::set<unsigned> OutputRegs, InputRegs;
2458   unsigned OpNum = 1;
2459   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2460     assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2461     std::string &ConstraintCode = Constraints[i].Codes[0];
2462     
2463     MVT::ValueType OpVT;
2464
2465     // Compute the value type for each operand and add it to ConstraintVTs.
2466     switch (Constraints[i].Type) {
2467     case InlineAsm::isOutput:
2468       if (!Constraints[i].isIndirectOutput) {
2469         assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2470         OpVT = TLI.getValueType(I.getType());
2471       } else {
2472         const Type *OpTy = I.getOperand(OpNum)->getType();
2473         OpVT = TLI.getValueType(cast<PointerType>(OpTy)->getElementType());
2474         OpNum++;  // Consumes a call operand.
2475       }
2476       break;
2477     case InlineAsm::isInput:
2478       OpVT = TLI.getValueType(I.getOperand(OpNum)->getType());
2479       OpNum++;  // Consumes a call operand.
2480       break;
2481     case InlineAsm::isClobber:
2482       OpVT = MVT::Other;
2483       break;
2484     }
2485     
2486     ConstraintVTs.push_back(OpVT);
2487
2488     if (TLI.getRegForInlineAsmConstraint(ConstraintCode, OpVT).first == 0)
2489       continue;  // Not assigned a fixed reg.
2490     
2491     // Build a list of regs that this operand uses.  This always has a single
2492     // element for promoted/expanded operands.
2493     RegsForValue Regs = GetRegistersForValue(ConstraintCode, OpVT,
2494                                              false, false,
2495                                              OutputRegs, InputRegs);
2496     
2497     switch (Constraints[i].Type) {
2498     case InlineAsm::isOutput:
2499       // We can't assign any other output to this register.
2500       OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2501       // If this is an early-clobber output, it cannot be assigned to the same
2502       // value as the input reg.
2503       if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2504         InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2505       break;
2506     case InlineAsm::isInput:
2507       // We can't assign any other input to this register.
2508       InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2509       break;
2510     case InlineAsm::isClobber:
2511       // Clobbered regs cannot be used as inputs or outputs.
2512       InputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2513       OutputRegs.insert(Regs.Regs.begin(), Regs.Regs.end());
2514       break;
2515     }
2516   }      
2517   
2518   // Loop over all of the inputs, copying the operand values into the
2519   // appropriate registers and processing the output regs.
2520   RegsForValue RetValRegs;
2521   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
2522   OpNum = 1;
2523   
2524   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
2525     assert(Constraints[i].Codes.size() == 1 && "Only handles one code so far!");
2526     std::string &ConstraintCode = Constraints[i].Codes[0];
2527
2528     switch (Constraints[i].Type) {
2529     case InlineAsm::isOutput: {
2530       TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2531       if (ConstraintCode.size() == 1)   // not a physreg name.
2532         CTy = TLI.getConstraintType(ConstraintCode[0]);
2533       
2534       if (CTy == TargetLowering::C_Memory) {
2535         // Memory output.
2536         SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2537         
2538         // Check that the operand (the address to store to) isn't a float.
2539         if (!MVT::isInteger(InOperandVal.getValueType()))
2540           assert(0 && "MATCH FAIL!");
2541         
2542         if (!Constraints[i].isIndirectOutput)
2543           assert(0 && "MATCH FAIL!");
2544
2545         OpNum++;  // Consumes a call operand.
2546         
2547         // Extend/truncate to the right pointer type if needed.
2548         MVT::ValueType PtrType = TLI.getPointerTy();
2549         if (InOperandVal.getValueType() < PtrType)
2550           InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2551         else if (InOperandVal.getValueType() > PtrType)
2552           InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2553         
2554         // Add information to the INLINEASM node to know about this output.
2555         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2556         AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2557         AsmNodeOperands.push_back(InOperandVal);
2558         break;
2559       }
2560
2561       // Otherwise, this is a register output.
2562       assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2563
2564       // If this is an early-clobber output, or if there is an input
2565       // constraint that matches this, we need to reserve the input register
2566       // so no other inputs allocate to it.
2567       bool UsesInputRegister = false;
2568       if (Constraints[i].isEarlyClobber || Constraints[i].hasMatchingInput)
2569         UsesInputRegister = true;
2570       
2571       // Copy the output from the appropriate register.  Find a register that
2572       // we can use.
2573       RegsForValue Regs =
2574         GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2575                              true, UsesInputRegister, 
2576                              OutputRegs, InputRegs);
2577       if (Regs.Regs.empty()) {
2578         cerr << "Couldn't allocate output reg for contraint '"
2579              << ConstraintCode << "'!\n";
2580         exit(1);
2581       }
2582
2583       if (!Constraints[i].isIndirectOutput) {
2584         assert(RetValRegs.Regs.empty() &&
2585                "Cannot have multiple output constraints yet!");
2586         assert(I.getType() != Type::VoidTy && "Bad inline asm!");
2587         RetValRegs = Regs;
2588       } else {
2589         IndirectStoresToEmit.push_back(std::make_pair(Regs, 
2590                                                       I.getOperand(OpNum)));
2591         OpNum++;  // Consumes a call operand.
2592       }
2593       
2594       // Add information to the INLINEASM node to know that this register is
2595       // set.
2596       Regs.AddInlineAsmOperands(2 /*REGDEF*/, DAG, AsmNodeOperands);
2597       break;
2598     }
2599     case InlineAsm::isInput: {
2600       SDOperand InOperandVal = getValue(I.getOperand(OpNum));
2601       OpNum++;  // Consumes a call operand.
2602       
2603       if (isdigit(ConstraintCode[0])) {    // Matching constraint?
2604         // If this is required to match an output register we have already set,
2605         // just use its register.
2606         unsigned OperandNo = atoi(ConstraintCode.c_str());
2607         
2608         // Scan until we find the definition we already emitted of this operand.
2609         // When we find it, create a RegsForValue operand.
2610         unsigned CurOp = 2;  // The first operand.
2611         for (; OperandNo; --OperandNo) {
2612           // Advance to the next operand.
2613           unsigned NumOps = 
2614             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2615           assert(((NumOps & 7) == 2 /*REGDEF*/ ||
2616                   (NumOps & 7) == 4 /*MEM*/) &&
2617                  "Skipped past definitions?");
2618           CurOp += (NumOps>>3)+1;
2619         }
2620
2621         unsigned NumOps = 
2622           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
2623         assert((NumOps & 7) == 2 /*REGDEF*/ &&
2624                "Skipped past definitions?");
2625         
2626         // Add NumOps>>3 registers to MatchedRegs.
2627         RegsForValue MatchedRegs;
2628         MatchedRegs.ValueVT = InOperandVal.getValueType();
2629         MatchedRegs.RegVT   = AsmNodeOperands[CurOp+1].getValueType();
2630         for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
2631           unsigned Reg=cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
2632           MatchedRegs.Regs.push_back(Reg);
2633         }
2634         
2635         // Use the produced MatchedRegs object to 
2636         MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag,
2637                                   TLI.getPointerTy());
2638         MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
2639         break;
2640       }
2641       
2642       TargetLowering::ConstraintType CTy = TargetLowering::C_RegisterClass;
2643       if (ConstraintCode.size() == 1)   // not a physreg name.
2644         CTy = TLI.getConstraintType(ConstraintCode[0]);
2645         
2646       if (CTy == TargetLowering::C_Other) {
2647         InOperandVal = TLI.isOperandValidForConstraint(InOperandVal,
2648                                                        ConstraintCode[0], DAG);
2649         if (!InOperandVal.Val) {
2650           cerr << "Invalid operand for inline asm constraint '"
2651                << ConstraintCode << "'!\n";
2652           exit(1);
2653         }
2654         
2655         // Add information to the INLINEASM node to know about this input.
2656         unsigned ResOpType = 3 /*IMM*/ | (1 << 3);
2657         AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2658         AsmNodeOperands.push_back(InOperandVal);
2659         break;
2660       } else if (CTy == TargetLowering::C_Memory) {
2661         // Memory input.
2662         
2663         // Check that the operand isn't a float.
2664         if (!MVT::isInteger(InOperandVal.getValueType()))
2665           assert(0 && "MATCH FAIL!");
2666         
2667         // Extend/truncate to the right pointer type if needed.
2668         MVT::ValueType PtrType = TLI.getPointerTy();
2669         if (InOperandVal.getValueType() < PtrType)
2670           InOperandVal = DAG.getNode(ISD::ZERO_EXTEND, PtrType, InOperandVal);
2671         else if (InOperandVal.getValueType() > PtrType)
2672           InOperandVal = DAG.getNode(ISD::TRUNCATE, PtrType, InOperandVal);
2673
2674         // Add information to the INLINEASM node to know about this input.
2675         unsigned ResOpType = 4/*MEM*/ | (1 << 3);
2676         AsmNodeOperands.push_back(DAG.getConstant(ResOpType, MVT::i32));
2677         AsmNodeOperands.push_back(InOperandVal);
2678         break;
2679       }
2680         
2681       assert(CTy == TargetLowering::C_RegisterClass && "Unknown op type!");
2682
2683       // Copy the input into the appropriate registers.
2684       RegsForValue InRegs =
2685         GetRegistersForValue(ConstraintCode, ConstraintVTs[i],
2686                              false, true, OutputRegs, InputRegs);
2687       // FIXME: should be match fail.
2688       assert(!InRegs.Regs.empty() && "Couldn't allocate input reg!");
2689
2690       InRegs.getCopyToRegs(InOperandVal, DAG, Chain, Flag, TLI.getPointerTy());
2691       
2692       InRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG, AsmNodeOperands);
2693       break;
2694     }
2695     case InlineAsm::isClobber: {
2696       RegsForValue ClobberedRegs =
2697         GetRegistersForValue(ConstraintCode, MVT::Other, false, false,
2698                              OutputRegs, InputRegs);
2699       // Add the clobbered value to the operand list, so that the register
2700       // allocator is aware that the physreg got clobbered.
2701       if (!ClobberedRegs.Regs.empty())
2702         ClobberedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG, AsmNodeOperands);
2703       break;
2704     }
2705     }
2706   }
2707   
2708   // Finish up input operands.
2709   AsmNodeOperands[0] = Chain;
2710   if (Flag.Val) AsmNodeOperands.push_back(Flag);
2711   
2712   Chain = DAG.getNode(ISD::INLINEASM, 
2713                       DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
2714                       &AsmNodeOperands[0], AsmNodeOperands.size());
2715   Flag = Chain.getValue(1);
2716
2717   // If this asm returns a register value, copy the result from that register
2718   // and set it as the value of the call.
2719   if (!RetValRegs.Regs.empty())
2720     setValue(&I, RetValRegs.getCopyFromRegs(DAG, Chain, Flag));
2721   
2722   std::vector<std::pair<SDOperand, Value*> > StoresToEmit;
2723   
2724   // Process indirect outputs, first output all of the flagged copies out of
2725   // physregs.
2726   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
2727     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
2728     Value *Ptr = IndirectStoresToEmit[i].second;
2729     SDOperand OutVal = OutRegs.getCopyFromRegs(DAG, Chain, Flag);
2730     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
2731   }
2732   
2733   // Emit the non-flagged stores from the physregs.
2734   SmallVector<SDOperand, 8> OutChains;
2735   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
2736     OutChains.push_back(DAG.getStore(Chain,  StoresToEmit[i].first,
2737                                     getValue(StoresToEmit[i].second),
2738                                     StoresToEmit[i].second, 0));
2739   if (!OutChains.empty())
2740     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2741                         &OutChains[0], OutChains.size());
2742   DAG.setRoot(Chain);
2743 }
2744
2745
2746 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
2747   SDOperand Src = getValue(I.getOperand(0));
2748
2749   MVT::ValueType IntPtr = TLI.getPointerTy();
2750
2751   if (IntPtr < Src.getValueType())
2752     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
2753   else if (IntPtr > Src.getValueType())
2754     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
2755
2756   // Scale the source by the type size.
2757   uint64_t ElementSize = TD->getTypeSize(I.getType()->getElementType());
2758   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
2759                     Src, getIntPtrConstant(ElementSize));
2760
2761   TargetLowering::ArgListTy Args;
2762   TargetLowering::ArgListEntry Entry;
2763   Entry.Node = Src;
2764   Entry.Ty = TLI.getTargetData()->getIntPtrType();
2765   Entry.isSigned = false;
2766   Entry.isInReg = false;
2767   Entry.isSRet = false;
2768   Args.push_back(Entry);
2769
2770   std::pair<SDOperand,SDOperand> Result =
2771     TLI.LowerCallTo(getRoot(), I.getType(), false, false, CallingConv::C, true,
2772                     DAG.getExternalSymbol("malloc", IntPtr),
2773                     Args, DAG);
2774   setValue(&I, Result.first);  // Pointers always fit in registers
2775   DAG.setRoot(Result.second);
2776 }
2777
2778 void SelectionDAGLowering::visitFree(FreeInst &I) {
2779   TargetLowering::ArgListTy Args;
2780   TargetLowering::ArgListEntry Entry;
2781   Entry.Node = getValue(I.getOperand(0));
2782   Entry.Ty = TLI.getTargetData()->getIntPtrType();
2783   Entry.isSigned = false;
2784   Entry.isInReg = false;
2785   Entry.isSRet = false;
2786   Args.push_back(Entry);
2787   MVT::ValueType IntPtr = TLI.getPointerTy();
2788   std::pair<SDOperand,SDOperand> Result =
2789     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, CallingConv::C, true,
2790                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
2791   DAG.setRoot(Result.second);
2792 }
2793
2794 // InsertAtEndOfBasicBlock - This method should be implemented by targets that
2795 // mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
2796 // instructions are special in various ways, which require special support to
2797 // insert.  The specified MachineInstr is created but not inserted into any
2798 // basic blocks, and the scheduler passes ownership of it to this method.
2799 MachineBasicBlock *TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
2800                                                        MachineBasicBlock *MBB) {
2801   cerr << "If a target marks an instruction with "
2802        << "'usesCustomDAGSchedInserter', it must implement "
2803        << "TargetLowering::InsertAtEndOfBasicBlock!\n";
2804   abort();
2805   return 0;  
2806 }
2807
2808 void SelectionDAGLowering::visitVAStart(CallInst &I) {
2809   DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(), 
2810                           getValue(I.getOperand(1)), 
2811                           DAG.getSrcValue(I.getOperand(1))));
2812 }
2813
2814 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
2815   SDOperand V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
2816                              getValue(I.getOperand(0)),
2817                              DAG.getSrcValue(I.getOperand(0)));
2818   setValue(&I, V);
2819   DAG.setRoot(V.getValue(1));
2820 }
2821
2822 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
2823   DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
2824                           getValue(I.getOperand(1)), 
2825                           DAG.getSrcValue(I.getOperand(1))));
2826 }
2827
2828 void SelectionDAGLowering::visitVACopy(CallInst &I) {
2829   DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(), 
2830                           getValue(I.getOperand(1)), 
2831                           getValue(I.getOperand(2)),
2832                           DAG.getSrcValue(I.getOperand(1)),
2833                           DAG.getSrcValue(I.getOperand(2))));
2834 }
2835
2836 /// ExpandScalarFormalArgs - Recursively expand the formal_argument node, either
2837 /// bit_convert it or join a pair of them with a BUILD_PAIR when appropriate.
2838 static SDOperand ExpandScalarFormalArgs(MVT::ValueType VT, SDNode *Arg,
2839                                         unsigned &i, SelectionDAG &DAG,
2840                                         TargetLowering &TLI) {
2841   if (TLI.getTypeAction(VT) != TargetLowering::Expand)
2842     return SDOperand(Arg, i++);
2843
2844   MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
2845   unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
2846   if (NumVals == 1) {
2847     return DAG.getNode(ISD::BIT_CONVERT, VT,
2848                        ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI));
2849   } else if (NumVals == 2) {
2850     SDOperand Lo = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2851     SDOperand Hi = ExpandScalarFormalArgs(EVT, Arg, i, DAG, TLI);
2852     if (!TLI.isLittleEndian())
2853       std::swap(Lo, Hi);
2854     return DAG.getNode(ISD::BUILD_PAIR, VT, Lo, Hi);
2855   } else {
2856     // Value scalarized into many values.  Unimp for now.
2857     assert(0 && "Cannot expand i64 -> i16 yet!");
2858   }
2859   return SDOperand();
2860 }
2861
2862 /// TargetLowering::LowerArguments - This is the default LowerArguments
2863 /// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
2864 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be 
2865 /// integrated into SDISel.
2866 std::vector<SDOperand> 
2867 TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
2868   const FunctionType *FTy = F.getFunctionType();
2869   // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
2870   std::vector<SDOperand> Ops;
2871   Ops.push_back(DAG.getRoot());
2872   Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
2873   Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
2874
2875   // Add one result value for each formal argument.
2876   std::vector<MVT::ValueType> RetVals;
2877   unsigned j = 0;
2878   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
2879     MVT::ValueType VT = getValueType(I->getType());
2880     bool isInReg = FTy->paramHasAttr(++j, FunctionType::InRegAttribute);
2881     bool isSRet  = FTy->paramHasAttr(j, FunctionType::StructRetAttribute);
2882     unsigned Flags = (isInReg << 1) | (isSRet << 2);
2883     
2884     switch (getTypeAction(VT)) {
2885     default: assert(0 && "Unknown type action!");
2886     case Legal: 
2887       RetVals.push_back(VT);
2888       Ops.push_back(DAG.getConstant(Flags, MVT::i32));
2889       break;
2890     case Promote:
2891       RetVals.push_back(getTypeToTransformTo(VT));
2892       Ops.push_back(DAG.getConstant(Flags, MVT::i32));
2893       break;
2894     case Expand:
2895       if (VT != MVT::Vector) {
2896         // If this is a large integer, it needs to be broken up into small
2897         // integers.  Figure out what the destination type is and how many small
2898         // integers it turns into.
2899         MVT::ValueType NVT = getTypeToExpandTo(VT);
2900         unsigned NumVals = getNumElements(VT);
2901         for (unsigned i = 0; i != NumVals; ++i) {
2902           RetVals.push_back(NVT);
2903           Ops.push_back(DAG.getConstant(Flags, MVT::i32));
2904         }
2905       } else {
2906         // Otherwise, this is a vector type.  We only support legal vectors
2907         // right now.
2908         unsigned NumElems = cast<PackedType>(I->getType())->getNumElements();
2909         const Type *EltTy = cast<PackedType>(I->getType())->getElementType();
2910
2911         // Figure out if there is a Packed type corresponding to this Vector
2912         // type.  If so, convert to the packed type.
2913         MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2914         if (TVT != MVT::Other && isTypeLegal(TVT)) {
2915           RetVals.push_back(TVT);
2916           Ops.push_back(DAG.getConstant(Flags, MVT::i32));
2917         } else {
2918           assert(0 && "Don't support illegal by-val vector arguments yet!");
2919         }
2920       }
2921       break;
2922     }
2923   }
2924
2925   RetVals.push_back(MVT::Other);
2926   
2927   // Create the node.
2928   SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
2929                                DAG.getNodeValueTypes(RetVals), RetVals.size(),
2930                                &Ops[0], Ops.size()).Val;
2931   
2932   DAG.setRoot(SDOperand(Result, Result->getNumValues()-1));
2933
2934   // Set up the return result vector.
2935   Ops.clear();
2936   unsigned i = 0;
2937   unsigned Idx = 1;
2938   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 
2939       ++I, ++Idx) {
2940     MVT::ValueType VT = getValueType(I->getType());
2941     
2942     switch (getTypeAction(VT)) {
2943     default: assert(0 && "Unknown type action!");
2944     case Legal: 
2945       Ops.push_back(SDOperand(Result, i++));
2946       break;
2947     case Promote: {
2948       SDOperand Op(Result, i++);
2949       if (MVT::isInteger(VT)) {
2950         if (FTy->paramHasAttr(Idx, FunctionType::SExtAttribute))
2951           Op = DAG.getNode(ISD::AssertSext, Op.getValueType(), Op,
2952                            DAG.getValueType(VT));
2953         else if (FTy->paramHasAttr(Idx, FunctionType::ZExtAttribute))
2954           Op = DAG.getNode(ISD::AssertZext, Op.getValueType(), Op,
2955                            DAG.getValueType(VT));
2956         Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2957       } else {
2958         assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
2959         Op = DAG.getNode(ISD::FP_ROUND, VT, Op);
2960       }
2961       Ops.push_back(Op);
2962       break;
2963     }
2964     case Expand:
2965       if (VT != MVT::Vector) {
2966         // If this is a large integer or a floating point node that needs to be
2967         // expanded, it needs to be reassembled from small integers.  Figure out
2968         // what the source elt type is and how many small integers it is.
2969         Ops.push_back(ExpandScalarFormalArgs(VT, Result, i, DAG, *this));
2970       } else {
2971         // Otherwise, this is a vector type.  We only support legal vectors
2972         // right now.
2973         const PackedType *PTy = cast<PackedType>(I->getType());
2974         unsigned NumElems = PTy->getNumElements();
2975         const Type *EltTy = PTy->getElementType();
2976
2977         // Figure out if there is a Packed type corresponding to this Vector
2978         // type.  If so, convert to the packed type.
2979         MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
2980         if (TVT != MVT::Other && isTypeLegal(TVT)) {
2981           SDOperand N = SDOperand(Result, i++);
2982           // Handle copies from generic vectors to registers.
2983           N = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, N,
2984                           DAG.getConstant(NumElems, MVT::i32), 
2985                           DAG.getValueType(getValueType(EltTy)));
2986           Ops.push_back(N);
2987         } else {
2988           assert(0 && "Don't support illegal by-val vector arguments yet!");
2989           abort();
2990         }
2991       }
2992       break;
2993     }
2994   }
2995   return Ops;
2996 }
2997
2998
2999 /// ExpandScalarCallArgs - Recursively expand call argument node by
3000 /// bit_converting it or extract a pair of elements from the larger  node.
3001 static void ExpandScalarCallArgs(MVT::ValueType VT, SDOperand Arg,
3002                                  unsigned Flags, 
3003                                  SmallVector<SDOperand, 32> &Ops,
3004                                  SelectionDAG &DAG,
3005                                  TargetLowering &TLI) {
3006   if (TLI.getTypeAction(VT) != TargetLowering::Expand) {
3007     Ops.push_back(Arg);
3008     Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3009     return;
3010   }
3011
3012   MVT::ValueType EVT = TLI.getTypeToTransformTo(VT);
3013   unsigned NumVals = MVT::getSizeInBits(VT) / MVT::getSizeInBits(EVT);
3014   if (NumVals == 1) {
3015     Arg = DAG.getNode(ISD::BIT_CONVERT, EVT, Arg);
3016     ExpandScalarCallArgs(EVT, Arg, Flags, Ops, DAG, TLI);
3017   } else if (NumVals == 2) {
3018     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3019                                DAG.getConstant(0, TLI.getPointerTy()));
3020     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, EVT, Arg,
3021                                DAG.getConstant(1, TLI.getPointerTy()));
3022     if (!TLI.isLittleEndian())
3023       std::swap(Lo, Hi);
3024     ExpandScalarCallArgs(EVT, Lo, Flags, Ops, DAG, TLI);
3025     ExpandScalarCallArgs(EVT, Hi, Flags, Ops, DAG, TLI);
3026   } else {
3027     // Value scalarized into many values.  Unimp for now.
3028     assert(0 && "Cannot expand i64 -> i16 yet!");
3029   }
3030 }
3031
3032 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
3033 /// implementation, which just inserts an ISD::CALL node, which is later custom
3034 /// lowered by the target to something concrete.  FIXME: When all targets are
3035 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
3036 std::pair<SDOperand, SDOperand>
3037 TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy, 
3038                             bool RetTyIsSigned, bool isVarArg,
3039                             unsigned CallingConv, bool isTailCall, 
3040                             SDOperand Callee,
3041                             ArgListTy &Args, SelectionDAG &DAG) {
3042   SmallVector<SDOperand, 32> Ops;
3043   Ops.push_back(Chain);   // Op#0 - Chain
3044   Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
3045   Ops.push_back(DAG.getConstant(isVarArg, getPointerTy()));    // Op#2 - VarArg
3046   Ops.push_back(DAG.getConstant(isTailCall, getPointerTy()));  // Op#3 - Tail
3047   Ops.push_back(Callee);
3048   
3049   // Handle all of the outgoing arguments.
3050   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
3051     MVT::ValueType VT = getValueType(Args[i].Ty);
3052     SDOperand Op = Args[i].Node;
3053     bool isSigned = Args[i].isSigned;
3054     bool isInReg = Args[i].isInReg;
3055     bool isSRet  = Args[i].isSRet; 
3056     unsigned Flags = (isSRet << 2) | (isInReg << 1) | isSigned;
3057     switch (getTypeAction(VT)) {
3058     default: assert(0 && "Unknown type action!");
3059     case Legal: 
3060       Ops.push_back(Op);
3061       Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3062       break;
3063     case Promote:
3064       if (MVT::isInteger(VT)) {
3065         unsigned ExtOp = isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND; 
3066         Op = DAG.getNode(ExtOp, getTypeToTransformTo(VT), Op);
3067       } else {
3068         assert(MVT::isFloatingPoint(VT) && "Not int or FP?");
3069         Op = DAG.getNode(ISD::FP_EXTEND, getTypeToTransformTo(VT), Op);
3070       }
3071       Ops.push_back(Op);
3072       Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3073       break;
3074     case Expand:
3075       if (VT != MVT::Vector) {
3076         // If this is a large integer, it needs to be broken down into small
3077         // integers.  Figure out what the source elt type is and how many small
3078         // integers it is.
3079         ExpandScalarCallArgs(VT, Op, Flags, Ops, DAG, *this);
3080       } else {
3081         // Otherwise, this is a vector type.  We only support legal vectors
3082         // right now.
3083         const PackedType *PTy = cast<PackedType>(Args[i].Ty);
3084         unsigned NumElems = PTy->getNumElements();
3085         const Type *EltTy = PTy->getElementType();
3086         
3087         // Figure out if there is a Packed type corresponding to this Vector
3088         // type.  If so, convert to the packed type.
3089         MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3090         if (TVT != MVT::Other && isTypeLegal(TVT)) {
3091           // Insert a VBIT_CONVERT of the MVT::Vector type to the packed type.
3092           Op = DAG.getNode(ISD::VBIT_CONVERT, TVT, Op);
3093           Ops.push_back(Op);
3094           Ops.push_back(DAG.getConstant(Flags, MVT::i32));
3095         } else {
3096           assert(0 && "Don't support illegal by-val vector call args yet!");
3097           abort();
3098         }
3099       }
3100       break;
3101     }
3102   }
3103   
3104   // Figure out the result value types.
3105   SmallVector<MVT::ValueType, 4> RetTys;
3106
3107   if (RetTy != Type::VoidTy) {
3108     MVT::ValueType VT = getValueType(RetTy);
3109     switch (getTypeAction(VT)) {
3110     default: assert(0 && "Unknown type action!");
3111     case Legal:
3112       RetTys.push_back(VT);
3113       break;
3114     case Promote:
3115       RetTys.push_back(getTypeToTransformTo(VT));
3116       break;
3117     case Expand:
3118       if (VT != MVT::Vector) {
3119         // If this is a large integer, it needs to be reassembled from small
3120         // integers.  Figure out what the source elt type is and how many small
3121         // integers it is.
3122         MVT::ValueType NVT = getTypeToExpandTo(VT);
3123         unsigned NumVals = getNumElements(VT);
3124         for (unsigned i = 0; i != NumVals; ++i)
3125           RetTys.push_back(NVT);
3126       } else {
3127         // Otherwise, this is a vector type.  We only support legal vectors
3128         // right now.
3129         const PackedType *PTy = cast<PackedType>(RetTy);
3130         unsigned NumElems = PTy->getNumElements();
3131         const Type *EltTy = PTy->getElementType();
3132         
3133         // Figure out if there is a Packed type corresponding to this Vector
3134         // type.  If so, convert to the packed type.
3135         MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3136         if (TVT != MVT::Other && isTypeLegal(TVT)) {
3137           RetTys.push_back(TVT);
3138         } else {
3139           assert(0 && "Don't support illegal by-val vector call results yet!");
3140           abort();
3141         }
3142       }
3143     }    
3144   }
3145   
3146   RetTys.push_back(MVT::Other);  // Always has a chain.
3147   
3148   // Finally, create the CALL node.
3149   SDOperand Res = DAG.getNode(ISD::CALL,
3150                               DAG.getVTList(&RetTys[0], RetTys.size()),
3151                               &Ops[0], Ops.size());
3152   
3153   // This returns a pair of operands.  The first element is the
3154   // return value for the function (if RetTy is not VoidTy).  The second
3155   // element is the outgoing token chain.
3156   SDOperand ResVal;
3157   if (RetTys.size() != 1) {
3158     MVT::ValueType VT = getValueType(RetTy);
3159     if (RetTys.size() == 2) {
3160       ResVal = Res;
3161       
3162       // If this value was promoted, truncate it down.
3163       if (ResVal.getValueType() != VT) {
3164         if (VT == MVT::Vector) {
3165           // Insert a VBITCONVERT to convert from the packed result type to the
3166           // MVT::Vector type.
3167           unsigned NumElems = cast<PackedType>(RetTy)->getNumElements();
3168           const Type *EltTy = cast<PackedType>(RetTy)->getElementType();
3169           
3170           // Figure out if there is a Packed type corresponding to this Vector
3171           // type.  If so, convert to the packed type.
3172           MVT::ValueType TVT = MVT::getVectorType(getValueType(EltTy), NumElems);
3173           if (TVT != MVT::Other && isTypeLegal(TVT)) {
3174             // Insert a VBIT_CONVERT of the FORMAL_ARGUMENTS to a
3175             // "N x PTyElementVT" MVT::Vector type.
3176             ResVal = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, ResVal,
3177                                  DAG.getConstant(NumElems, MVT::i32), 
3178                                  DAG.getValueType(getValueType(EltTy)));
3179           } else {
3180             abort();
3181           }
3182         } else if (MVT::isInteger(VT)) {
3183           unsigned AssertOp = ISD::AssertSext;
3184           if (!RetTyIsSigned)
3185             AssertOp = ISD::AssertZext;
3186           ResVal = DAG.getNode(AssertOp, ResVal.getValueType(), ResVal, 
3187                                DAG.getValueType(VT));
3188           ResVal = DAG.getNode(ISD::TRUNCATE, VT, ResVal);
3189         } else {
3190           assert(MVT::isFloatingPoint(VT));
3191           if (getTypeAction(VT) == Expand)
3192             ResVal = DAG.getNode(ISD::BIT_CONVERT, VT, ResVal);
3193           else
3194             ResVal = DAG.getNode(ISD::FP_ROUND, VT, ResVal);
3195         }
3196       }
3197     } else if (RetTys.size() == 3) {
3198       ResVal = DAG.getNode(ISD::BUILD_PAIR, VT, 
3199                            Res.getValue(0), Res.getValue(1));
3200       
3201     } else {
3202       assert(0 && "Case not handled yet!");
3203     }
3204   }
3205   
3206   return std::make_pair(ResVal, Res.getValue(Res.Val->getNumValues()-1));
3207 }
3208
3209
3210
3211 // It is always conservatively correct for llvm.returnaddress and
3212 // llvm.frameaddress to return 0.
3213 //
3214 // FIXME: Change this to insert a FRAMEADDR/RETURNADDR node, and have that be
3215 // expanded to 0 if the target wants.
3216 std::pair<SDOperand, SDOperand>
3217 TargetLowering::LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain,
3218                                         unsigned Depth, SelectionDAG &DAG) {
3219   return std::make_pair(DAG.getConstant(0, getPointerTy()), Chain);
3220 }
3221
3222 SDOperand TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
3223   assert(0 && "LowerOperation not implemented for this target!");
3224   abort();
3225   return SDOperand();
3226 }
3227
3228 SDOperand TargetLowering::CustomPromoteOperation(SDOperand Op,
3229                                                  SelectionDAG &DAG) {
3230   assert(0 && "CustomPromoteOperation not implemented for this target!");
3231   abort();
3232   return SDOperand();
3233 }
3234
3235 void SelectionDAGLowering::visitFrameReturnAddress(CallInst &I, bool isFrame) {
3236   unsigned Depth = (unsigned)cast<ConstantInt>(I.getOperand(1))->getZExtValue();
3237   std::pair<SDOperand,SDOperand> Result =
3238     TLI.LowerFrameReturnAddress(isFrame, getRoot(), Depth, DAG);
3239   setValue(&I, Result.first);
3240   DAG.setRoot(Result.second);
3241 }
3242
3243 /// getMemsetValue - Vectorized representation of the memset value
3244 /// operand.
3245 static SDOperand getMemsetValue(SDOperand Value, MVT::ValueType VT,
3246                                 SelectionDAG &DAG) {
3247   MVT::ValueType CurVT = VT;
3248   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3249     uint64_t Val   = C->getValue() & 255;
3250     unsigned Shift = 8;
3251     while (CurVT != MVT::i8) {
3252       Val = (Val << Shift) | Val;
3253       Shift <<= 1;
3254       CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3255     }
3256     return DAG.getConstant(Val, VT);
3257   } else {
3258     Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
3259     unsigned Shift = 8;
3260     while (CurVT != MVT::i8) {
3261       Value =
3262         DAG.getNode(ISD::OR, VT,
3263                     DAG.getNode(ISD::SHL, VT, Value,
3264                                 DAG.getConstant(Shift, MVT::i8)), Value);
3265       Shift <<= 1;
3266       CurVT = (MVT::ValueType)((unsigned)CurVT - 1);
3267     }
3268
3269     return Value;
3270   }
3271 }
3272
3273 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3274 /// used when a memcpy is turned into a memset when the source is a constant
3275 /// string ptr.
3276 static SDOperand getMemsetStringVal(MVT::ValueType VT,
3277                                     SelectionDAG &DAG, TargetLowering &TLI,
3278                                     std::string &Str, unsigned Offset) {
3279   uint64_t Val = 0;
3280   unsigned MSB = getSizeInBits(VT) / 8;
3281   if (TLI.isLittleEndian())
3282     Offset = Offset + MSB - 1;
3283   for (unsigned i = 0; i != MSB; ++i) {
3284     Val = (Val << 8) | (unsigned char)Str[Offset];
3285     Offset += TLI.isLittleEndian() ? -1 : 1;
3286   }
3287   return DAG.getConstant(Val, VT);
3288 }
3289
3290 /// getMemBasePlusOffset - Returns base and offset node for the 
3291 static SDOperand getMemBasePlusOffset(SDOperand Base, unsigned Offset,
3292                                       SelectionDAG &DAG, TargetLowering &TLI) {
3293   MVT::ValueType VT = Base.getValueType();
3294   return DAG.getNode(ISD::ADD, VT, Base, DAG.getConstant(Offset, VT));
3295 }
3296
3297 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
3298 /// to replace the memset / memcpy is below the threshold. It also returns the
3299 /// types of the sequence of  memory ops to perform memset / memcpy.
3300 static bool MeetsMaxMemopRequirement(std::vector<MVT::ValueType> &MemOps,
3301                                      unsigned Limit, uint64_t Size,
3302                                      unsigned Align, TargetLowering &TLI) {
3303   MVT::ValueType VT;
3304
3305   if (TLI.allowsUnalignedMemoryAccesses()) {
3306     VT = MVT::i64;
3307   } else {
3308     switch (Align & 7) {
3309     case 0:
3310       VT = MVT::i64;
3311       break;
3312     case 4:
3313       VT = MVT::i32;
3314       break;
3315     case 2:
3316       VT = MVT::i16;
3317       break;
3318     default:
3319       VT = MVT::i8;
3320       break;
3321     }
3322   }
3323
3324   MVT::ValueType LVT = MVT::i64;
3325   while (!TLI.isTypeLegal(LVT))
3326     LVT = (MVT::ValueType)((unsigned)LVT - 1);
3327   assert(MVT::isInteger(LVT));
3328
3329   if (VT > LVT)
3330     VT = LVT;
3331
3332   unsigned NumMemOps = 0;
3333   while (Size != 0) {
3334     unsigned VTSize = getSizeInBits(VT) / 8;
3335     while (VTSize > Size) {
3336       VT = (MVT::ValueType)((unsigned)VT - 1);
3337       VTSize >>= 1;
3338     }
3339     assert(MVT::isInteger(VT));
3340
3341     if (++NumMemOps > Limit)
3342       return false;
3343     MemOps.push_back(VT);
3344     Size -= VTSize;
3345   }
3346
3347   return true;
3348 }
3349
3350 void SelectionDAGLowering::visitMemIntrinsic(CallInst &I, unsigned Op) {
3351   SDOperand Op1 = getValue(I.getOperand(1));
3352   SDOperand Op2 = getValue(I.getOperand(2));
3353   SDOperand Op3 = getValue(I.getOperand(3));
3354   SDOperand Op4 = getValue(I.getOperand(4));
3355   unsigned Align = (unsigned)cast<ConstantSDNode>(Op4)->getValue();
3356   if (Align == 0) Align = 1;
3357
3358   if (ConstantSDNode *Size = dyn_cast<ConstantSDNode>(Op3)) {
3359     std::vector<MVT::ValueType> MemOps;
3360
3361     // Expand memset / memcpy to a series of load / store ops
3362     // if the size operand falls below a certain threshold.
3363     SmallVector<SDOperand, 8> OutChains;
3364     switch (Op) {
3365     default: break;  // Do nothing for now.
3366     case ISD::MEMSET: {
3367       if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemset(),
3368                                    Size->getValue(), Align, TLI)) {
3369         unsigned NumMemOps = MemOps.size();
3370         unsigned Offset = 0;
3371         for (unsigned i = 0; i < NumMemOps; i++) {
3372           MVT::ValueType VT = MemOps[i];
3373           unsigned VTSize = getSizeInBits(VT) / 8;
3374           SDOperand Value = getMemsetValue(Op2, VT, DAG);
3375           SDOperand Store = DAG.getStore(getRoot(), Value,
3376                                     getMemBasePlusOffset(Op1, Offset, DAG, TLI),
3377                                          I.getOperand(1), Offset);
3378           OutChains.push_back(Store);
3379           Offset += VTSize;
3380         }
3381       }
3382       break;
3383     }
3384     case ISD::MEMCPY: {
3385       if (MeetsMaxMemopRequirement(MemOps, TLI.getMaxStoresPerMemcpy(),
3386                                    Size->getValue(), Align, TLI)) {
3387         unsigned NumMemOps = MemOps.size();
3388         unsigned SrcOff = 0, DstOff = 0, SrcDelta = 0;
3389         GlobalAddressSDNode *G = NULL;
3390         std::string Str;
3391         bool CopyFromStr = false;
3392
3393         if (Op2.getOpcode() == ISD::GlobalAddress)
3394           G = cast<GlobalAddressSDNode>(Op2);
3395         else if (Op2.getOpcode() == ISD::ADD &&
3396                  Op2.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3397                  Op2.getOperand(1).getOpcode() == ISD::Constant) {
3398           G = cast<GlobalAddressSDNode>(Op2.getOperand(0));
3399           SrcDelta = cast<ConstantSDNode>(Op2.getOperand(1))->getValue();
3400         }
3401         if (G) {
3402           GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3403           if (GV && GV->isConstant()) {
3404             Str = GV->getStringValue(false);
3405             if (!Str.empty()) {
3406               CopyFromStr = true;
3407               SrcOff += SrcDelta;
3408             }
3409           }
3410         }
3411
3412         for (unsigned i = 0; i < NumMemOps; i++) {
3413           MVT::ValueType VT = MemOps[i];
3414           unsigned VTSize = getSizeInBits(VT) / 8;
3415           SDOperand Value, Chain, Store;
3416
3417           if (CopyFromStr) {
3418             Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
3419             Chain = getRoot();
3420             Store =
3421               DAG.getStore(Chain, Value,
3422                            getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3423                            I.getOperand(1), DstOff);
3424           } else {
3425             Value = DAG.getLoad(VT, getRoot(),
3426                         getMemBasePlusOffset(Op2, SrcOff, DAG, TLI),
3427                         I.getOperand(2), SrcOff);
3428             Chain = Value.getValue(1);
3429             Store =
3430               DAG.getStore(Chain, Value,
3431                            getMemBasePlusOffset(Op1, DstOff, DAG, TLI),
3432                            I.getOperand(1), DstOff);
3433           }
3434           OutChains.push_back(Store);
3435           SrcOff += VTSize;
3436           DstOff += VTSize;
3437         }
3438       }
3439       break;
3440     }
3441     }
3442
3443     if (!OutChains.empty()) {
3444       DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
3445                   &OutChains[0], OutChains.size()));
3446       return;
3447     }
3448   }
3449
3450   DAG.setRoot(DAG.getNode(Op, MVT::Other, getRoot(), Op1, Op2, Op3, Op4));
3451 }
3452
3453 //===----------------------------------------------------------------------===//
3454 // SelectionDAGISel code
3455 //===----------------------------------------------------------------------===//
3456
3457 unsigned SelectionDAGISel::MakeReg(MVT::ValueType VT) {
3458   return RegMap->createVirtualRegister(TLI.getRegClassFor(VT));
3459 }
3460
3461 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
3462   // FIXME: we only modify the CFG to split critical edges.  This
3463   // updates dom and loop info.
3464   AU.addRequired<AliasAnalysis>();
3465 }
3466
3467
3468 /// OptimizeNoopCopyExpression - We have determined that the specified cast
3469 /// instruction is a noop copy (e.g. it's casting from one pointer type to
3470 /// another, int->uint, or int->sbyte on PPC.
3471 ///
3472 /// Return true if any changes are made.
3473 static bool OptimizeNoopCopyExpression(CastInst *CI) {
3474   BasicBlock *DefBB = CI->getParent();
3475   
3476   /// InsertedCasts - Only insert a cast in each block once.
3477   std::map<BasicBlock*, CastInst*> InsertedCasts;
3478   
3479   bool MadeChange = false;
3480   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end(); 
3481        UI != E; ) {
3482     Use &TheUse = UI.getUse();
3483     Instruction *User = cast<Instruction>(*UI);
3484     
3485     // Figure out which BB this cast is used in.  For PHI's this is the
3486     // appropriate predecessor block.
3487     BasicBlock *UserBB = User->getParent();
3488     if (PHINode *PN = dyn_cast<PHINode>(User)) {
3489       unsigned OpVal = UI.getOperandNo()/2;
3490       UserBB = PN->getIncomingBlock(OpVal);
3491     }
3492     
3493     // Preincrement use iterator so we don't invalidate it.
3494     ++UI;
3495     
3496     // If this user is in the same block as the cast, don't change the cast.
3497     if (UserBB == DefBB) continue;
3498     
3499     // If we have already inserted a cast into this block, use it.
3500     CastInst *&InsertedCast = InsertedCasts[UserBB];
3501
3502     if (!InsertedCast) {
3503       BasicBlock::iterator InsertPt = UserBB->begin();
3504       while (isa<PHINode>(InsertPt)) ++InsertPt;
3505       
3506       InsertedCast = 
3507         CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "", 
3508                          InsertPt);
3509       MadeChange = true;
3510     }
3511     
3512     // Replace a use of the cast with a use of the new casat.
3513     TheUse = InsertedCast;
3514   }
3515   
3516   // If we removed all uses, nuke the cast.
3517   if (CI->use_empty())
3518     CI->eraseFromParent();
3519   
3520   return MadeChange;
3521 }
3522
3523 /// InsertGEPComputeCode - Insert code into BB to compute Ptr+PtrOffset,
3524 /// casting to the type of GEPI.
3525 static Instruction *InsertGEPComputeCode(Instruction *&V, BasicBlock *BB,
3526                                          Instruction *GEPI, Value *Ptr,
3527                                          Value *PtrOffset) {
3528   if (V) return V;   // Already computed.
3529   
3530   // Figure out the insertion point
3531   BasicBlock::iterator InsertPt;
3532   if (BB == GEPI->getParent()) {
3533     // If GEP is already inserted into BB, insert right after the GEP.
3534     InsertPt = GEPI;
3535     ++InsertPt;
3536   } else {
3537     // Otherwise, insert at the top of BB, after any PHI nodes
3538     InsertPt = BB->begin();
3539     while (isa<PHINode>(InsertPt)) ++InsertPt;
3540   }
3541   
3542   // If Ptr is itself a cast, but in some other BB, emit a copy of the cast into
3543   // BB so that there is only one value live across basic blocks (the cast 
3544   // operand).
3545   if (CastInst *CI = dyn_cast<CastInst>(Ptr))
3546     if (CI->getParent() != BB && isa<PointerType>(CI->getOperand(0)->getType()))
3547       Ptr = CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(),
3548                              "", InsertPt);
3549   
3550   // Add the offset, cast it to the right type.
3551   Ptr = BinaryOperator::createAdd(Ptr, PtrOffset, "", InsertPt);
3552   // Ptr is an integer type, GEPI is pointer type ==> IntToPtr
3553   return V = CastInst::create(Instruction::IntToPtr, Ptr, GEPI->getType(), 
3554                               "", InsertPt);
3555 }
3556
3557 /// ReplaceUsesOfGEPInst - Replace all uses of RepPtr with inserted code to
3558 /// compute its value.  The RepPtr value can be computed with Ptr+PtrOffset. One
3559 /// trivial way of doing this would be to evaluate Ptr+PtrOffset in RepPtr's
3560 /// block, then ReplaceAllUsesWith'ing everything.  However, we would prefer to
3561 /// sink PtrOffset into user blocks where doing so will likely allow us to fold
3562 /// the constant add into a load or store instruction.  Additionally, if a user
3563 /// is a pointer-pointer cast, we look through it to find its users.
3564 static void ReplaceUsesOfGEPInst(Instruction *RepPtr, Value *Ptr, 
3565                                  Constant *PtrOffset, BasicBlock *DefBB,
3566                                  GetElementPtrInst *GEPI,
3567                            std::map<BasicBlock*,Instruction*> &InsertedExprs) {
3568   while (!RepPtr->use_empty()) {
3569     Instruction *User = cast<Instruction>(RepPtr->use_back());
3570     
3571     // If the user is a Pointer-Pointer cast, recurse. Only BitCast can be
3572     // used for a Pointer-Pointer cast.
3573     if (isa<BitCastInst>(User)) {
3574       ReplaceUsesOfGEPInst(User, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3575       
3576       // Drop the use of RepPtr. The cast is dead.  Don't delete it now, else we
3577       // could invalidate an iterator.
3578       User->setOperand(0, UndefValue::get(RepPtr->getType()));
3579       continue;
3580     }
3581     
3582     // If this is a load of the pointer, or a store through the pointer, emit
3583     // the increment into the load/store block.
3584     Instruction *NewVal;
3585     if (isa<LoadInst>(User) ||
3586         (isa<StoreInst>(User) && User->getOperand(0) != RepPtr)) {
3587       NewVal = InsertGEPComputeCode(InsertedExprs[User->getParent()], 
3588                                     User->getParent(), GEPI,
3589                                     Ptr, PtrOffset);
3590     } else {
3591       // If this use is not foldable into the addressing mode, use a version 
3592       // emitted in the GEP block.
3593       NewVal = InsertGEPComputeCode(InsertedExprs[DefBB], DefBB, GEPI, 
3594                                     Ptr, PtrOffset);
3595     }
3596     
3597     if (GEPI->getType() != RepPtr->getType()) {
3598       BasicBlock::iterator IP = NewVal;
3599       ++IP;
3600       // NewVal must be a GEP which must be pointer type, so BitCast
3601       NewVal = new BitCastInst(NewVal, RepPtr->getType(), "", IP);
3602     }
3603     User->replaceUsesOfWith(RepPtr, NewVal);
3604   }
3605 }
3606
3607
3608 /// OptimizeGEPExpression - Since we are doing basic-block-at-a-time instruction
3609 /// selection, we want to be a bit careful about some things.  In particular, if
3610 /// we have a GEP instruction that is used in a different block than it is
3611 /// defined, the addressing expression of the GEP cannot be folded into loads or
3612 /// stores that use it.  In this case, decompose the GEP and move constant
3613 /// indices into blocks that use it.
3614 static bool OptimizeGEPExpression(GetElementPtrInst *GEPI,
3615                                   const TargetData *TD) {
3616   // If this GEP is only used inside the block it is defined in, there is no
3617   // need to rewrite it.
3618   bool isUsedOutsideDefBB = false;
3619   BasicBlock *DefBB = GEPI->getParent();
3620   for (Value::use_iterator UI = GEPI->use_begin(), E = GEPI->use_end(); 
3621        UI != E; ++UI) {
3622     if (cast<Instruction>(*UI)->getParent() != DefBB) {
3623       isUsedOutsideDefBB = true;
3624       break;
3625     }
3626   }
3627   if (!isUsedOutsideDefBB) return false;
3628
3629   // If this GEP has no non-zero constant indices, there is nothing we can do,
3630   // ignore it.
3631   bool hasConstantIndex = false;
3632   bool hasVariableIndex = false;
3633   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3634        E = GEPI->op_end(); OI != E; ++OI) {
3635     if (ConstantInt *CI = dyn_cast<ConstantInt>(*OI)) {
3636       if (CI->getZExtValue()) {
3637         hasConstantIndex = true;
3638         break;
3639       }
3640     } else {
3641       hasVariableIndex = true;
3642     }
3643   }
3644   
3645   // If this is a "GEP X, 0, 0, 0", turn this into a cast.
3646   if (!hasConstantIndex && !hasVariableIndex) {
3647     /// The GEP operand must be a pointer, so must its result -> BitCast
3648     Value *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), 
3649                              GEPI->getName(), GEPI);
3650     GEPI->replaceAllUsesWith(NC);
3651     GEPI->eraseFromParent();
3652     return true;
3653   }
3654   
3655   // If this is a GEP &Alloca, 0, 0, forward subst the frame index into uses.
3656   if (!hasConstantIndex && !isa<AllocaInst>(GEPI->getOperand(0)))
3657     return false;
3658   
3659   // Otherwise, decompose the GEP instruction into multiplies and adds.  Sum the
3660   // constant offset (which we now know is non-zero) and deal with it later.
3661   uint64_t ConstantOffset = 0;
3662   const Type *UIntPtrTy = TD->getIntPtrType();
3663   Value *Ptr = new PtrToIntInst(GEPI->getOperand(0), UIntPtrTy, "", GEPI);
3664   const Type *Ty = GEPI->getOperand(0)->getType();
3665
3666   for (GetElementPtrInst::op_iterator OI = GEPI->op_begin()+1,
3667        E = GEPI->op_end(); OI != E; ++OI) {
3668     Value *Idx = *OI;
3669     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
3670       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
3671       if (Field)
3672         ConstantOffset += TD->getStructLayout(StTy)->MemberOffsets[Field];
3673       Ty = StTy->getElementType(Field);
3674     } else {
3675       Ty = cast<SequentialType>(Ty)->getElementType();
3676
3677       // Handle constant subscripts.
3678       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
3679         if (CI->getZExtValue() == 0) continue;
3680         ConstantOffset += (int64_t)TD->getTypeSize(Ty)*CI->getSExtValue();
3681         continue;
3682       }
3683       
3684       // Ptr = Ptr + Idx * ElementSize;
3685       
3686       // Cast Idx to UIntPtrTy if needed.
3687       Idx = CastInst::createIntegerCast(Idx, UIntPtrTy, true/*SExt*/, "", GEPI);
3688       
3689       uint64_t ElementSize = TD->getTypeSize(Ty);
3690       // Mask off bits that should not be set.
3691       ElementSize &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3692       Constant *SizeCst = ConstantInt::get(UIntPtrTy, ElementSize);
3693
3694       // Multiply by the element size and add to the base.
3695       Idx = BinaryOperator::createMul(Idx, SizeCst, "", GEPI);
3696       Ptr = BinaryOperator::createAdd(Ptr, Idx, "", GEPI);
3697     }
3698   }
3699   
3700   // Make sure that the offset fits in uintptr_t.
3701   ConstantOffset &= ~0ULL >> (64-UIntPtrTy->getPrimitiveSizeInBits());
3702   Constant *PtrOffset = ConstantInt::get(UIntPtrTy, ConstantOffset);
3703   
3704   // Okay, we have now emitted all of the variable index parts to the BB that
3705   // the GEP is defined in.  Loop over all of the using instructions, inserting
3706   // an "add Ptr, ConstantOffset" into each block that uses it and update the
3707   // instruction to use the newly computed value, making GEPI dead.  When the
3708   // user is a load or store instruction address, we emit the add into the user
3709   // block, otherwise we use a canonical version right next to the gep (these 
3710   // won't be foldable as addresses, so we might as well share the computation).
3711   
3712   std::map<BasicBlock*,Instruction*> InsertedExprs;
3713   ReplaceUsesOfGEPInst(GEPI, Ptr, PtrOffset, DefBB, GEPI, InsertedExprs);
3714   
3715   // Finally, the GEP is dead, remove it.
3716   GEPI->eraseFromParent();
3717   
3718   return true;
3719 }
3720
3721
3722 /// SplitEdgeNicely - Split the critical edge from TI to it's specified
3723 /// successor if it will improve codegen.  We only do this if the successor has
3724 /// phi nodes (otherwise critical edges are ok).  If there is already another
3725 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
3726 /// instead of introducing a new block.
3727 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
3728   BasicBlock *TIBB = TI->getParent();
3729   BasicBlock *Dest = TI->getSuccessor(SuccNum);
3730   assert(isa<PHINode>(Dest->begin()) &&
3731          "This should only be called if Dest has a PHI!");
3732
3733   /// TIPHIValues - This array is lazily computed to determine the values of
3734   /// PHIs in Dest that TI would provide.
3735   std::vector<Value*> TIPHIValues;
3736   
3737   // Check to see if Dest has any blocks that can be used as a split edge for
3738   // this terminator.
3739   for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
3740     BasicBlock *Pred = *PI;
3741     // To be usable, the pred has to end with an uncond branch to the dest.
3742     BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
3743     if (!PredBr || !PredBr->isUnconditional() ||
3744         // Must be empty other than the branch.
3745         &Pred->front() != PredBr)
3746       continue;
3747     
3748     // Finally, since we know that Dest has phi nodes in it, we have to make
3749     // sure that jumping to Pred will have the same affect as going to Dest in
3750     // terms of PHI values.
3751     PHINode *PN;
3752     unsigned PHINo = 0;
3753     bool FoundMatch = true;
3754     for (BasicBlock::iterator I = Dest->begin();
3755          (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
3756       if (PHINo == TIPHIValues.size())
3757         TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
3758
3759       // If the PHI entry doesn't work, we can't use this pred.
3760       if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
3761         FoundMatch = false;
3762         break;
3763       }
3764     }
3765     
3766     // If we found a workable predecessor, change TI to branch to Succ.
3767     if (FoundMatch) {
3768       Dest->removePredecessor(TIBB);
3769       TI->setSuccessor(SuccNum, Pred);
3770       return;
3771     }
3772   }
3773   
3774   SplitCriticalEdge(TI, SuccNum, P, true);  
3775 }
3776
3777
3778 bool SelectionDAGISel::runOnFunction(Function &Fn) {
3779   MachineFunction &MF = MachineFunction::construct(&Fn, TLI.getTargetMachine());
3780   RegMap = MF.getSSARegMap();
3781   DOUT << "\n\n\n=== " << Fn.getName() << "\n";
3782
3783   // First, split all critical edges.
3784   //
3785   // In this pass we also look for GEP and cast instructions that are used
3786   // across basic blocks and rewrite them to improve basic-block-at-a-time
3787   // selection.
3788   //
3789   bool MadeChange = true;
3790   while (MadeChange) {
3791     MadeChange = false;
3792   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
3793     // Split all critical edges where the dest block has a PHI.
3794     TerminatorInst *BBTI = BB->getTerminator();
3795     if (BBTI->getNumSuccessors() > 1) {
3796       for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
3797         if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
3798             isCriticalEdge(BBTI, i, true))
3799           SplitEdgeNicely(BBTI, i, this);
3800     }
3801     
3802     
3803     for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
3804       Instruction *I = BBI++;
3805       
3806       if (CallInst *CI = dyn_cast<CallInst>(I)) {
3807         // If we found an inline asm expession, and if the target knows how to
3808         // lower it to normal LLVM code, do so now.
3809         if (isa<InlineAsm>(CI->getCalledValue()))
3810           if (const TargetAsmInfo *TAI = 
3811                 TLI.getTargetMachine().getTargetAsmInfo()) {
3812             if (TAI->ExpandInlineAsm(CI))
3813               BBI = BB->begin();
3814           }
3815       } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
3816         MadeChange |= OptimizeGEPExpression(GEPI, TLI.getTargetData());
3817       } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
3818         // If the source of the cast is a constant, then this should have
3819         // already been constant folded.  The only reason NOT to constant fold
3820         // it is if something (e.g. LSR) was careful to place the constant
3821         // evaluation in a block other than then one that uses it (e.g. to hoist
3822         // the address of globals out of a loop).  If this is the case, we don't
3823         // want to forward-subst the cast.
3824         if (isa<Constant>(CI->getOperand(0)))
3825           continue;
3826         
3827         // If this is a noop copy, sink it into user blocks to reduce the number
3828         // of virtual registers that must be created and coallesced.
3829         MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
3830         MVT::ValueType DstVT = TLI.getValueType(CI->getType());
3831         
3832         // This is an fp<->int conversion?
3833         if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
3834           continue;
3835         
3836         // If this is an extension, it will be a zero or sign extension, which
3837         // isn't a noop.
3838         if (SrcVT < DstVT) continue;
3839         
3840         // If these values will be promoted, find out what they will be promoted
3841         // to.  This helps us consider truncates on PPC as noop copies when they
3842         // are.
3843         if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
3844           SrcVT = TLI.getTypeToTransformTo(SrcVT);
3845         if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
3846           DstVT = TLI.getTypeToTransformTo(DstVT);
3847
3848         // If, after promotion, these are the same types, this is a noop copy.
3849         if (SrcVT == DstVT)
3850           MadeChange |= OptimizeNoopCopyExpression(CI);
3851       }
3852     }
3853   }
3854   }
3855   
3856   FunctionLoweringInfo FuncInfo(TLI, Fn, MF);
3857
3858   for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
3859     SelectBasicBlock(I, MF, FuncInfo);
3860
3861   return true;
3862 }
3863
3864 SDOperand SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, 
3865                                                            unsigned Reg) {
3866   SDOperand Op = getValue(V);
3867   assert((Op.getOpcode() != ISD::CopyFromReg ||
3868           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
3869          "Copy from a reg to the same reg!");
3870   
3871   // If this type is not legal, we must make sure to not create an invalid
3872   // register use.
3873   MVT::ValueType SrcVT = Op.getValueType();
3874   MVT::ValueType DestVT = TLI.getTypeToTransformTo(SrcVT);
3875   if (SrcVT == DestVT) {
3876     return DAG.getCopyToReg(getRoot(), Reg, Op);
3877   } else if (SrcVT == MVT::Vector) {
3878     // Handle copies from generic vectors to registers.
3879     MVT::ValueType PTyElementVT, PTyLegalElementVT;
3880     unsigned NE = TLI.getPackedTypeBreakdown(cast<PackedType>(V->getType()),
3881                                              PTyElementVT, PTyLegalElementVT);
3882     
3883     // Insert a VBIT_CONVERT of the input vector to a "N x PTyElementVT" 
3884     // MVT::Vector type.
3885     Op = DAG.getNode(ISD::VBIT_CONVERT, MVT::Vector, Op,
3886                      DAG.getConstant(NE, MVT::i32), 
3887                      DAG.getValueType(PTyElementVT));
3888
3889     // Loop over all of the elements of the resultant vector,
3890     // VEXTRACT_VECTOR_ELT'ing them, converting them to PTyLegalElementVT, then
3891     // copying them into output registers.
3892     SmallVector<SDOperand, 8> OutChains;
3893     SDOperand Root = getRoot();
3894     for (unsigned i = 0; i != NE; ++i) {
3895       SDOperand Elt = DAG.getNode(ISD::VEXTRACT_VECTOR_ELT, PTyElementVT,
3896                                   Op, DAG.getConstant(i, TLI.getPointerTy()));
3897       if (PTyElementVT == PTyLegalElementVT) {
3898         // Elements are legal.
3899         OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3900       } else if (PTyLegalElementVT > PTyElementVT) {
3901         // Elements are promoted.
3902         if (MVT::isFloatingPoint(PTyLegalElementVT))
3903           Elt = DAG.getNode(ISD::FP_EXTEND, PTyLegalElementVT, Elt);
3904         else
3905           Elt = DAG.getNode(ISD::ANY_EXTEND, PTyLegalElementVT, Elt);
3906         OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Elt));
3907       } else {
3908         // Elements are expanded.
3909         // The src value is expanded into multiple registers.
3910         SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3911                                    Elt, DAG.getConstant(0, TLI.getPointerTy()));
3912         SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, PTyLegalElementVT,
3913                                    Elt, DAG.getConstant(1, TLI.getPointerTy()));
3914         OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Lo));
3915         OutChains.push_back(DAG.getCopyToReg(Root, Reg++, Hi));
3916       }
3917     }
3918     return DAG.getNode(ISD::TokenFactor, MVT::Other,
3919                        &OutChains[0], OutChains.size());
3920   } else if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote) {
3921     // The src value is promoted to the register.
3922     if (MVT::isFloatingPoint(SrcVT))
3923       Op = DAG.getNode(ISD::FP_EXTEND, DestVT, Op);
3924     else
3925       Op = DAG.getNode(ISD::ANY_EXTEND, DestVT, Op);
3926     return DAG.getCopyToReg(getRoot(), Reg, Op);
3927   } else  {
3928     DestVT = TLI.getTypeToExpandTo(SrcVT);
3929     unsigned NumVals = TLI.getNumElements(SrcVT);
3930     if (NumVals == 1)
3931       return DAG.getCopyToReg(getRoot(), Reg,
3932                               DAG.getNode(ISD::BIT_CONVERT, DestVT, Op));
3933     assert(NumVals == 2 && "1 to 4 (and more) expansion not implemented!");
3934     // The src value is expanded into multiple registers.
3935     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3936                                Op, DAG.getConstant(0, TLI.getPointerTy()));
3937     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DestVT,
3938                                Op, DAG.getConstant(1, TLI.getPointerTy()));
3939     Op = DAG.getCopyToReg(getRoot(), Reg, Lo);
3940     return DAG.getCopyToReg(Op, Reg+1, Hi);
3941   }
3942 }
3943
3944 void SelectionDAGISel::
3945 LowerArguments(BasicBlock *BB, SelectionDAGLowering &SDL,
3946                std::vector<SDOperand> &UnorderedChains) {
3947   // If this is the entry block, emit arguments.
3948   Function &F = *BB->getParent();
3949   FunctionLoweringInfo &FuncInfo = SDL.FuncInfo;
3950   SDOperand OldRoot = SDL.DAG.getRoot();
3951   std::vector<SDOperand> Args = TLI.LowerArguments(F, SDL.DAG);
3952
3953   unsigned a = 0;
3954   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
3955        AI != E; ++AI, ++a)
3956     if (!AI->use_empty()) {
3957       SDL.setValue(AI, Args[a]);
3958
3959       // If this argument is live outside of the entry block, insert a copy from
3960       // whereever we got it to the vreg that other BB's will reference it as.
3961       if (FuncInfo.ValueMap.count(AI)) {
3962         SDOperand Copy =
3963           SDL.CopyValueToVirtualRegister(AI, FuncInfo.ValueMap[AI]);
3964         UnorderedChains.push_back(Copy);
3965       }
3966     }
3967
3968   // Finally, if the target has anything special to do, allow it to do so.
3969   // FIXME: this should insert code into the DAG!
3970   EmitFunctionEntryCode(F, SDL.DAG.getMachineFunction());
3971 }
3972
3973 void SelectionDAGISel::BuildSelectionDAG(SelectionDAG &DAG, BasicBlock *LLVMBB,
3974        std::vector<std::pair<MachineInstr*, unsigned> > &PHINodesToUpdate,
3975                                          FunctionLoweringInfo &FuncInfo) {
3976   SelectionDAGLowering SDL(DAG, TLI, FuncInfo);
3977
3978   std::vector<SDOperand> UnorderedChains;
3979
3980   // Lower any arguments needed in this block if this is the entry block.
3981   if (LLVMBB == &LLVMBB->getParent()->front())
3982     LowerArguments(LLVMBB, SDL, UnorderedChains);
3983
3984   BB = FuncInfo.MBBMap[LLVMBB];
3985   SDL.setCurrentBasicBlock(BB);
3986
3987   // Lower all of the non-terminator instructions.
3988   for (BasicBlock::iterator I = LLVMBB->begin(), E = --LLVMBB->end();
3989        I != E; ++I)
3990     SDL.visit(*I);
3991   
3992   // Ensure that all instructions which are used outside of their defining
3993   // blocks are available as virtual registers.
3994   for (BasicBlock::iterator I = LLVMBB->begin(), E = LLVMBB->end(); I != E;++I)
3995     if (!I->use_empty() && !isa<PHINode>(I)) {
3996       std::map<const Value*, unsigned>::iterator VMI =FuncInfo.ValueMap.find(I);
3997       if (VMI != FuncInfo.ValueMap.end())
3998         UnorderedChains.push_back(
3999                                 SDL.CopyValueToVirtualRegister(I, VMI->second));
4000     }
4001
4002   // Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
4003   // ensure constants are generated when needed.  Remember the virtual registers
4004   // that need to be added to the Machine PHI nodes as input.  We cannot just
4005   // directly add them, because expansion might result in multiple MBB's for one
4006   // BB.  As such, the start of the BB might correspond to a different MBB than
4007   // the end.
4008   //
4009   TerminatorInst *TI = LLVMBB->getTerminator();
4010
4011   // Emit constants only once even if used by multiple PHI nodes.
4012   std::map<Constant*, unsigned> ConstantsOut;
4013   
4014   // Vector bool would be better, but vector<bool> is really slow.
4015   std::vector<unsigned char> SuccsHandled;
4016   if (TI->getNumSuccessors())
4017     SuccsHandled.resize(BB->getParent()->getNumBlockIDs());
4018     
4019   // Check successor nodes PHI nodes that expect a constant to be available from
4020   // this block.
4021   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4022     BasicBlock *SuccBB = TI->getSuccessor(succ);
4023     if (!isa<PHINode>(SuccBB->begin())) continue;
4024     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
4025     
4026     // If this terminator has multiple identical successors (common for
4027     // switches), only handle each succ once.
4028     unsigned SuccMBBNo = SuccMBB->getNumber();
4029     if (SuccsHandled[SuccMBBNo]) continue;
4030     SuccsHandled[SuccMBBNo] = true;
4031     
4032     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4033     PHINode *PN;
4034
4035     // At this point we know that there is a 1-1 correspondence between LLVM PHI
4036     // nodes and Machine PHI nodes, but the incoming operands have not been
4037     // emitted yet.
4038     for (BasicBlock::iterator I = SuccBB->begin();
4039          (PN = dyn_cast<PHINode>(I)); ++I) {
4040       // Ignore dead phi's.
4041       if (PN->use_empty()) continue;
4042       
4043       unsigned Reg;
4044       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4045       
4046       if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4047         unsigned &RegOut = ConstantsOut[C];
4048         if (RegOut == 0) {
4049           RegOut = FuncInfo.CreateRegForValue(C);
4050           UnorderedChains.push_back(
4051                            SDL.CopyValueToVirtualRegister(C, RegOut));
4052         }
4053         Reg = RegOut;
4054       } else {
4055         Reg = FuncInfo.ValueMap[PHIOp];
4056         if (Reg == 0) {
4057           assert(isa<AllocaInst>(PHIOp) &&
4058                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4059                  "Didn't codegen value into a register!??");
4060           Reg = FuncInfo.CreateRegForValue(PHIOp);
4061           UnorderedChains.push_back(
4062                            SDL.CopyValueToVirtualRegister(PHIOp, Reg));
4063         }
4064       }
4065
4066       // Remember that this register needs to added to the machine PHI node as
4067       // the input for this MBB.
4068       MVT::ValueType VT = TLI.getValueType(PN->getType());
4069       unsigned NumElements;
4070       if (VT != MVT::Vector)
4071         NumElements = TLI.getNumElements(VT);
4072       else {
4073         MVT::ValueType VT1,VT2;
4074         NumElements = 
4075           TLI.getPackedTypeBreakdown(cast<PackedType>(PN->getType()),
4076                                      VT1, VT2);
4077       }
4078       for (unsigned i = 0, e = NumElements; i != e; ++i)
4079         PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4080     }
4081   }
4082   ConstantsOut.clear();
4083
4084   // Turn all of the unordered chains into one factored node.
4085   if (!UnorderedChains.empty()) {
4086     SDOperand Root = SDL.getRoot();
4087     if (Root.getOpcode() != ISD::EntryToken) {
4088       unsigned i = 0, e = UnorderedChains.size();
4089       for (; i != e; ++i) {
4090         assert(UnorderedChains[i].Val->getNumOperands() > 1);
4091         if (UnorderedChains[i].Val->getOperand(0) == Root)
4092           break;  // Don't add the root if we already indirectly depend on it.
4093       }
4094         
4095       if (i == e)
4096         UnorderedChains.push_back(Root);
4097     }
4098     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other,
4099                             &UnorderedChains[0], UnorderedChains.size()));
4100   }
4101
4102   // Lower the terminator after the copies are emitted.
4103   SDL.visit(*LLVMBB->getTerminator());
4104
4105   // Copy over any CaseBlock records that may now exist due to SwitchInst
4106   // lowering, as well as any jump table information.
4107   SwitchCases.clear();
4108   SwitchCases = SDL.SwitchCases;
4109   JT = SDL.JT;
4110   
4111   // Make sure the root of the DAG is up-to-date.
4112   DAG.setRoot(SDL.getRoot());
4113 }
4114
4115 void SelectionDAGISel::CodeGenAndEmitDAG(SelectionDAG &DAG) {
4116   // Get alias analysis for load/store combining.
4117   AliasAnalysis &AA = getAnalysis<AliasAnalysis>();
4118
4119   // Run the DAG combiner in pre-legalize mode.
4120   DAG.Combine(false, AA);
4121   
4122   DOUT << "Lowered selection DAG:\n";
4123   DEBUG(DAG.dump());
4124   
4125   // Second step, hack on the DAG until it only uses operations and types that
4126   // the target supports.
4127   DAG.Legalize();
4128   
4129   DOUT << "Legalized selection DAG:\n";
4130   DEBUG(DAG.dump());
4131   
4132   // Run the DAG combiner in post-legalize mode.
4133   DAG.Combine(true, AA);
4134   
4135   if (ViewISelDAGs) DAG.viewGraph();
4136
4137   // Third, instruction select all of the operations to machine code, adding the
4138   // code to the MachineBasicBlock.
4139   InstructionSelectBasicBlock(DAG);
4140   
4141   DOUT << "Selected machine code:\n";
4142   DEBUG(BB->dump());
4143 }  
4144
4145 void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB, MachineFunction &MF,
4146                                         FunctionLoweringInfo &FuncInfo) {
4147   std::vector<std::pair<MachineInstr*, unsigned> > PHINodesToUpdate;
4148   {
4149     SelectionDAG DAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4150     CurDAG = &DAG;
4151   
4152     // First step, lower LLVM code to some DAG.  This DAG may use operations and
4153     // types that are not supported by the target.
4154     BuildSelectionDAG(DAG, LLVMBB, PHINodesToUpdate, FuncInfo);
4155
4156     // Second step, emit the lowered DAG as machine code.
4157     CodeGenAndEmitDAG(DAG);
4158   }
4159   
4160   // Next, now that we know what the last MBB the LLVM BB expanded is, update
4161   // PHI nodes in successors.
4162   if (SwitchCases.empty() && JT.Reg == 0) {
4163     for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4164       MachineInstr *PHI = PHINodesToUpdate[i].first;
4165       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4166              "This is not a machine PHI node that we are updating!");
4167       PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4168       PHI->addMachineBasicBlockOperand(BB);
4169     }
4170     return;
4171   }
4172   
4173   // If the JumpTable record is filled in, then we need to emit a jump table.
4174   // Updating the PHI nodes is tricky in this case, since we need to determine
4175   // whether the PHI is a successor of the range check MBB or the jump table MBB
4176   if (JT.Reg) {
4177     assert(SwitchCases.empty() && "Cannot have jump table and lowered switch");
4178     SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4179     CurDAG = &SDAG;
4180     SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4181     MachineBasicBlock *RangeBB = BB;
4182     // Set the current basic block to the mbb we wish to insert the code into
4183     BB = JT.MBB;
4184     SDL.setCurrentBasicBlock(BB);
4185     // Emit the code
4186     SDL.visitJumpTable(JT);
4187     SDAG.setRoot(SDL.getRoot());
4188     CodeGenAndEmitDAG(SDAG);
4189     // Update PHI Nodes
4190     for (unsigned pi = 0, pe = PHINodesToUpdate.size(); pi != pe; ++pi) {
4191       MachineInstr *PHI = PHINodesToUpdate[pi].first;
4192       MachineBasicBlock *PHIBB = PHI->getParent();
4193       assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4194              "This is not a machine PHI node that we are updating!");
4195       if (PHIBB == JT.Default) {
4196         PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4197         PHI->addMachineBasicBlockOperand(RangeBB);
4198       }
4199       if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
4200         PHI->addRegOperand(PHINodesToUpdate[pi].second, false);
4201         PHI->addMachineBasicBlockOperand(BB);
4202       }
4203     }
4204     return;
4205   }
4206   
4207   // If the switch block involved a branch to one of the actual successors, we
4208   // need to update PHI nodes in that block.
4209   for (unsigned i = 0, e = PHINodesToUpdate.size(); i != e; ++i) {
4210     MachineInstr *PHI = PHINodesToUpdate[i].first;
4211     assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
4212            "This is not a machine PHI node that we are updating!");
4213     if (BB->isSuccessor(PHI->getParent())) {
4214       PHI->addRegOperand(PHINodesToUpdate[i].second, false);
4215       PHI->addMachineBasicBlockOperand(BB);
4216     }
4217   }
4218   
4219   // If we generated any switch lowering information, build and codegen any
4220   // additional DAGs necessary.
4221   for (unsigned i = 0, e = SwitchCases.size(); i != e; ++i) {
4222     SelectionDAG SDAG(TLI, MF, getAnalysisToUpdate<MachineModuleInfo>());
4223     CurDAG = &SDAG;
4224     SelectionDAGLowering SDL(SDAG, TLI, FuncInfo);
4225     
4226     // Set the current basic block to the mbb we wish to insert the code into
4227     BB = SwitchCases[i].ThisBB;
4228     SDL.setCurrentBasicBlock(BB);
4229     
4230     // Emit the code
4231     SDL.visitSwitchCase(SwitchCases[i]);
4232     SDAG.setRoot(SDL.getRoot());
4233     CodeGenAndEmitDAG(SDAG);
4234     
4235     // Handle any PHI nodes in successors of this chunk, as if we were coming
4236     // from the original BB before switch expansion.  Note that PHI nodes can
4237     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
4238     // handle them the right number of times.
4239     while ((BB = SwitchCases[i].TrueBB)) {  // Handle LHS and RHS.
4240       for (MachineBasicBlock::iterator Phi = BB->begin();
4241            Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
4242         // This value for this PHI node is recorded in PHINodesToUpdate, get it.
4243         for (unsigned pn = 0; ; ++pn) {
4244           assert(pn != PHINodesToUpdate.size() && "Didn't find PHI entry!");
4245           if (PHINodesToUpdate[pn].first == Phi) {
4246             Phi->addRegOperand(PHINodesToUpdate[pn].second, false);
4247             Phi->addMachineBasicBlockOperand(SwitchCases[i].ThisBB);
4248             break;
4249           }
4250         }
4251       }
4252       
4253       // Don't process RHS if same block as LHS.
4254       if (BB == SwitchCases[i].FalseBB)
4255         SwitchCases[i].FalseBB = 0;
4256       
4257       // If we haven't handled the RHS, do so now.  Otherwise, we're done.
4258       SwitchCases[i].TrueBB = SwitchCases[i].FalseBB;
4259       SwitchCases[i].FalseBB = 0;
4260     }
4261     assert(SwitchCases[i].TrueBB == 0 && SwitchCases[i].FalseBB == 0);
4262   }
4263 }
4264
4265
4266 //===----------------------------------------------------------------------===//
4267 /// ScheduleAndEmitDAG - Pick a safe ordering and emit instructions for each
4268 /// target node in the graph.
4269 void SelectionDAGISel::ScheduleAndEmitDAG(SelectionDAG &DAG) {
4270   if (ViewSchedDAGs) DAG.viewGraph();
4271
4272   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
4273   
4274   if (!Ctor) {
4275     Ctor = ISHeuristic;
4276     RegisterScheduler::setDefault(Ctor);
4277   }
4278   
4279   ScheduleDAG *SL = Ctor(this, &DAG, BB);
4280   BB = SL->Run();
4281   delete SL;
4282 }
4283
4284
4285 HazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
4286   return new HazardRecognizer();
4287 }
4288
4289 //===----------------------------------------------------------------------===//
4290 // Helper functions used by the generated instruction selector.
4291 //===----------------------------------------------------------------------===//
4292 // Calls to these methods are generated by tblgen.
4293
4294 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
4295 /// the dag combiner simplified the 255, we still want to match.  RHS is the
4296 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
4297 /// specified in the .td file (e.g. 255).
4298 bool SelectionDAGISel::CheckAndMask(SDOperand LHS, ConstantSDNode *RHS, 
4299                                     int64_t DesiredMaskS) {
4300   uint64_t ActualMask = RHS->getValue();
4301   uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4302   
4303   // If the actual mask exactly matches, success!
4304   if (ActualMask == DesiredMask)
4305     return true;
4306   
4307   // If the actual AND mask is allowing unallowed bits, this doesn't match.
4308   if (ActualMask & ~DesiredMask)
4309     return false;
4310   
4311   // Otherwise, the DAG Combiner may have proven that the value coming in is
4312   // either already zero or is not demanded.  Check for known zero input bits.
4313   uint64_t NeededMask = DesiredMask & ~ActualMask;
4314   if (getTargetLowering().MaskedValueIsZero(LHS, NeededMask))
4315     return true;
4316   
4317   // TODO: check to see if missing bits are just not demanded.
4318
4319   // Otherwise, this pattern doesn't match.
4320   return false;
4321 }
4322
4323 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
4324 /// the dag combiner simplified the 255, we still want to match.  RHS is the
4325 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
4326 /// specified in the .td file (e.g. 255).
4327 bool SelectionDAGISel::CheckOrMask(SDOperand LHS, ConstantSDNode *RHS, 
4328                                     int64_t DesiredMaskS) {
4329   uint64_t ActualMask = RHS->getValue();
4330   uint64_t DesiredMask =DesiredMaskS & MVT::getIntVTBitMask(LHS.getValueType());
4331   
4332   // If the actual mask exactly matches, success!
4333   if (ActualMask == DesiredMask)
4334     return true;
4335   
4336   // If the actual AND mask is allowing unallowed bits, this doesn't match.
4337   if (ActualMask & ~DesiredMask)
4338     return false;
4339   
4340   // Otherwise, the DAG Combiner may have proven that the value coming in is
4341   // either already zero or is not demanded.  Check for known zero input bits.
4342   uint64_t NeededMask = DesiredMask & ~ActualMask;
4343   
4344   uint64_t KnownZero, KnownOne;
4345   getTargetLowering().ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
4346   
4347   // If all the missing bits in the or are already known to be set, match!
4348   if ((NeededMask & KnownOne) == NeededMask)
4349     return true;
4350   
4351   // TODO: check to see if missing bits are just not demanded.
4352   
4353   // Otherwise, this pattern doesn't match.
4354   return false;
4355 }
4356
4357
4358 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
4359 /// by tblgen.  Others should not call it.
4360 void SelectionDAGISel::
4361 SelectInlineAsmMemoryOperands(std::vector<SDOperand> &Ops, SelectionDAG &DAG) {
4362   std::vector<SDOperand> InOps;
4363   std::swap(InOps, Ops);
4364
4365   Ops.push_back(InOps[0]);  // input chain.
4366   Ops.push_back(InOps[1]);  // input asm string.
4367
4368   unsigned i = 2, e = InOps.size();
4369   if (InOps[e-1].getValueType() == MVT::Flag)
4370     --e;  // Don't process a flag operand if it is here.
4371   
4372   while (i != e) {
4373     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getValue();
4374     if ((Flags & 7) != 4 /*MEM*/) {
4375       // Just skip over this operand, copying the operands verbatim.
4376       Ops.insert(Ops.end(), InOps.begin()+i, InOps.begin()+i+(Flags >> 3) + 1);
4377       i += (Flags >> 3) + 1;
4378     } else {
4379       assert((Flags >> 3) == 1 && "Memory operand with multiple values?");
4380       // Otherwise, this is a memory operand.  Ask the target to select it.
4381       std::vector<SDOperand> SelOps;
4382       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps, DAG)) {
4383         cerr << "Could not match memory address.  Inline asm failure!\n";
4384         exit(1);
4385       }
4386       
4387       // Add this to the output node.
4388       Ops.push_back(DAG.getTargetConstant(4/*MEM*/ | (SelOps.size() << 3),
4389                                           MVT::i32));
4390       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
4391       i += 2;
4392     }
4393   }
4394   
4395   // Add the flag input back if present.
4396   if (e != InOps.size())
4397     Ops.push_back(InOps.back());
4398 }