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