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