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