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