Emit label for llvm.dbg.func.start of the inlined function.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAGBuild.cpp
1 //===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuild.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Module.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/GCMetadata.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetFrameInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/MathExtras.h"
50 #include <algorithm>
51 using namespace llvm;
52
53 /// LimitFloatPrecision - Generate low-precision inline sequences for
54 /// some float libcalls (6, 8 or 12 bits).
55 static unsigned LimitFloatPrecision;
56
57 static cl::opt<unsigned, true>
58 LimitFPPrecision("limit-float-precision",
59                  cl::desc("Generate low-precision inline sequences "
60                           "for some float libcalls"),
61                  cl::location(LimitFloatPrecision),
62                  cl::init(0));
63
64 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
65 /// insertvalue or extractvalue indices that identify a member, return
66 /// the linearized index of the start of the member.
67 ///
68 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
69                                    const unsigned *Indices,
70                                    const unsigned *IndicesEnd,
71                                    unsigned CurIndex = 0) {
72   // Base case: We're done.
73   if (Indices && Indices == IndicesEnd)
74     return CurIndex;
75
76   // Given a struct type, recursively traverse the elements.
77   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
78     for (StructType::element_iterator EB = STy->element_begin(),
79                                       EI = EB,
80                                       EE = STy->element_end();
81         EI != EE; ++EI) {
82       if (Indices && *Indices == unsigned(EI - EB))
83         return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
84       CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
85     }
86   }
87   // Given an array type, recursively traverse the elements.
88   else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
89     const Type *EltTy = ATy->getElementType();
90     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
91       if (Indices && *Indices == i)
92         return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
93       CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
94     }
95   }
96   // We haven't found the type we're looking for, so keep searching.
97   return CurIndex + 1;
98 }
99
100 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
101 /// MVTs that represent all the individual underlying
102 /// non-aggregate types that comprise it.
103 ///
104 /// If Offsets is non-null, it points to a vector to be filled in
105 /// with the in-memory offsets of each of the individual values.
106 ///
107 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
108                             SmallVectorImpl<MVT> &ValueVTs,
109                             SmallVectorImpl<uint64_t> *Offsets = 0,
110                             uint64_t StartingOffset = 0) {
111   // Given a struct type, recursively traverse the elements.
112   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
113     const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
114     for (StructType::element_iterator EB = STy->element_begin(),
115                                       EI = EB,
116                                       EE = STy->element_end();
117          EI != EE; ++EI)
118       ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
119                       StartingOffset + SL->getElementOffset(EI - EB));
120     return;
121   }
122   // Given an array type, recursively traverse the elements.
123   if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
124     const Type *EltTy = ATy->getElementType();
125     uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
126     for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
127       ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
128                       StartingOffset + i * EltSize);
129     return;
130   }
131   // Base case: we can get an MVT for this LLVM IR type.
132   ValueVTs.push_back(TLI.getValueType(Ty));
133   if (Offsets)
134     Offsets->push_back(StartingOffset);
135 }
136
137 namespace llvm {
138   /// RegsForValue - This struct represents the registers (physical or virtual)
139   /// that a particular set of values is assigned, and the type information about
140   /// the value. The most common situation is to represent one value at a time,
141   /// but struct or array values are handled element-wise as multiple values.
142   /// The splitting of aggregates is performed recursively, so that we never
143   /// have aggregate-typed registers. The values at this point do not necessarily
144   /// have legal types, so each value may require one or more registers of some
145   /// legal type.
146   /// 
147   struct VISIBILITY_HIDDEN RegsForValue {
148     /// TLI - The TargetLowering object.
149     ///
150     const TargetLowering *TLI;
151
152     /// ValueVTs - The value types of the values, which may not be legal, and
153     /// may need be promoted or synthesized from one or more registers.
154     ///
155     SmallVector<MVT, 4> ValueVTs;
156     
157     /// RegVTs - The value types of the registers. This is the same size as
158     /// ValueVTs and it records, for each value, what the type of the assigned
159     /// register or registers are. (Individual values are never synthesized
160     /// from more than one type of register.)
161     ///
162     /// With virtual registers, the contents of RegVTs is redundant with TLI's
163     /// getRegisterType member function, however when with physical registers
164     /// it is necessary to have a separate record of the types.
165     ///
166     SmallVector<MVT, 4> RegVTs;
167     
168     /// Regs - This list holds the registers assigned to the values.
169     /// Each legal or promoted value requires one register, and each
170     /// expanded value requires multiple registers.
171     ///
172     SmallVector<unsigned, 4> Regs;
173     
174     RegsForValue() : TLI(0) {}
175     
176     RegsForValue(const TargetLowering &tli,
177                  const SmallVector<unsigned, 4> &regs, 
178                  MVT regvt, MVT valuevt)
179       : TLI(&tli),  ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
180     RegsForValue(const TargetLowering &tli,
181                  const SmallVector<unsigned, 4> &regs, 
182                  const SmallVector<MVT, 4> &regvts,
183                  const SmallVector<MVT, 4> &valuevts)
184       : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
185     RegsForValue(const TargetLowering &tli,
186                  unsigned Reg, const Type *Ty) : TLI(&tli) {
187       ComputeValueVTs(tli, Ty, ValueVTs);
188
189       for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
190         MVT ValueVT = ValueVTs[Value];
191         unsigned NumRegs = TLI->getNumRegisters(ValueVT);
192         MVT RegisterVT = TLI->getRegisterType(ValueVT);
193         for (unsigned i = 0; i != NumRegs; ++i)
194           Regs.push_back(Reg + i);
195         RegVTs.push_back(RegisterVT);
196         Reg += NumRegs;
197       }
198     }
199     
200     /// append - Add the specified values to this one.
201     void append(const RegsForValue &RHS) {
202       TLI = RHS.TLI;
203       ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
204       RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
205       Regs.append(RHS.Regs.begin(), RHS.Regs.end());
206     }
207     
208     
209     /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
210     /// this value and returns the result as a ValueVTs value.  This uses 
211     /// Chain/Flag as the input and updates them for the output Chain/Flag.
212     /// If the Flag pointer is NULL, no flag is used.
213     SDValue getCopyFromRegs(SelectionDAG &DAG,
214                               SDValue &Chain, SDValue *Flag) const;
215
216     /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
217     /// specified value into the registers specified by this object.  This uses 
218     /// Chain/Flag as the input and updates them for the output Chain/Flag.
219     /// If the Flag pointer is NULL, no flag is used.
220     void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
221                        SDValue &Chain, SDValue *Flag) const;
222     
223     /// AddInlineAsmOperands - Add this value to the specified inlineasm node
224     /// operand list.  This adds the code marker and includes the number of 
225     /// values added into it.
226     void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
227                               std::vector<SDValue> &Ops) const;
228   };
229 }
230
231 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
232 /// PHI nodes or outside of the basic block that defines it, or used by a 
233 /// switch or atomic instruction, which may expand to multiple basic blocks.
234 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
235   if (isa<PHINode>(I)) return true;
236   BasicBlock *BB = I->getParent();
237   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
238     if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
239         // FIXME: Remove switchinst special case.
240         isa<SwitchInst>(*UI))
241       return true;
242   return false;
243 }
244
245 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
246 /// entry block, return true.  This includes arguments used by switches, since
247 /// the switch may expand into multiple basic blocks.
248 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
249   // With FastISel active, we may be splitting blocks, so force creation
250   // of virtual registers for all non-dead arguments.
251   // Don't force virtual registers for byval arguments though, because
252   // fast-isel can't handle those in all cases.
253   if (EnableFastISel && !A->hasByValAttr())
254     return A->use_empty();
255
256   BasicBlock *Entry = A->getParent()->begin();
257   for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
258     if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
259       return false;  // Use not in entry block.
260   return true;
261 }
262
263 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
264   : TLI(tli) {
265 }
266
267 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
268                                bool EnableFastISel) {
269   Fn = &fn;
270   MF = &mf;
271   RegInfo = &MF->getRegInfo();
272
273   // Create a vreg for each argument register that is not dead and is used
274   // outside of the entry block for the function.
275   for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
276        AI != E; ++AI)
277     if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
278       InitializeRegForValue(AI);
279
280   // Initialize the mapping of values to registers.  This is only set up for
281   // instruction values that are used outside of the block that defines
282   // them.
283   Function::iterator BB = Fn->begin(), EB = Fn->end();
284   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
285     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
286       if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
287         const Type *Ty = AI->getAllocatedType();
288         uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
289         unsigned Align = 
290           std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
291                    AI->getAlignment());
292
293         TySize *= CUI->getZExtValue();   // Get total allocated size.
294         if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
295         StaticAllocaMap[AI] =
296           MF->getFrameInfo()->CreateStackObject(TySize, Align);
297       }
298
299   for (; BB != EB; ++BB)
300     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
301       if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
302         if (!isa<AllocaInst>(I) ||
303             !StaticAllocaMap.count(cast<AllocaInst>(I)))
304           InitializeRegForValue(I);
305
306   // Create an initial MachineBasicBlock for each LLVM BasicBlock in F.  This
307   // also creates the initial PHI MachineInstrs, though none of the input
308   // operands are populated.
309   for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
310     MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
311     MBBMap[BB] = MBB;
312     MF->push_back(MBB);
313
314     // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
315     // appropriate.
316     PHINode *PN;
317     for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
318       if (PN->use_empty()) continue;
319       
320       unsigned PHIReg = ValueMap[PN];
321       assert(PHIReg && "PHI node does not have an assigned virtual register!");
322
323       SmallVector<MVT, 4> ValueVTs;
324       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
325       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
326         MVT VT = ValueVTs[vti];
327         unsigned NumRegisters = TLI.getNumRegisters(VT);
328         const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
329         for (unsigned i = 0; i != NumRegisters; ++i)
330           BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
331         PHIReg += NumRegisters;
332       }
333     }
334   }
335 }
336
337 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
338   return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
339 }
340
341 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
342 /// the correctly promoted or expanded types.  Assign these registers
343 /// consecutive vreg numbers and return the first assigned number.
344 ///
345 /// In the case that the given value has struct or array type, this function
346 /// will assign registers for each member or element.
347 ///
348 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
349   SmallVector<MVT, 4> ValueVTs;
350   ComputeValueVTs(TLI, V->getType(), ValueVTs);
351
352   unsigned FirstReg = 0;
353   for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
354     MVT ValueVT = ValueVTs[Value];
355     MVT RegisterVT = TLI.getRegisterType(ValueVT);
356
357     unsigned NumRegs = TLI.getNumRegisters(ValueVT);
358     for (unsigned i = 0; i != NumRegs; ++i) {
359       unsigned R = MakeReg(RegisterVT);
360       if (!FirstReg) FirstReg = R;
361     }
362   }
363   return FirstReg;
364 }
365
366 /// getCopyFromParts - Create a value that contains the specified legal parts
367 /// combined into the value they represent.  If the parts combine to a type
368 /// larger then ValueVT then AssertOp can be used to specify whether the extra
369 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
370 /// (ISD::AssertSext).
371 static SDValue getCopyFromParts(SelectionDAG &DAG,
372                                   const SDValue *Parts,
373                                   unsigned NumParts,
374                                   MVT PartVT,
375                                   MVT ValueVT,
376                                   ISD::NodeType AssertOp = ISD::DELETED_NODE) {
377   assert(NumParts > 0 && "No parts to assemble!");
378   TargetLowering &TLI = DAG.getTargetLoweringInfo();
379   SDValue Val = Parts[0];
380
381   if (NumParts > 1) {
382     // Assemble the value from multiple parts.
383     if (!ValueVT.isVector()) {
384       unsigned PartBits = PartVT.getSizeInBits();
385       unsigned ValueBits = ValueVT.getSizeInBits();
386
387       // Assemble the power of 2 part.
388       unsigned RoundParts = NumParts & (NumParts - 1) ?
389         1 << Log2_32(NumParts) : NumParts;
390       unsigned RoundBits = PartBits * RoundParts;
391       MVT RoundVT = RoundBits == ValueBits ?
392         ValueVT : MVT::getIntegerVT(RoundBits);
393       SDValue Lo, Hi;
394
395       MVT HalfVT = ValueVT.isInteger() ?
396         MVT::getIntegerVT(RoundBits/2) :
397         MVT::getFloatingPointVT(RoundBits/2);
398
399       if (RoundParts > 2) {
400         Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
401         Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
402                               PartVT, HalfVT);
403       } else {
404         Lo = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[0]);
405         Hi = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[1]);
406       }
407       if (TLI.isBigEndian())
408         std::swap(Lo, Hi);
409       Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
410
411       if (RoundParts < NumParts) {
412         // Assemble the trailing non-power-of-2 part.
413         unsigned OddParts = NumParts - RoundParts;
414         MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
415         Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
416
417         // Combine the round and odd parts.
418         Lo = Val;
419         if (TLI.isBigEndian())
420           std::swap(Lo, Hi);
421         MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
422         Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
423         Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
424                          DAG.getConstant(Lo.getValueType().getSizeInBits(),
425                                          TLI.getShiftAmountTy()));
426         Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
427         Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
428       }
429     } else {
430       // Handle a multi-element vector.
431       MVT IntermediateVT, RegisterVT;
432       unsigned NumIntermediates;
433       unsigned NumRegs =
434         TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
435                                    RegisterVT);
436       assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
437       NumParts = NumRegs; // Silence a compiler warning.
438       assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
439       assert(RegisterVT == Parts[0].getValueType() &&
440              "Part type doesn't match part!");
441
442       // Assemble the parts into intermediate operands.
443       SmallVector<SDValue, 8> Ops(NumIntermediates);
444       if (NumIntermediates == NumParts) {
445         // If the register was not expanded, truncate or copy the value,
446         // as appropriate.
447         for (unsigned i = 0; i != NumParts; ++i)
448           Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
449                                     PartVT, IntermediateVT);
450       } else if (NumParts > 0) {
451         // If the intermediate type was expanded, build the intermediate operands
452         // from the parts.
453         assert(NumParts % NumIntermediates == 0 &&
454                "Must expand into a divisible number of parts!");
455         unsigned Factor = NumParts / NumIntermediates;
456         for (unsigned i = 0; i != NumIntermediates; ++i)
457           Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
458                                     PartVT, IntermediateVT);
459       }
460
461       // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
462       // operands.
463       Val = DAG.getNode(IntermediateVT.isVector() ?
464                         ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
465                         ValueVT, &Ops[0], NumIntermediates);
466     }
467   }
468
469   // There is now one part, held in Val.  Correct it to match ValueVT.
470   PartVT = Val.getValueType();
471
472   if (PartVT == ValueVT)
473     return Val;
474
475   if (PartVT.isVector()) {
476     assert(ValueVT.isVector() && "Unknown vector conversion!");
477     return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
478   }
479
480   if (ValueVT.isVector()) {
481     assert(ValueVT.getVectorElementType() == PartVT &&
482            ValueVT.getVectorNumElements() == 1 &&
483            "Only trivial scalar-to-vector conversions should get here!");
484     return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
485   }
486
487   if (PartVT.isInteger() &&
488       ValueVT.isInteger()) {
489     if (ValueVT.bitsLT(PartVT)) {
490       // For a truncate, see if we have any information to
491       // indicate whether the truncated bits will always be
492       // zero or sign-extension.
493       if (AssertOp != ISD::DELETED_NODE)
494         Val = DAG.getNode(AssertOp, PartVT, Val,
495                           DAG.getValueType(ValueVT));
496       return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
497     } else {
498       return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
499     }
500   }
501
502   if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
503     if (ValueVT.bitsLT(Val.getValueType()))
504       // FP_ROUND's are always exact here.
505       return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
506                          DAG.getIntPtrConstant(1));
507     return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
508   }
509
510   if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
511     return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
512
513   assert(0 && "Unknown mismatch!");
514   return SDValue();
515 }
516
517 /// getCopyToParts - Create a series of nodes that contain the specified value
518 /// split into legal parts.  If the parts contain more bits than Val, then, for
519 /// integers, ExtendKind can be used to specify how to generate the extra bits.
520 static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
521                            SDValue *Parts, unsigned NumParts, MVT PartVT,
522                            ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
523   TargetLowering &TLI = DAG.getTargetLoweringInfo();
524   MVT PtrVT = TLI.getPointerTy();
525   MVT ValueVT = Val.getValueType();
526   unsigned PartBits = PartVT.getSizeInBits();
527   assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
528
529   if (!NumParts)
530     return;
531
532   if (!ValueVT.isVector()) {
533     if (PartVT == ValueVT) {
534       assert(NumParts == 1 && "No-op copy with multiple parts!");
535       Parts[0] = Val;
536       return;
537     }
538
539     if (NumParts * PartBits > ValueVT.getSizeInBits()) {
540       // If the parts cover more bits than the value has, promote the value.
541       if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
542         assert(NumParts == 1 && "Do not know what to promote to!");
543         Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
544       } else if (PartVT.isInteger() && ValueVT.isInteger()) {
545         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
546         Val = DAG.getNode(ExtendKind, ValueVT, Val);
547       } else {
548         assert(0 && "Unknown mismatch!");
549       }
550     } else if (PartBits == ValueVT.getSizeInBits()) {
551       // Different types of the same size.
552       assert(NumParts == 1 && PartVT != ValueVT);
553       Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
554     } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
555       // If the parts cover less bits than value has, truncate the value.
556       if (PartVT.isInteger() && ValueVT.isInteger()) {
557         ValueVT = MVT::getIntegerVT(NumParts * PartBits);
558         Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
559       } else {
560         assert(0 && "Unknown mismatch!");
561       }
562     }
563
564     // The value may have changed - recompute ValueVT.
565     ValueVT = Val.getValueType();
566     assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
567            "Failed to tile the value with PartVT!");
568
569     if (NumParts == 1) {
570       assert(PartVT == ValueVT && "Type conversion failed!");
571       Parts[0] = Val;
572       return;
573     }
574
575     // Expand the value into multiple parts.
576     if (NumParts & (NumParts - 1)) {
577       // The number of parts is not a power of 2.  Split off and copy the tail.
578       assert(PartVT.isInteger() && ValueVT.isInteger() &&
579              "Do not know what to expand to!");
580       unsigned RoundParts = 1 << Log2_32(NumParts);
581       unsigned RoundBits = RoundParts * PartBits;
582       unsigned OddParts = NumParts - RoundParts;
583       SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
584                                      DAG.getConstant(RoundBits,
585                                                      TLI.getShiftAmountTy()));
586       getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
587       if (TLI.isBigEndian())
588         // The odd parts were reversed by getCopyToParts - unreverse them.
589         std::reverse(Parts + RoundParts, Parts + NumParts);
590       NumParts = RoundParts;
591       ValueVT = MVT::getIntegerVT(NumParts * PartBits);
592       Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
593     }
594
595     // The number of parts is a power of 2.  Repeatedly bisect the value using
596     // EXTRACT_ELEMENT.
597     Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
598                            MVT::getIntegerVT(ValueVT.getSizeInBits()),
599                            Val);
600     for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
601       for (unsigned i = 0; i < NumParts; i += StepSize) {
602         unsigned ThisBits = StepSize * PartBits / 2;
603         MVT ThisVT = MVT::getIntegerVT (ThisBits);
604         SDValue &Part0 = Parts[i];
605         SDValue &Part1 = Parts[i+StepSize/2];
606
607         Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
608                             DAG.getConstant(1, PtrVT));
609         Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
610                             DAG.getConstant(0, PtrVT));
611
612         if (ThisBits == PartBits && ThisVT != PartVT) {
613           Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
614           Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
615         }
616       }
617     }
618
619     if (TLI.isBigEndian())
620       std::reverse(Parts, Parts + NumParts);
621
622     return;
623   }
624
625   // Vector ValueVT.
626   if (NumParts == 1) {
627     if (PartVT != ValueVT) {
628       if (PartVT.isVector()) {
629         Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
630       } else {
631         assert(ValueVT.getVectorElementType() == PartVT &&
632                ValueVT.getVectorNumElements() == 1 &&
633                "Only trivial vector-to-scalar conversions should get here!");
634         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
635                           DAG.getConstant(0, PtrVT));
636       }
637     }
638
639     Parts[0] = Val;
640     return;
641   }
642
643   // Handle a multi-element vector.
644   MVT IntermediateVT, RegisterVT;
645   unsigned NumIntermediates;
646   unsigned NumRegs =
647     DAG.getTargetLoweringInfo()
648       .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
649                               RegisterVT);
650   unsigned NumElements = ValueVT.getVectorNumElements();
651
652   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
653   NumParts = NumRegs; // Silence a compiler warning.
654   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
655
656   // Split the vector into intermediate operands.
657   SmallVector<SDValue, 8> Ops(NumIntermediates);
658   for (unsigned i = 0; i != NumIntermediates; ++i)
659     if (IntermediateVT.isVector())
660       Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
661                            IntermediateVT, Val,
662                            DAG.getConstant(i * (NumElements / NumIntermediates),
663                                            PtrVT));
664     else
665       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
666                            IntermediateVT, Val, 
667                            DAG.getConstant(i, PtrVT));
668
669   // Split the intermediate operands into legal parts.
670   if (NumParts == NumIntermediates) {
671     // If the register was not expanded, promote or copy the value,
672     // as appropriate.
673     for (unsigned i = 0; i != NumParts; ++i)
674       getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
675   } else if (NumParts > 0) {
676     // If the intermediate type was expanded, split each the value into
677     // legal parts.
678     assert(NumParts % NumIntermediates == 0 &&
679            "Must expand into a divisible number of parts!");
680     unsigned Factor = NumParts / NumIntermediates;
681     for (unsigned i = 0; i != NumIntermediates; ++i)
682       getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
683   }
684 }
685
686
687 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
688   AA = &aa;
689   GFI = gfi;
690   TD = DAG.getTarget().getTargetData();
691 }
692
693 /// clear - Clear out the curret SelectionDAG and the associated
694 /// state and prepare this SelectionDAGLowering object to be used
695 /// for a new block. This doesn't clear out information about
696 /// additional blocks that are needed to complete switch lowering
697 /// or PHI node updating; that information is cleared out as it is
698 /// consumed.
699 void SelectionDAGLowering::clear() {
700   NodeMap.clear();
701   PendingLoads.clear();
702   PendingExports.clear();
703   DAG.clear();
704 }
705
706 /// getRoot - Return the current virtual root of the Selection DAG,
707 /// flushing any PendingLoad items. This must be done before emitting
708 /// a store or any other node that may need to be ordered after any
709 /// prior load instructions.
710 ///
711 SDValue SelectionDAGLowering::getRoot() {
712   if (PendingLoads.empty())
713     return DAG.getRoot();
714
715   if (PendingLoads.size() == 1) {
716     SDValue Root = PendingLoads[0];
717     DAG.setRoot(Root);
718     PendingLoads.clear();
719     return Root;
720   }
721
722   // Otherwise, we have to make a token factor node.
723   SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
724                                &PendingLoads[0], PendingLoads.size());
725   PendingLoads.clear();
726   DAG.setRoot(Root);
727   return Root;
728 }
729
730 /// getControlRoot - Similar to getRoot, but instead of flushing all the
731 /// PendingLoad items, flush all the PendingExports items. It is necessary
732 /// to do this before emitting a terminator instruction.
733 ///
734 SDValue SelectionDAGLowering::getControlRoot() {
735   SDValue Root = DAG.getRoot();
736
737   if (PendingExports.empty())
738     return Root;
739
740   // Turn all of the CopyToReg chains into one factored node.
741   if (Root.getOpcode() != ISD::EntryToken) {
742     unsigned i = 0, e = PendingExports.size();
743     for (; i != e; ++i) {
744       assert(PendingExports[i].getNode()->getNumOperands() > 1);
745       if (PendingExports[i].getNode()->getOperand(0) == Root)
746         break;  // Don't add the root if we already indirectly depend on it.
747     }
748
749     if (i == e)
750       PendingExports.push_back(Root);
751   }
752
753   Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
754                      &PendingExports[0],
755                      PendingExports.size());
756   PendingExports.clear();
757   DAG.setRoot(Root);
758   return Root;
759 }
760
761 void SelectionDAGLowering::visit(Instruction &I) {
762   visit(I.getOpcode(), I);
763 }
764
765 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
766   // Note: this doesn't use InstVisitor, because it has to work with
767   // ConstantExpr's in addition to instructions.
768   switch (Opcode) {
769   default: assert(0 && "Unknown instruction type encountered!");
770            abort();
771     // Build the switch statement using the Instruction.def file.
772 #define HANDLE_INST(NUM, OPCODE, CLASS) \
773   case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
774 #include "llvm/Instruction.def"
775   }
776
777
778 void SelectionDAGLowering::visitAdd(User &I) {
779   if (I.getType()->isFPOrFPVector())
780     visitBinary(I, ISD::FADD);
781   else
782     visitBinary(I, ISD::ADD);
783 }
784
785 void SelectionDAGLowering::visitMul(User &I) {
786   if (I.getType()->isFPOrFPVector())
787     visitBinary(I, ISD::FMUL);
788   else
789     visitBinary(I, ISD::MUL);
790 }
791
792 SDValue SelectionDAGLowering::getValue(const Value *V) {
793   SDValue &N = NodeMap[V];
794   if (N.getNode()) return N;
795   
796   if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
797     MVT VT = TLI.getValueType(V->getType(), true);
798     
799     if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
800       return N = DAG.getConstant(*CI, VT);
801
802     if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
803       return N = DAG.getGlobalAddress(GV, VT);
804     
805     if (isa<ConstantPointerNull>(C))
806       return N = DAG.getConstant(0, TLI.getPointerTy());
807     
808     if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
809       return N = DAG.getConstantFP(*CFP, VT);
810     
811     if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
812         !V->getType()->isAggregateType())
813       return N = DAG.getNode(ISD::UNDEF, VT);
814
815     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
816       visit(CE->getOpcode(), *CE);
817       SDValue N1 = NodeMap[V];
818       assert(N1.getNode() && "visit didn't populate the ValueMap!");
819       return N1;
820     }
821     
822     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
823       SmallVector<SDValue, 4> Constants;
824       for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
825            OI != OE; ++OI) {
826         SDNode *Val = getValue(*OI).getNode();
827         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
828           Constants.push_back(SDValue(Val, i));
829       }
830       return DAG.getMergeValues(&Constants[0], Constants.size());
831     }
832
833     if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
834       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
835              "Unknown struct or array constant!");
836
837       SmallVector<MVT, 4> ValueVTs;
838       ComputeValueVTs(TLI, C->getType(), ValueVTs);
839       unsigned NumElts = ValueVTs.size();
840       if (NumElts == 0)
841         return SDValue(); // empty struct
842       SmallVector<SDValue, 4> Constants(NumElts);
843       for (unsigned i = 0; i != NumElts; ++i) {
844         MVT EltVT = ValueVTs[i];
845         if (isa<UndefValue>(C))
846           Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
847         else if (EltVT.isFloatingPoint())
848           Constants[i] = DAG.getConstantFP(0, EltVT);
849         else
850           Constants[i] = DAG.getConstant(0, EltVT);
851       }
852       return DAG.getMergeValues(&Constants[0], NumElts);
853     }
854
855     const VectorType *VecTy = cast<VectorType>(V->getType());
856     unsigned NumElements = VecTy->getNumElements();
857     
858     // Now that we know the number and type of the elements, get that number of
859     // elements into the Ops array based on what kind of constant it is.
860     SmallVector<SDValue, 16> Ops;
861     if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
862       for (unsigned i = 0; i != NumElements; ++i)
863         Ops.push_back(getValue(CP->getOperand(i)));
864     } else {
865       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
866              "Unknown vector constant!");
867       MVT EltVT = TLI.getValueType(VecTy->getElementType());
868
869       SDValue Op;
870       if (isa<UndefValue>(C))
871         Op = DAG.getNode(ISD::UNDEF, EltVT);
872       else if (EltVT.isFloatingPoint())
873         Op = DAG.getConstantFP(0, EltVT);
874       else
875         Op = DAG.getConstant(0, EltVT);
876       Ops.assign(NumElements, Op);
877     }
878     
879     // Create a BUILD_VECTOR node.
880     return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
881   }
882       
883   // If this is a static alloca, generate it as the frameindex instead of
884   // computation.
885   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
886     DenseMap<const AllocaInst*, int>::iterator SI =
887       FuncInfo.StaticAllocaMap.find(AI);
888     if (SI != FuncInfo.StaticAllocaMap.end())
889       return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
890   }
891       
892   unsigned InReg = FuncInfo.ValueMap[V];
893   assert(InReg && "Value not in map!");
894   
895   RegsForValue RFV(TLI, InReg, V->getType());
896   SDValue Chain = DAG.getEntryNode();
897   return RFV.getCopyFromRegs(DAG, Chain, NULL);
898 }
899
900
901 void SelectionDAGLowering::visitRet(ReturnInst &I) {
902   if (I.getNumOperands() == 0) {
903     DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
904     return;
905   }
906   
907   SmallVector<SDValue, 8> NewValues;
908   NewValues.push_back(getControlRoot());
909   for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {  
910     SmallVector<MVT, 4> ValueVTs;
911     ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
912     unsigned NumValues = ValueVTs.size();
913     if (NumValues == 0) continue;
914
915     SDValue RetOp = getValue(I.getOperand(i));
916     for (unsigned j = 0, f = NumValues; j != f; ++j) {
917       MVT VT = ValueVTs[j];
918
919       // FIXME: C calling convention requires the return type to be promoted to
920       // at least 32-bit. But this is not necessary for non-C calling
921       // conventions.
922       if (VT.isInteger()) {
923         MVT MinVT = TLI.getRegisterType(MVT::i32);
924         if (VT.bitsLT(MinVT))
925           VT = MinVT;
926       }
927
928       unsigned NumParts = TLI.getNumRegisters(VT);
929       MVT PartVT = TLI.getRegisterType(VT);
930       SmallVector<SDValue, 4> Parts(NumParts);
931       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
932   
933       const Function *F = I.getParent()->getParent();
934       if (F->paramHasAttr(0, Attribute::SExt))
935         ExtendKind = ISD::SIGN_EXTEND;
936       else if (F->paramHasAttr(0, Attribute::ZExt))
937         ExtendKind = ISD::ZERO_EXTEND;
938
939       getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
940                      &Parts[0], NumParts, PartVT, ExtendKind);
941
942       // 'inreg' on function refers to return value
943       ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
944       if (F->paramHasAttr(0, Attribute::InReg))
945         Flags.setInReg();
946       for (unsigned i = 0; i < NumParts; ++i) {
947         NewValues.push_back(Parts[i]);
948         NewValues.push_back(DAG.getArgFlags(Flags));
949       }
950     }
951   }
952   DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
953                           &NewValues[0], NewValues.size()));
954 }
955
956 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
957 /// the current basic block, add it to ValueMap now so that we'll get a
958 /// CopyTo/FromReg.
959 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
960   // No need to export constants.
961   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
962   
963   // Already exported?
964   if (FuncInfo.isExportedInst(V)) return;
965
966   unsigned Reg = FuncInfo.InitializeRegForValue(V);
967   CopyValueToVirtualRegister(V, Reg);
968 }
969
970 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
971                                                     const BasicBlock *FromBB) {
972   // The operands of the setcc have to be in this block.  We don't know
973   // how to export them from some other block.
974   if (Instruction *VI = dyn_cast<Instruction>(V)) {
975     // Can export from current BB.
976     if (VI->getParent() == FromBB)
977       return true;
978     
979     // Is already exported, noop.
980     return FuncInfo.isExportedInst(V);
981   }
982   
983   // If this is an argument, we can export it if the BB is the entry block or
984   // if it is already exported.
985   if (isa<Argument>(V)) {
986     if (FromBB == &FromBB->getParent()->getEntryBlock())
987       return true;
988
989     // Otherwise, can only export this if it is already exported.
990     return FuncInfo.isExportedInst(V);
991   }
992   
993   // Otherwise, constants can always be exported.
994   return true;
995 }
996
997 static bool InBlock(const Value *V, const BasicBlock *BB) {
998   if (const Instruction *I = dyn_cast<Instruction>(V))
999     return I->getParent() == BB;
1000   return true;
1001 }
1002
1003 /// getFCmpCondCode - Return the ISD condition code corresponding to
1004 /// the given LLVM IR floating-point condition code.  This includes
1005 /// consideration of global floating-point math flags.
1006 ///
1007 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1008   ISD::CondCode FPC, FOC;
1009   switch (Pred) {
1010   case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1011   case FCmpInst::FCMP_OEQ:   FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1012   case FCmpInst::FCMP_OGT:   FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1013   case FCmpInst::FCMP_OGE:   FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1014   case FCmpInst::FCMP_OLT:   FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1015   case FCmpInst::FCMP_OLE:   FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1016   case FCmpInst::FCMP_ONE:   FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1017   case FCmpInst::FCMP_ORD:   FOC = FPC = ISD::SETO;   break;
1018   case FCmpInst::FCMP_UNO:   FOC = FPC = ISD::SETUO;  break;
1019   case FCmpInst::FCMP_UEQ:   FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1020   case FCmpInst::FCMP_UGT:   FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1021   case FCmpInst::FCMP_UGE:   FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1022   case FCmpInst::FCMP_ULT:   FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1023   case FCmpInst::FCMP_ULE:   FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1024   case FCmpInst::FCMP_UNE:   FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1025   case FCmpInst::FCMP_TRUE:  FOC = FPC = ISD::SETTRUE; break;
1026   default:
1027     assert(0 && "Invalid FCmp predicate opcode!");
1028     FOC = FPC = ISD::SETFALSE;
1029     break;
1030   }
1031   if (FiniteOnlyFPMath())
1032     return FOC;
1033   else 
1034     return FPC;
1035 }
1036
1037 /// getICmpCondCode - Return the ISD condition code corresponding to
1038 /// the given LLVM IR integer condition code.
1039 ///
1040 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1041   switch (Pred) {
1042   case ICmpInst::ICMP_EQ:  return ISD::SETEQ;
1043   case ICmpInst::ICMP_NE:  return ISD::SETNE;
1044   case ICmpInst::ICMP_SLE: return ISD::SETLE;
1045   case ICmpInst::ICMP_ULE: return ISD::SETULE;
1046   case ICmpInst::ICMP_SGE: return ISD::SETGE;
1047   case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1048   case ICmpInst::ICMP_SLT: return ISD::SETLT;
1049   case ICmpInst::ICMP_ULT: return ISD::SETULT;
1050   case ICmpInst::ICMP_SGT: return ISD::SETGT;
1051   case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1052   default:
1053     assert(0 && "Invalid ICmp predicate opcode!");
1054     return ISD::SETNE;
1055   }
1056 }
1057
1058 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1059 /// This function emits a branch and is used at the leaves of an OR or an
1060 /// AND operator tree.
1061 ///
1062 void
1063 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1064                                                    MachineBasicBlock *TBB,
1065                                                    MachineBasicBlock *FBB,
1066                                                    MachineBasicBlock *CurBB) {
1067   const BasicBlock *BB = CurBB->getBasicBlock();
1068
1069   // If the leaf of the tree is a comparison, merge the condition into
1070   // the caseblock.
1071   if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1072     // The operands of the cmp have to be in this block.  We don't know
1073     // how to export them from some other block.  If this is the first block
1074     // of the sequence, no exporting is needed.
1075     if (CurBB == CurMBB ||
1076         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1077          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1078       ISD::CondCode Condition;
1079       if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1080         Condition = getICmpCondCode(IC->getPredicate());
1081       } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1082         Condition = getFCmpCondCode(FC->getPredicate());
1083       } else {
1084         Condition = ISD::SETEQ; // silence warning.
1085         assert(0 && "Unknown compare instruction");
1086       }
1087
1088       CaseBlock CB(Condition, BOp->getOperand(0),
1089                    BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1090       SwitchCases.push_back(CB);
1091       return;
1092     }
1093   }
1094
1095   // Create a CaseBlock record representing this branch.
1096   CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1097                NULL, TBB, FBB, CurBB);
1098   SwitchCases.push_back(CB);
1099 }
1100
1101 /// FindMergedConditions - If Cond is an expression like 
1102 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1103                                                 MachineBasicBlock *TBB,
1104                                                 MachineBasicBlock *FBB,
1105                                                 MachineBasicBlock *CurBB,
1106                                                 unsigned Opc) {
1107   // If this node is not part of the or/and tree, emit it as a branch.
1108   Instruction *BOp = dyn_cast<Instruction>(Cond);
1109   if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 
1110       (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1111       BOp->getParent() != CurBB->getBasicBlock() ||
1112       !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1113       !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1114     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1115     return;
1116   }
1117   
1118   //  Create TmpBB after CurBB.
1119   MachineFunction::iterator BBI = CurBB;
1120   MachineFunction &MF = DAG.getMachineFunction();
1121   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1122   CurBB->getParent()->insert(++BBI, TmpBB);
1123   
1124   if (Opc == Instruction::Or) {
1125     // Codegen X | Y as:
1126     //   jmp_if_X TBB
1127     //   jmp TmpBB
1128     // TmpBB:
1129     //   jmp_if_Y TBB
1130     //   jmp FBB
1131     //
1132   
1133     // Emit the LHS condition.
1134     FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1135   
1136     // Emit the RHS condition into TmpBB.
1137     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1138   } else {
1139     assert(Opc == Instruction::And && "Unknown merge op!");
1140     // Codegen X & Y as:
1141     //   jmp_if_X TmpBB
1142     //   jmp FBB
1143     // TmpBB:
1144     //   jmp_if_Y TBB
1145     //   jmp FBB
1146     //
1147     //  This requires creation of TmpBB after CurBB.
1148     
1149     // Emit the LHS condition.
1150     FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1151     
1152     // Emit the RHS condition into TmpBB.
1153     FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1154   }
1155 }
1156
1157 /// If the set of cases should be emitted as a series of branches, return true.
1158 /// If we should emit this as a bunch of and/or'd together conditions, return
1159 /// false.
1160 bool 
1161 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1162   if (Cases.size() != 2) return true;
1163   
1164   // If this is two comparisons of the same values or'd or and'd together, they
1165   // will get folded into a single comparison, so don't emit two blocks.
1166   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1167        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1168       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1169        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1170     return false;
1171   }
1172   
1173   return true;
1174 }
1175
1176 void SelectionDAGLowering::visitBr(BranchInst &I) {
1177   // Update machine-CFG edges.
1178   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1179
1180   // Figure out which block is immediately after the current one.
1181   MachineBasicBlock *NextBlock = 0;
1182   MachineFunction::iterator BBI = CurMBB;
1183   if (++BBI != CurMBB->getParent()->end())
1184     NextBlock = BBI;
1185
1186   if (I.isUnconditional()) {
1187     // Update machine-CFG edges.
1188     CurMBB->addSuccessor(Succ0MBB);
1189     
1190     // If this is not a fall-through branch, emit the branch.
1191     if (Succ0MBB != NextBlock)
1192       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1193                               DAG.getBasicBlock(Succ0MBB)));
1194     return;
1195   }
1196
1197   // If this condition is one of the special cases we handle, do special stuff
1198   // now.
1199   Value *CondVal = I.getCondition();
1200   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1201
1202   // If this is a series of conditions that are or'd or and'd together, emit
1203   // this as a sequence of branches instead of setcc's with and/or operations.
1204   // For example, instead of something like:
1205   //     cmp A, B
1206   //     C = seteq 
1207   //     cmp D, E
1208   //     F = setle 
1209   //     or C, F
1210   //     jnz foo
1211   // Emit:
1212   //     cmp A, B
1213   //     je foo
1214   //     cmp D, E
1215   //     jle foo
1216   //
1217   if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1218     if (BOp->hasOneUse() && 
1219         (BOp->getOpcode() == Instruction::And ||
1220          BOp->getOpcode() == Instruction::Or)) {
1221       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1222       // If the compares in later blocks need to use values not currently
1223       // exported from this block, export them now.  This block should always
1224       // be the first entry.
1225       assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1226       
1227       // Allow some cases to be rejected.
1228       if (ShouldEmitAsBranches(SwitchCases)) {
1229         for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1230           ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1231           ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1232         }
1233         
1234         // Emit the branch for this block.
1235         visitSwitchCase(SwitchCases[0]);
1236         SwitchCases.erase(SwitchCases.begin());
1237         return;
1238       }
1239       
1240       // Okay, we decided not to do this, remove any inserted MBB's and clear
1241       // SwitchCases.
1242       for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1243         CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1244       
1245       SwitchCases.clear();
1246     }
1247   }
1248   
1249   // Create a CaseBlock record representing this branch.
1250   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1251                NULL, Succ0MBB, Succ1MBB, CurMBB);
1252   // Use visitSwitchCase to actually insert the fast branch sequence for this
1253   // cond branch.
1254   visitSwitchCase(CB);
1255 }
1256
1257 /// visitSwitchCase - Emits the necessary code to represent a single node in
1258 /// the binary search tree resulting from lowering a switch instruction.
1259 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1260   SDValue Cond;
1261   SDValue CondLHS = getValue(CB.CmpLHS);
1262   
1263   // Build the setcc now. 
1264   if (CB.CmpMHS == NULL) {
1265     // Fold "(X == true)" to X and "(X == false)" to !X to
1266     // handle common cases produced by branch lowering.
1267     if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1268       Cond = CondLHS;
1269     else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1270       SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1271       Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1272     } else
1273       Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1274   } else {
1275     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1276
1277     uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1278     uint64_t High  = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1279
1280     SDValue CmpOp = getValue(CB.CmpMHS);
1281     MVT VT = CmpOp.getValueType();
1282
1283     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1284       Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1285     } else {
1286       SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1287       Cond = DAG.getSetCC(MVT::i1, SUB,
1288                           DAG.getConstant(High-Low, VT), ISD::SETULE);
1289     }
1290   }
1291   
1292   // Update successor info
1293   CurMBB->addSuccessor(CB.TrueBB);
1294   CurMBB->addSuccessor(CB.FalseBB);
1295   
1296   // Set NextBlock to be the MBB immediately after the current one, if any.
1297   // This is used to avoid emitting unnecessary branches to the next block.
1298   MachineBasicBlock *NextBlock = 0;
1299   MachineFunction::iterator BBI = CurMBB;
1300   if (++BBI != CurMBB->getParent()->end())
1301     NextBlock = BBI;
1302   
1303   // If the lhs block is the next block, invert the condition so that we can
1304   // fall through to the lhs instead of the rhs block.
1305   if (CB.TrueBB == NextBlock) {
1306     std::swap(CB.TrueBB, CB.FalseBB);
1307     SDValue True = DAG.getConstant(1, Cond.getValueType());
1308     Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1309   }
1310   SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1311                                  DAG.getBasicBlock(CB.TrueBB));
1312   
1313   // If the branch was constant folded, fix up the CFG.
1314   if (BrCond.getOpcode() == ISD::BR) {
1315     CurMBB->removeSuccessor(CB.FalseBB);
1316     DAG.setRoot(BrCond);
1317   } else {
1318     // Otherwise, go ahead and insert the false branch.
1319     if (BrCond == getControlRoot()) 
1320       CurMBB->removeSuccessor(CB.TrueBB);
1321     
1322     if (CB.FalseBB == NextBlock)
1323       DAG.setRoot(BrCond);
1324     else
1325       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
1326                               DAG.getBasicBlock(CB.FalseBB)));
1327   }
1328 }
1329
1330 /// visitJumpTable - Emit JumpTable node in the current MBB
1331 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1332   // Emit the code for the jump table
1333   assert(JT.Reg != -1U && "Should lower JT Header first!");
1334   MVT PTy = TLI.getPointerTy();
1335   SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1336   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1337   DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1338                           Table, Index));
1339   return;
1340 }
1341
1342 /// visitJumpTableHeader - This function emits necessary code to produce index
1343 /// in the JumpTable from switch case.
1344 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1345                                                 JumpTableHeader &JTH) {
1346   // Subtract the lowest switch case value from the value being switched on
1347   // and conditional branch to default mbb if the result is greater than the
1348   // difference between smallest and largest cases.
1349   SDValue SwitchOp = getValue(JTH.SValue);
1350   MVT VT = SwitchOp.getValueType();
1351   SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1352                               DAG.getConstant(JTH.First, VT));
1353   
1354   // The SDNode we just created, which holds the value being switched on
1355   // minus the the smallest case value, needs to be copied to a virtual
1356   // register so it can be used as an index into the jump table in a 
1357   // subsequent basic block.  This value may be smaller or larger than the
1358   // target's pointer type, and therefore require extension or truncating.
1359   if (VT.bitsGT(TLI.getPointerTy()))
1360     SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1361   else
1362     SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1363   
1364   unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1365   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1366   JT.Reg = JumpTableReg;
1367
1368   // Emit the range check for the jump table, and branch to the default
1369   // block for the switch statement if the value being switched on exceeds
1370   // the largest case in the switch.
1371   SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1372                                DAG.getConstant(JTH.Last-JTH.First,VT),
1373                                ISD::SETUGT);
1374
1375   // Set NextBlock to be the MBB immediately after the current one, if any.
1376   // This is used to avoid emitting unnecessary branches to the next block.
1377   MachineBasicBlock *NextBlock = 0;
1378   MachineFunction::iterator BBI = CurMBB;
1379   if (++BBI != CurMBB->getParent()->end())
1380     NextBlock = BBI;
1381
1382   SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1383                                  DAG.getBasicBlock(JT.Default));
1384
1385   if (JT.MBB == NextBlock)
1386     DAG.setRoot(BrCond);
1387   else
1388     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond, 
1389                             DAG.getBasicBlock(JT.MBB)));
1390
1391   return;
1392 }
1393
1394 /// visitBitTestHeader - This function emits necessary code to produce value
1395 /// suitable for "bit tests"
1396 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1397   // Subtract the minimum value
1398   SDValue SwitchOp = getValue(B.SValue);
1399   MVT VT = SwitchOp.getValueType();
1400   SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1401                               DAG.getConstant(B.First, VT));
1402
1403   // Check range
1404   SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1405                                     DAG.getConstant(B.Range, VT),
1406                                     ISD::SETUGT);
1407
1408   SDValue ShiftOp;
1409   if (VT.bitsGT(TLI.getShiftAmountTy()))
1410     ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1411   else
1412     ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1413
1414   // Make desired shift
1415   SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1416                                     DAG.getConstant(1, TLI.getPointerTy()),
1417                                     ShiftOp);
1418
1419   unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1420   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1421   B.Reg = SwitchReg;
1422
1423   // Set NextBlock to be the MBB immediately after the current one, if any.
1424   // This is used to avoid emitting unnecessary branches to the next block.
1425   MachineBasicBlock *NextBlock = 0;
1426   MachineFunction::iterator BBI = CurMBB;
1427   if (++BBI != CurMBB->getParent()->end())
1428     NextBlock = BBI;
1429
1430   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1431
1432   CurMBB->addSuccessor(B.Default);
1433   CurMBB->addSuccessor(MBB);
1434
1435   SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1436                                   DAG.getBasicBlock(B.Default));
1437   
1438   if (MBB == NextBlock)
1439     DAG.setRoot(BrRange);
1440   else
1441     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1442                             DAG.getBasicBlock(MBB)));
1443
1444   return;
1445 }
1446
1447 /// visitBitTestCase - this function produces one "bit test"
1448 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1449                                             unsigned Reg,
1450                                             BitTestCase &B) {
1451   // Emit bit tests and jumps
1452   SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg, 
1453                                            TLI.getPointerTy());
1454   
1455   SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1456                                 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1457   SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1458                                   DAG.getConstant(0, TLI.getPointerTy()),
1459                                   ISD::SETNE);
1460
1461   CurMBB->addSuccessor(B.TargetBB);
1462   CurMBB->addSuccessor(NextMBB);
1463   
1464   SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1465                                 AndCmp, DAG.getBasicBlock(B.TargetBB));
1466
1467   // Set NextBlock to be the MBB immediately after the current one, if any.
1468   // This is used to avoid emitting unnecessary branches to the next block.
1469   MachineBasicBlock *NextBlock = 0;
1470   MachineFunction::iterator BBI = CurMBB;
1471   if (++BBI != CurMBB->getParent()->end())
1472     NextBlock = BBI;
1473
1474   if (NextMBB == NextBlock)
1475     DAG.setRoot(BrAnd);
1476   else
1477     DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1478                             DAG.getBasicBlock(NextMBB)));
1479
1480   return;
1481 }
1482
1483 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1484   // Retrieve successors.
1485   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1486   MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1487
1488   if (isa<InlineAsm>(I.getCalledValue()))
1489     visitInlineAsm(&I);
1490   else
1491     LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1492
1493   // If the value of the invoke is used outside of its defining block, make it
1494   // available as a virtual register.
1495   if (!I.use_empty()) {
1496     DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1497     if (VMI != FuncInfo.ValueMap.end())
1498       CopyValueToVirtualRegister(&I, VMI->second);
1499   }
1500
1501   // Update successor info
1502   CurMBB->addSuccessor(Return);
1503   CurMBB->addSuccessor(LandingPad);
1504
1505   // Drop into normal successor.
1506   DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1507                           DAG.getBasicBlock(Return)));
1508 }
1509
1510 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1511 }
1512
1513 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1514 /// small case ranges).
1515 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1516                                                   CaseRecVector& WorkList,
1517                                                   Value* SV,
1518                                                   MachineBasicBlock* Default) {
1519   Case& BackCase  = *(CR.Range.second-1);
1520   
1521   // Size is the number of Cases represented by this range.
1522   unsigned Size = CR.Range.second - CR.Range.first;
1523   if (Size > 3)
1524     return false;  
1525   
1526   // Get the MachineFunction which holds the current MBB.  This is used when
1527   // inserting any additional MBBs necessary to represent the switch.
1528   MachineFunction *CurMF = CurMBB->getParent();  
1529
1530   // Figure out which block is immediately after the current one.
1531   MachineBasicBlock *NextBlock = 0;
1532   MachineFunction::iterator BBI = CR.CaseBB;
1533
1534   if (++BBI != CurMBB->getParent()->end())
1535     NextBlock = BBI;
1536
1537   // TODO: If any two of the cases has the same destination, and if one value
1538   // is the same as the other, but has one bit unset that the other has set,
1539   // use bit manipulation to do two compares at once.  For example:
1540   // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1541     
1542   // Rearrange the case blocks so that the last one falls through if possible.
1543   if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1544     // The last case block won't fall through into 'NextBlock' if we emit the
1545     // branches in this order.  See if rearranging a case value would help.
1546     for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1547       if (I->BB == NextBlock) {
1548         std::swap(*I, BackCase);
1549         break;
1550       }
1551     }
1552   }
1553   
1554   // Create a CaseBlock record representing a conditional branch to
1555   // the Case's target mbb if the value being switched on SV is equal
1556   // to C.
1557   MachineBasicBlock *CurBlock = CR.CaseBB;
1558   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1559     MachineBasicBlock *FallThrough;
1560     if (I != E-1) {
1561       FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1562       CurMF->insert(BBI, FallThrough);
1563     } else {
1564       // If the last case doesn't match, go to the default block.
1565       FallThrough = Default;
1566     }
1567
1568     Value *RHS, *LHS, *MHS;
1569     ISD::CondCode CC;
1570     if (I->High == I->Low) {
1571       // This is just small small case range :) containing exactly 1 case
1572       CC = ISD::SETEQ;
1573       LHS = SV; RHS = I->High; MHS = NULL;
1574     } else {
1575       CC = ISD::SETLE;
1576       LHS = I->Low; MHS = SV; RHS = I->High;
1577     }
1578     CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1579     
1580     // If emitting the first comparison, just call visitSwitchCase to emit the
1581     // code into the current block.  Otherwise, push the CaseBlock onto the
1582     // vector to be later processed by SDISel, and insert the node's MBB
1583     // before the next MBB.
1584     if (CurBlock == CurMBB)
1585       visitSwitchCase(CB);
1586     else
1587       SwitchCases.push_back(CB);
1588     
1589     CurBlock = FallThrough;
1590   }
1591
1592   return true;
1593 }
1594
1595 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1596   return !DisableJumpTables &&
1597           (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1598            TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1599 }
1600   
1601 /// handleJTSwitchCase - Emit jumptable for current switch case range
1602 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1603                                               CaseRecVector& WorkList,
1604                                               Value* SV,
1605                                               MachineBasicBlock* Default) {
1606   Case& FrontCase = *CR.Range.first;
1607   Case& BackCase  = *(CR.Range.second-1);
1608
1609   int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1610   int64_t Last  = cast<ConstantInt>(BackCase.High)->getSExtValue();
1611
1612   uint64_t TSize = 0;
1613   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1614        I!=E; ++I)
1615     TSize += I->size();
1616
1617   if (!areJTsAllowed(TLI) || TSize <= 3)
1618     return false;
1619   
1620   double Density = (double)TSize / (double)((Last - First) + 1ULL);  
1621   if (Density < 0.4)
1622     return false;
1623
1624   DOUT << "Lowering jump table\n"
1625        << "First entry: " << First << ". Last entry: " << Last << "\n"
1626        << "Size: " << TSize << ". Density: " << Density << "\n\n";
1627
1628   // Get the MachineFunction which holds the current MBB.  This is used when
1629   // inserting any additional MBBs necessary to represent the switch.
1630   MachineFunction *CurMF = CurMBB->getParent();
1631
1632   // Figure out which block is immediately after the current one.
1633   MachineBasicBlock *NextBlock = 0;
1634   MachineFunction::iterator BBI = CR.CaseBB;
1635
1636   if (++BBI != CurMBB->getParent()->end())
1637     NextBlock = BBI;
1638
1639   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1640
1641   // Create a new basic block to hold the code for loading the address
1642   // of the jump table, and jumping to it.  Update successor information;
1643   // we will either branch to the default case for the switch, or the jump
1644   // table.
1645   MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1646   CurMF->insert(BBI, JumpTableBB);
1647   CR.CaseBB->addSuccessor(Default);
1648   CR.CaseBB->addSuccessor(JumpTableBB);
1649                 
1650   // Build a vector of destination BBs, corresponding to each target
1651   // of the jump table. If the value of the jump table slot corresponds to
1652   // a case statement, push the case's BB onto the vector, otherwise, push
1653   // the default BB.
1654   std::vector<MachineBasicBlock*> DestBBs;
1655   int64_t TEI = First;
1656   for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1657     int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1658     int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1659     
1660     if ((Low <= TEI) && (TEI <= High)) {
1661       DestBBs.push_back(I->BB);
1662       if (TEI==High)
1663         ++I;
1664     } else {
1665       DestBBs.push_back(Default);
1666     }
1667   }
1668   
1669   // Update successor info. Add one edge to each unique successor.
1670   BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());  
1671   for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(), 
1672          E = DestBBs.end(); I != E; ++I) {
1673     if (!SuccsHandled[(*I)->getNumber()]) {
1674       SuccsHandled[(*I)->getNumber()] = true;
1675       JumpTableBB->addSuccessor(*I);
1676     }
1677   }
1678       
1679   // Create a jump table index for this jump table, or return an existing
1680   // one.
1681   unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1682   
1683   // Set the jump table information so that we can codegen it as a second
1684   // MachineBasicBlock
1685   JumpTable JT(-1U, JTI, JumpTableBB, Default);
1686   JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1687   if (CR.CaseBB == CurMBB)
1688     visitJumpTableHeader(JT, JTH);
1689         
1690   JTCases.push_back(JumpTableBlock(JTH, JT));
1691
1692   return true;
1693 }
1694
1695 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1696 /// 2 subtrees.
1697 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1698                                                    CaseRecVector& WorkList,
1699                                                    Value* SV,
1700                                                    MachineBasicBlock* Default) {
1701   // Get the MachineFunction which holds the current MBB.  This is used when
1702   // inserting any additional MBBs necessary to represent the switch.
1703   MachineFunction *CurMF = CurMBB->getParent();  
1704
1705   // Figure out which block is immediately after the current one.
1706   MachineBasicBlock *NextBlock = 0;
1707   MachineFunction::iterator BBI = CR.CaseBB;
1708
1709   if (++BBI != CurMBB->getParent()->end())
1710     NextBlock = BBI;
1711
1712   Case& FrontCase = *CR.Range.first;
1713   Case& BackCase  = *(CR.Range.second-1);
1714   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1715
1716   // Size is the number of Cases represented by this range.
1717   unsigned Size = CR.Range.second - CR.Range.first;
1718
1719   int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1720   int64_t Last  = cast<ConstantInt>(BackCase.High)->getSExtValue();
1721   double FMetric = 0;
1722   CaseItr Pivot = CR.Range.first + Size/2;
1723
1724   // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1725   // (heuristically) allow us to emit JumpTable's later.
1726   uint64_t TSize = 0;
1727   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1728        I!=E; ++I)
1729     TSize += I->size();
1730
1731   uint64_t LSize = FrontCase.size();
1732   uint64_t RSize = TSize-LSize;
1733   DOUT << "Selecting best pivot: \n"
1734        << "First: " << First << ", Last: " << Last <<"\n"
1735        << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1736   for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1737        J!=E; ++I, ++J) {
1738     int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1739     int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1740     assert((RBegin-LEnd>=1) && "Invalid case distance");
1741     double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1742     double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1743     double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1744     // Should always split in some non-trivial place
1745     DOUT <<"=>Step\n"
1746          << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1747          << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1748          << "Metric: " << Metric << "\n"; 
1749     if (FMetric < Metric) {
1750       Pivot = J;
1751       FMetric = Metric;
1752       DOUT << "Current metric set to: " << FMetric << "\n";
1753     }
1754
1755     LSize += J->size();
1756     RSize -= J->size();
1757   }
1758   if (areJTsAllowed(TLI)) {
1759     // If our case is dense we *really* should handle it earlier!
1760     assert((FMetric > 0) && "Should handle dense range earlier!");
1761   } else {
1762     Pivot = CR.Range.first + Size/2;
1763   }
1764   
1765   CaseRange LHSR(CR.Range.first, Pivot);
1766   CaseRange RHSR(Pivot, CR.Range.second);
1767   Constant *C = Pivot->Low;
1768   MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1769       
1770   // We know that we branch to the LHS if the Value being switched on is
1771   // less than the Pivot value, C.  We use this to optimize our binary 
1772   // tree a bit, by recognizing that if SV is greater than or equal to the
1773   // LHS's Case Value, and that Case Value is exactly one less than the 
1774   // Pivot's Value, then we can branch directly to the LHS's Target,
1775   // rather than creating a leaf node for it.
1776   if ((LHSR.second - LHSR.first) == 1 &&
1777       LHSR.first->High == CR.GE &&
1778       cast<ConstantInt>(C)->getSExtValue() ==
1779       (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1780     TrueBB = LHSR.first->BB;
1781   } else {
1782     TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1783     CurMF->insert(BBI, TrueBB);
1784     WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1785   }
1786   
1787   // Similar to the optimization above, if the Value being switched on is
1788   // known to be less than the Constant CR.LT, and the current Case Value
1789   // is CR.LT - 1, then we can branch directly to the target block for
1790   // the current Case Value, rather than emitting a RHS leaf node for it.
1791   if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1792       cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1793       (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1794     FalseBB = RHSR.first->BB;
1795   } else {
1796     FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1797     CurMF->insert(BBI, FalseBB);
1798     WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1799   }
1800
1801   // Create a CaseBlock record representing a conditional branch to
1802   // the LHS node if the value being switched on SV is less than C. 
1803   // Otherwise, branch to LHS.
1804   CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1805
1806   if (CR.CaseBB == CurMBB)
1807     visitSwitchCase(CB);
1808   else
1809     SwitchCases.push_back(CB);
1810
1811   return true;
1812 }
1813
1814 /// handleBitTestsSwitchCase - if current case range has few destination and
1815 /// range span less, than machine word bitwidth, encode case range into series
1816 /// of masks and emit bit tests with these masks.
1817 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1818                                                     CaseRecVector& WorkList,
1819                                                     Value* SV,
1820                                                     MachineBasicBlock* Default){
1821   unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1822
1823   Case& FrontCase = *CR.Range.first;
1824   Case& BackCase  = *(CR.Range.second-1);
1825
1826   // Get the MachineFunction which holds the current MBB.  This is used when
1827   // inserting any additional MBBs necessary to represent the switch.
1828   MachineFunction *CurMF = CurMBB->getParent();  
1829
1830   unsigned numCmps = 0;
1831   for (CaseItr I = CR.Range.first, E = CR.Range.second;
1832        I!=E; ++I) {
1833     // Single case counts one, case range - two.
1834     if (I->Low == I->High)
1835       numCmps +=1;
1836     else
1837       numCmps +=2;
1838   }
1839     
1840   // Count unique destinations
1841   SmallSet<MachineBasicBlock*, 4> Dests;
1842   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1843     Dests.insert(I->BB);
1844     if (Dests.size() > 3)
1845       // Don't bother the code below, if there are too much unique destinations
1846       return false;
1847   }
1848   DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1849        << "Total number of comparisons: " << numCmps << "\n";
1850   
1851   // Compute span of values.
1852   Constant* minValue = FrontCase.Low;
1853   Constant* maxValue = BackCase.High;
1854   uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1855                    cast<ConstantInt>(minValue)->getSExtValue();
1856   DOUT << "Compare range: " << range << "\n"
1857        << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1858        << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1859   
1860   if (range>=IntPtrBits ||
1861       (!(Dests.size() == 1 && numCmps >= 3) &&
1862        !(Dests.size() == 2 && numCmps >= 5) &&
1863        !(Dests.size() >= 3 && numCmps >= 6)))
1864     return false;
1865   
1866   DOUT << "Emitting bit tests\n";
1867   int64_t lowBound = 0;
1868     
1869   // Optimize the case where all the case values fit in a
1870   // word without having to subtract minValue. In this case,
1871   // we can optimize away the subtraction.
1872   if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1873       cast<ConstantInt>(maxValue)->getSExtValue() <  IntPtrBits) {
1874     range = cast<ConstantInt>(maxValue)->getSExtValue();
1875   } else {
1876     lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1877   }
1878     
1879   CaseBitsVector CasesBits;
1880   unsigned i, count = 0;
1881
1882   for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1883     MachineBasicBlock* Dest = I->BB;
1884     for (i = 0; i < count; ++i)
1885       if (Dest == CasesBits[i].BB)
1886         break;
1887     
1888     if (i == count) {
1889       assert((count < 3) && "Too much destinations to test!");
1890       CasesBits.push_back(CaseBits(0, Dest, 0));
1891       count++;
1892     }
1893     
1894     uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1895     uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1896     
1897     for (uint64_t j = lo; j <= hi; j++) {
1898       CasesBits[i].Mask |=  1ULL << j;
1899       CasesBits[i].Bits++;
1900     }
1901       
1902   }
1903   std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1904   
1905   BitTestInfo BTC;
1906
1907   // Figure out which block is immediately after the current one.
1908   MachineFunction::iterator BBI = CR.CaseBB;
1909   ++BBI;
1910
1911   const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1912
1913   DOUT << "Cases:\n";
1914   for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1915     DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1916          << ", BB: " << CasesBits[i].BB << "\n";
1917
1918     MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1919     CurMF->insert(BBI, CaseBB);
1920     BTC.push_back(BitTestCase(CasesBits[i].Mask,
1921                               CaseBB,
1922                               CasesBits[i].BB));
1923   }
1924   
1925   BitTestBlock BTB(lowBound, range, SV,
1926                    -1U, (CR.CaseBB == CurMBB),
1927                    CR.CaseBB, Default, BTC);
1928
1929   if (CR.CaseBB == CurMBB)
1930     visitBitTestHeader(BTB);
1931   
1932   BitTestCases.push_back(BTB);
1933
1934   return true;
1935 }
1936
1937
1938 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1939 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1940                                           const SwitchInst& SI) {
1941   unsigned numCmps = 0;
1942
1943   // Start with "simple" cases
1944   for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1945     MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1946     Cases.push_back(Case(SI.getSuccessorValue(i),
1947                          SI.getSuccessorValue(i),
1948                          SMBB));
1949   }
1950   std::sort(Cases.begin(), Cases.end(), CaseCmp());
1951
1952   // Merge case into clusters
1953   if (Cases.size()>=2)
1954     // Must recompute end() each iteration because it may be
1955     // invalidated by erase if we hold on to it
1956     for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1957       int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1958       int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1959       MachineBasicBlock* nextBB = J->BB;
1960       MachineBasicBlock* currentBB = I->BB;
1961
1962       // If the two neighboring cases go to the same destination, merge them
1963       // into a single case.
1964       if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1965         I->High = J->High;
1966         J = Cases.erase(J);
1967       } else {
1968         I = J++;
1969       }
1970     }
1971
1972   for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1973     if (I->Low != I->High)
1974       // A range counts double, since it requires two compares.
1975       ++numCmps;
1976   }
1977
1978   return numCmps;
1979 }
1980
1981 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {  
1982   // Figure out which block is immediately after the current one.
1983   MachineBasicBlock *NextBlock = 0;
1984   MachineFunction::iterator BBI = CurMBB;
1985
1986   MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1987
1988   // If there is only the default destination, branch to it if it is not the
1989   // next basic block.  Otherwise, just fall through.
1990   if (SI.getNumOperands() == 2) {
1991     // Update machine-CFG edges.
1992
1993     // If this is not a fall-through branch, emit the branch.
1994     CurMBB->addSuccessor(Default);
1995     if (Default != NextBlock)
1996       DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1997                               DAG.getBasicBlock(Default)));
1998     
1999     return;
2000   }
2001   
2002   // If there are any non-default case statements, create a vector of Cases
2003   // representing each one, and sort the vector so that we can efficiently
2004   // create a binary search tree from them.
2005   CaseVector Cases;
2006   unsigned numCmps = Clusterify(Cases, SI);
2007   DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2008        << ". Total compares: " << numCmps << "\n";
2009
2010   // Get the Value to be switched on and default basic blocks, which will be
2011   // inserted into CaseBlock records, representing basic blocks in the binary
2012   // search tree.
2013   Value *SV = SI.getOperand(0);
2014
2015   // Push the initial CaseRec onto the worklist
2016   CaseRecVector WorkList;
2017   WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2018
2019   while (!WorkList.empty()) {
2020     // Grab a record representing a case range to process off the worklist
2021     CaseRec CR = WorkList.back();
2022     WorkList.pop_back();
2023
2024     if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2025       continue;
2026     
2027     // If the range has few cases (two or less) emit a series of specific
2028     // tests.
2029     if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2030       continue;
2031     
2032     // If the switch has more than 5 blocks, and at least 40% dense, and the 
2033     // target supports indirect branches, then emit a jump table rather than 
2034     // lowering the switch to a binary tree of conditional branches.
2035     if (handleJTSwitchCase(CR, WorkList, SV, Default))
2036       continue;
2037           
2038     // Emit binary tree. We need to pick a pivot, and push left and right ranges
2039     // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2040     handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2041   }
2042 }
2043
2044
2045 void SelectionDAGLowering::visitSub(User &I) {
2046   // -0.0 - X --> fneg
2047   const Type *Ty = I.getType();
2048   if (isa<VectorType>(Ty)) {
2049     if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2050       const VectorType *DestTy = cast<VectorType>(I.getType());
2051       const Type *ElTy = DestTy->getElementType();
2052       if (ElTy->isFloatingPoint()) {
2053         unsigned VL = DestTy->getNumElements();
2054         std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2055         Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2056         if (CV == CNZ) {
2057           SDValue Op2 = getValue(I.getOperand(1));
2058           setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2059           return;
2060         }
2061       }
2062     }
2063   }
2064   if (Ty->isFloatingPoint()) {
2065     if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2066       if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2067         SDValue Op2 = getValue(I.getOperand(1));
2068         setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2069         return;
2070       }
2071   }
2072
2073   visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2074 }
2075
2076 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2077   SDValue Op1 = getValue(I.getOperand(0));
2078   SDValue Op2 = getValue(I.getOperand(1));
2079   
2080   setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2081 }
2082
2083 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2084   SDValue Op1 = getValue(I.getOperand(0));
2085   SDValue Op2 = getValue(I.getOperand(1));
2086   if (!isa<VectorType>(I.getType())) {
2087     if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2088       Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2089     else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2090       Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2091   }
2092   
2093   setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2094 }
2095
2096 void SelectionDAGLowering::visitICmp(User &I) {
2097   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2098   if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2099     predicate = IC->getPredicate();
2100   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2101     predicate = ICmpInst::Predicate(IC->getPredicate());
2102   SDValue Op1 = getValue(I.getOperand(0));
2103   SDValue Op2 = getValue(I.getOperand(1));
2104   ISD::CondCode Opcode = getICmpCondCode(predicate);
2105   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2106 }
2107
2108 void SelectionDAGLowering::visitFCmp(User &I) {
2109   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2110   if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2111     predicate = FC->getPredicate();
2112   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2113     predicate = FCmpInst::Predicate(FC->getPredicate());
2114   SDValue Op1 = getValue(I.getOperand(0));
2115   SDValue Op2 = getValue(I.getOperand(1));
2116   ISD::CondCode Condition = getFCmpCondCode(predicate);
2117   setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2118 }
2119
2120 void SelectionDAGLowering::visitVICmp(User &I) {
2121   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2122   if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2123     predicate = IC->getPredicate();
2124   else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2125     predicate = ICmpInst::Predicate(IC->getPredicate());
2126   SDValue Op1 = getValue(I.getOperand(0));
2127   SDValue Op2 = getValue(I.getOperand(1));
2128   ISD::CondCode Opcode = getICmpCondCode(predicate);
2129   setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2130 }
2131
2132 void SelectionDAGLowering::visitVFCmp(User &I) {
2133   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2134   if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2135     predicate = FC->getPredicate();
2136   else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2137     predicate = FCmpInst::Predicate(FC->getPredicate());
2138   SDValue Op1 = getValue(I.getOperand(0));
2139   SDValue Op2 = getValue(I.getOperand(1));
2140   ISD::CondCode Condition = getFCmpCondCode(predicate);
2141   MVT DestVT = TLI.getValueType(I.getType());
2142     
2143   setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2144 }
2145
2146 void SelectionDAGLowering::visitSelect(User &I) {
2147   SmallVector<MVT, 4> ValueVTs;
2148   ComputeValueVTs(TLI, I.getType(), ValueVTs);
2149   unsigned NumValues = ValueVTs.size();
2150   if (NumValues != 0) {
2151     SmallVector<SDValue, 4> Values(NumValues);
2152     SDValue Cond     = getValue(I.getOperand(0));
2153     SDValue TrueVal  = getValue(I.getOperand(1));
2154     SDValue FalseVal = getValue(I.getOperand(2));
2155
2156     for (unsigned i = 0; i != NumValues; ++i)
2157       Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2158                               SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2159                               SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2160
2161     setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2162                                     &Values[0], NumValues));
2163   }
2164 }
2165
2166
2167 void SelectionDAGLowering::visitTrunc(User &I) {
2168   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2169   SDValue N = getValue(I.getOperand(0));
2170   MVT DestVT = TLI.getValueType(I.getType());
2171   setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2172 }
2173
2174 void SelectionDAGLowering::visitZExt(User &I) {
2175   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2176   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2177   SDValue N = getValue(I.getOperand(0));
2178   MVT DestVT = TLI.getValueType(I.getType());
2179   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2180 }
2181
2182 void SelectionDAGLowering::visitSExt(User &I) {
2183   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2184   // SExt also can't be a cast to bool for same reason. So, nothing much to do
2185   SDValue N = getValue(I.getOperand(0));
2186   MVT DestVT = TLI.getValueType(I.getType());
2187   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2188 }
2189
2190 void SelectionDAGLowering::visitFPTrunc(User &I) {
2191   // FPTrunc is never a no-op cast, no need to check
2192   SDValue N = getValue(I.getOperand(0));
2193   MVT DestVT = TLI.getValueType(I.getType());
2194   setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2195 }
2196
2197 void SelectionDAGLowering::visitFPExt(User &I){ 
2198   // FPTrunc is never a no-op cast, no need to check
2199   SDValue N = getValue(I.getOperand(0));
2200   MVT DestVT = TLI.getValueType(I.getType());
2201   setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2202 }
2203
2204 void SelectionDAGLowering::visitFPToUI(User &I) { 
2205   // FPToUI is never a no-op cast, no need to check
2206   SDValue N = getValue(I.getOperand(0));
2207   MVT DestVT = TLI.getValueType(I.getType());
2208   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2209 }
2210
2211 void SelectionDAGLowering::visitFPToSI(User &I) {
2212   // FPToSI is never a no-op cast, no need to check
2213   SDValue N = getValue(I.getOperand(0));
2214   MVT DestVT = TLI.getValueType(I.getType());
2215   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2216 }
2217
2218 void SelectionDAGLowering::visitUIToFP(User &I) { 
2219   // UIToFP is never a no-op cast, no need to check
2220   SDValue N = getValue(I.getOperand(0));
2221   MVT DestVT = TLI.getValueType(I.getType());
2222   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2223 }
2224
2225 void SelectionDAGLowering::visitSIToFP(User &I){ 
2226   // SIToFP is never a no-op cast, no need to check
2227   SDValue N = getValue(I.getOperand(0));
2228   MVT DestVT = TLI.getValueType(I.getType());
2229   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2230 }
2231
2232 void SelectionDAGLowering::visitPtrToInt(User &I) {
2233   // What to do depends on the size of the integer and the size of the pointer.
2234   // We can either truncate, zero extend, or no-op, accordingly.
2235   SDValue N = getValue(I.getOperand(0));
2236   MVT SrcVT = N.getValueType();
2237   MVT DestVT = TLI.getValueType(I.getType());
2238   SDValue Result;
2239   if (DestVT.bitsLT(SrcVT))
2240     Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2241   else 
2242     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2243     Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2244   setValue(&I, Result);
2245 }
2246
2247 void SelectionDAGLowering::visitIntToPtr(User &I) {
2248   // What to do depends on the size of the integer and the size of the pointer.
2249   // We can either truncate, zero extend, or no-op, accordingly.
2250   SDValue N = getValue(I.getOperand(0));
2251   MVT SrcVT = N.getValueType();
2252   MVT DestVT = TLI.getValueType(I.getType());
2253   if (DestVT.bitsLT(SrcVT))
2254     setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2255   else 
2256     // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2257     setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2258 }
2259
2260 void SelectionDAGLowering::visitBitCast(User &I) { 
2261   SDValue N = getValue(I.getOperand(0));
2262   MVT DestVT = TLI.getValueType(I.getType());
2263
2264   // BitCast assures us that source and destination are the same size so this 
2265   // is either a BIT_CONVERT or a no-op.
2266   if (DestVT != N.getValueType())
2267     setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2268   else
2269     setValue(&I, N); // noop cast.
2270 }
2271
2272 void SelectionDAGLowering::visitInsertElement(User &I) {
2273   SDValue InVec = getValue(I.getOperand(0));
2274   SDValue InVal = getValue(I.getOperand(1));
2275   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2276                                 getValue(I.getOperand(2)));
2277
2278   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2279                            TLI.getValueType(I.getType()),
2280                            InVec, InVal, InIdx));
2281 }
2282
2283 void SelectionDAGLowering::visitExtractElement(User &I) {
2284   SDValue InVec = getValue(I.getOperand(0));
2285   SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2286                                 getValue(I.getOperand(1)));
2287   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2288                            TLI.getValueType(I.getType()), InVec, InIdx));
2289 }
2290
2291 void SelectionDAGLowering::visitShuffleVector(User &I) {
2292   SDValue V1   = getValue(I.getOperand(0));
2293   SDValue V2   = getValue(I.getOperand(1));
2294   SDValue Mask = getValue(I.getOperand(2));
2295
2296   setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2297                            TLI.getValueType(I.getType()),
2298                            V1, V2, Mask));
2299 }
2300
2301 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2302   const Value *Op0 = I.getOperand(0);
2303   const Value *Op1 = I.getOperand(1);
2304   const Type *AggTy = I.getType();
2305   const Type *ValTy = Op1->getType();
2306   bool IntoUndef = isa<UndefValue>(Op0);
2307   bool FromUndef = isa<UndefValue>(Op1);
2308
2309   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2310                                             I.idx_begin(), I.idx_end());
2311
2312   SmallVector<MVT, 4> AggValueVTs;
2313   ComputeValueVTs(TLI, AggTy, AggValueVTs);
2314   SmallVector<MVT, 4> ValValueVTs;
2315   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2316
2317   unsigned NumAggValues = AggValueVTs.size();
2318   unsigned NumValValues = ValValueVTs.size();
2319   SmallVector<SDValue, 4> Values(NumAggValues);
2320
2321   SDValue Agg = getValue(Op0);
2322   SDValue Val = getValue(Op1);
2323   unsigned i = 0;
2324   // Copy the beginning value(s) from the original aggregate.
2325   for (; i != LinearIndex; ++i)
2326     Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2327                 SDValue(Agg.getNode(), Agg.getResNo() + i);
2328   // Copy values from the inserted value(s).
2329   for (; i != LinearIndex + NumValValues; ++i)
2330     Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2331                 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2332   // Copy remaining value(s) from the original aggregate.
2333   for (; i != NumAggValues; ++i)
2334     Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2335                 SDValue(Agg.getNode(), Agg.getResNo() + i);
2336
2337   setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2338                                   &Values[0], NumAggValues));
2339 }
2340
2341 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2342   const Value *Op0 = I.getOperand(0);
2343   const Type *AggTy = Op0->getType();
2344   const Type *ValTy = I.getType();
2345   bool OutOfUndef = isa<UndefValue>(Op0);
2346
2347   unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2348                                             I.idx_begin(), I.idx_end());
2349
2350   SmallVector<MVT, 4> ValValueVTs;
2351   ComputeValueVTs(TLI, ValTy, ValValueVTs);
2352
2353   unsigned NumValValues = ValValueVTs.size();
2354   SmallVector<SDValue, 4> Values(NumValValues);
2355
2356   SDValue Agg = getValue(Op0);
2357   // Copy out the selected value(s).
2358   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2359     Values[i - LinearIndex] =
2360       OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2361                    SDValue(Agg.getNode(), Agg.getResNo() + i);
2362
2363   setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2364                                   &Values[0], NumValValues));
2365 }
2366
2367
2368 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2369   SDValue N = getValue(I.getOperand(0));
2370   const Type *Ty = I.getOperand(0)->getType();
2371
2372   for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2373        OI != E; ++OI) {
2374     Value *Idx = *OI;
2375     if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2376       unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2377       if (Field) {
2378         // N = N + Offset
2379         uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2380         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2381                         DAG.getIntPtrConstant(Offset));
2382       }
2383       Ty = StTy->getElementType(Field);
2384     } else {
2385       Ty = cast<SequentialType>(Ty)->getElementType();
2386
2387       // If this is a constant subscript, handle it quickly.
2388       if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2389         if (CI->getZExtValue() == 0) continue;
2390         uint64_t Offs = 
2391             TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2392         N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2393                         DAG.getIntPtrConstant(Offs));
2394         continue;
2395       }
2396       
2397       // N = N + Idx * ElementSize;
2398       uint64_t ElementSize = TD->getABITypeSize(Ty);
2399       SDValue IdxN = getValue(Idx);
2400
2401       // If the index is smaller or larger than intptr_t, truncate or extend
2402       // it.
2403       if (IdxN.getValueType().bitsLT(N.getValueType()))
2404         IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2405       else if (IdxN.getValueType().bitsGT(N.getValueType()))
2406         IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2407
2408       // If this is a multiply by a power of two, turn it into a shl
2409       // immediately.  This is a very common case.
2410       if (ElementSize != 1) {
2411         if (isPowerOf2_64(ElementSize)) {
2412           unsigned Amt = Log2_64(ElementSize);
2413           IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2414                              DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2415         } else {
2416           SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2417           IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2418         }
2419       }
2420
2421       N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2422     }
2423   }
2424   setValue(&I, N);
2425 }
2426
2427 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2428   // If this is a fixed sized alloca in the entry block of the function,
2429   // allocate it statically on the stack.
2430   if (FuncInfo.StaticAllocaMap.count(&I))
2431     return;   // getValue will auto-populate this.
2432
2433   const Type *Ty = I.getAllocatedType();
2434   uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2435   unsigned Align =
2436     std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2437              I.getAlignment());
2438
2439   SDValue AllocSize = getValue(I.getArraySize());
2440   MVT IntPtr = TLI.getPointerTy();
2441   if (IntPtr.bitsLT(AllocSize.getValueType()))
2442     AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2443   else if (IntPtr.bitsGT(AllocSize.getValueType()))
2444     AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2445
2446   AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2447                           DAG.getIntPtrConstant(TySize));
2448
2449   // Handle alignment.  If the requested alignment is less than or equal to
2450   // the stack alignment, ignore it.  If the size is greater than or equal to
2451   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2452   unsigned StackAlign =
2453     TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2454   if (Align <= StackAlign)
2455     Align = 0;
2456
2457   // Round the size of the allocation up to the stack alignment size
2458   // by add SA-1 to the size.
2459   AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2460                           DAG.getIntPtrConstant(StackAlign-1));
2461   // Mask out the low bits for alignment purposes.
2462   AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2463                           DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2464
2465   SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2466   const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2467                                                     MVT::Other);
2468   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2469   setValue(&I, DSA);
2470   DAG.setRoot(DSA.getValue(1));
2471
2472   // Inform the Frame Information that we have just allocated a variable-sized
2473   // object.
2474   CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2475 }
2476
2477 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2478   const Value *SV = I.getOperand(0);
2479   SDValue Ptr = getValue(SV);
2480
2481   const Type *Ty = I.getType();
2482   bool isVolatile = I.isVolatile();
2483   unsigned Alignment = I.getAlignment();
2484
2485   SmallVector<MVT, 4> ValueVTs;
2486   SmallVector<uint64_t, 4> Offsets;
2487   ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2488   unsigned NumValues = ValueVTs.size();
2489   if (NumValues == 0)
2490     return;
2491
2492   SDValue Root;
2493   bool ConstantMemory = false;
2494   if (I.isVolatile())
2495     // Serialize volatile loads with other side effects.
2496     Root = getRoot();
2497   else if (AA->pointsToConstantMemory(SV)) {
2498     // Do not serialize (non-volatile) loads of constant memory with anything.
2499     Root = DAG.getEntryNode();
2500     ConstantMemory = true;
2501   } else {
2502     // Do not serialize non-volatile loads against each other.
2503     Root = DAG.getRoot();
2504   }
2505
2506   SmallVector<SDValue, 4> Values(NumValues);
2507   SmallVector<SDValue, 4> Chains(NumValues);
2508   MVT PtrVT = Ptr.getValueType();
2509   for (unsigned i = 0; i != NumValues; ++i) {
2510     SDValue L = DAG.getLoad(ValueVTs[i], Root,
2511                               DAG.getNode(ISD::ADD, PtrVT, Ptr,
2512                                           DAG.getConstant(Offsets[i], PtrVT)),
2513                               SV, Offsets[i],
2514                               isVolatile, Alignment);
2515     Values[i] = L;
2516     Chains[i] = L.getValue(1);
2517   }
2518   
2519   if (!ConstantMemory) {
2520     SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2521                                   &Chains[0], NumValues);
2522     if (isVolatile)
2523       DAG.setRoot(Chain);
2524     else
2525       PendingLoads.push_back(Chain);
2526   }
2527
2528   setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2529                                   &Values[0], NumValues));
2530 }
2531
2532
2533 void SelectionDAGLowering::visitStore(StoreInst &I) {
2534   Value *SrcV = I.getOperand(0);
2535   Value *PtrV = I.getOperand(1);
2536
2537   SmallVector<MVT, 4> ValueVTs;
2538   SmallVector<uint64_t, 4> Offsets;
2539   ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2540   unsigned NumValues = ValueVTs.size();
2541   if (NumValues == 0)
2542     return;
2543
2544   // Get the lowered operands. Note that we do this after
2545   // checking if NumResults is zero, because with zero results
2546   // the operands won't have values in the map.
2547   SDValue Src = getValue(SrcV);
2548   SDValue Ptr = getValue(PtrV);
2549
2550   SDValue Root = getRoot();
2551   SmallVector<SDValue, 4> Chains(NumValues);
2552   MVT PtrVT = Ptr.getValueType();
2553   bool isVolatile = I.isVolatile();
2554   unsigned Alignment = I.getAlignment();
2555   for (unsigned i = 0; i != NumValues; ++i)
2556     Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2557                              DAG.getNode(ISD::ADD, PtrVT, Ptr,
2558                                          DAG.getConstant(Offsets[i], PtrVT)),
2559                              PtrV, Offsets[i],
2560                              isVolatile, Alignment);
2561
2562   DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2563 }
2564
2565 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2566 /// node.
2567 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I, 
2568                                                 unsigned Intrinsic) {
2569   bool HasChain = !I.doesNotAccessMemory();
2570   bool OnlyLoad = HasChain && I.onlyReadsMemory();
2571
2572   // Build the operand list.
2573   SmallVector<SDValue, 8> Ops;
2574   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
2575     if (OnlyLoad) {
2576       // We don't need to serialize loads against other loads.
2577       Ops.push_back(DAG.getRoot());
2578     } else { 
2579       Ops.push_back(getRoot());
2580     }
2581   }
2582
2583   // Info is set by getTgtMemInstrinsic
2584   TargetLowering::IntrinsicInfo Info;
2585   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2586
2587   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.  
2588   if (!IsTgtIntrinsic)
2589     Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2590
2591   // Add all operands of the call to the operand list.
2592   for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2593     SDValue Op = getValue(I.getOperand(i));
2594     assert(TLI.isTypeLegal(Op.getValueType()) &&
2595            "Intrinsic uses a non-legal type?");
2596     Ops.push_back(Op);
2597   }
2598
2599   std::vector<MVT> VTs;
2600   if (I.getType() != Type::VoidTy) {
2601     MVT VT = TLI.getValueType(I.getType());
2602     if (VT.isVector()) {
2603       const VectorType *DestTy = cast<VectorType>(I.getType());
2604       MVT EltVT = TLI.getValueType(DestTy->getElementType());
2605       
2606       VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2607       assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2608     }
2609     
2610     assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2611     VTs.push_back(VT);
2612   }
2613   if (HasChain)
2614     VTs.push_back(MVT::Other);
2615
2616   const MVT *VTList = DAG.getNodeValueTypes(VTs);
2617
2618   // Create the node.
2619   SDValue Result;
2620   if (IsTgtIntrinsic) {
2621     // This is target intrinsic that touches memory
2622     Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2623                                      &Ops[0], Ops.size(),
2624                                      Info.memVT, Info.ptrVal, Info.offset,
2625                                      Info.align, Info.vol,
2626                                      Info.readMem, Info.writeMem);
2627   }
2628   else if (!HasChain)
2629     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2630                          &Ops[0], Ops.size());
2631   else if (I.getType() != Type::VoidTy)
2632     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2633                          &Ops[0], Ops.size());
2634   else
2635     Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2636                          &Ops[0], Ops.size());
2637
2638   if (HasChain) {
2639     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2640     if (OnlyLoad)
2641       PendingLoads.push_back(Chain);
2642     else
2643       DAG.setRoot(Chain);
2644   }
2645   if (I.getType() != Type::VoidTy) {
2646     if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2647       MVT VT = TLI.getValueType(PTy);
2648       Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2649     } 
2650     setValue(&I, Result);
2651   }
2652 }
2653
2654 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2655 static GlobalVariable *ExtractTypeInfo(Value *V) {
2656   V = V->stripPointerCasts();
2657   GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2658   assert ((GV || isa<ConstantPointerNull>(V)) &&
2659           "TypeInfo must be a global variable or NULL");
2660   return GV;
2661 }
2662
2663 namespace llvm {
2664
2665 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2666 /// call, and add them to the specified machine basic block.
2667 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2668                   MachineBasicBlock *MBB) {
2669   // Inform the MachineModuleInfo of the personality for this landing pad.
2670   ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2671   assert(CE->getOpcode() == Instruction::BitCast &&
2672          isa<Function>(CE->getOperand(0)) &&
2673          "Personality should be a function");
2674   MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2675
2676   // Gather all the type infos for this landing pad and pass them along to
2677   // MachineModuleInfo.
2678   std::vector<GlobalVariable *> TyInfo;
2679   unsigned N = I.getNumOperands();
2680
2681   for (unsigned i = N - 1; i > 2; --i) {
2682     if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2683       unsigned FilterLength = CI->getZExtValue();
2684       unsigned FirstCatch = i + FilterLength + !FilterLength;
2685       assert (FirstCatch <= N && "Invalid filter length");
2686
2687       if (FirstCatch < N) {
2688         TyInfo.reserve(N - FirstCatch);
2689         for (unsigned j = FirstCatch; j < N; ++j)
2690           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2691         MMI->addCatchTypeInfo(MBB, TyInfo);
2692         TyInfo.clear();
2693       }
2694
2695       if (!FilterLength) {
2696         // Cleanup.
2697         MMI->addCleanup(MBB);
2698       } else {
2699         // Filter.
2700         TyInfo.reserve(FilterLength - 1);
2701         for (unsigned j = i + 1; j < FirstCatch; ++j)
2702           TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2703         MMI->addFilterTypeInfo(MBB, TyInfo);
2704         TyInfo.clear();
2705       }
2706
2707       N = i;
2708     }
2709   }
2710
2711   if (N > 3) {
2712     TyInfo.reserve(N - 3);
2713     for (unsigned j = 3; j < N; ++j)
2714       TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2715     MMI->addCatchTypeInfo(MBB, TyInfo);
2716   }
2717 }
2718
2719 }
2720
2721 /// GetSignificand - Get the significand and build it into a floating-point
2722 /// number with exponent of 1:
2723 ///
2724 ///   Op = (Op & 0x007fffff) | 0x3f800000;
2725 ///
2726 /// where Op is the hexidecimal representation of floating point value.
2727 static SDValue
2728 GetSignificand(SelectionDAG &DAG, SDValue Op) {
2729     SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2730                              DAG.getConstant(0x007fffff, MVT::i32));
2731     SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2732                              DAG.getConstant(0x3f800000, MVT::i32));
2733     return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2734 }
2735
2736 /// GetExponent - Get the exponent:
2737 ///
2738 ///   (float)((Op1 >> 23) - 127);
2739 ///
2740 /// where Op is the hexidecimal representation of floating point value.
2741 static SDValue
2742 GetExponent(SelectionDAG &DAG, SDValue Op) {
2743     SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
2744                              DAG.getConstant(23, MVT::i32));
2745     SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2746                              DAG.getConstant(127, MVT::i32));
2747     return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
2748 }
2749
2750 /// getF32Constant - Get 32-bit floating point constant.
2751 static SDValue
2752 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2753   return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2754 }
2755
2756 /// Inlined utility function to implement binary input atomic intrinsics for 
2757 /// visitIntrinsicCall: I is a call instruction
2758 ///                     Op is the associated NodeType for I
2759 const char *
2760 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2761   SDValue Root = getRoot();   
2762   SDValue L = DAG.getAtomic(Op, Root, 
2763                               getValue(I.getOperand(1)), 
2764                               getValue(I.getOperand(2)),
2765                               I.getOperand(1));
2766   setValue(&I, L);
2767   DAG.setRoot(L.getValue(1));
2768   return 0;
2769 }
2770
2771 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2772 /// limited-precision mode.
2773 void
2774 SelectionDAGLowering::visitExp(CallInst &I) {
2775   SDValue result;
2776
2777   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2778       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2779     SDValue Op = getValue(I.getOperand(1));
2780
2781     // Put the exponent in the right bit position for later addition to the
2782     // final result:
2783     //
2784     //   #define LOG2OFe 1.4426950f
2785     //   IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2786     SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
2787                              getF32Constant(DAG, 0x3fb8aa3b));
2788     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
2789
2790     //   FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2791     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
2792     SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
2793
2794     //   IntegerPartOfX <<= 23;
2795     IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
2796                                  DAG.getConstant(23, MVT::i32));
2797
2798     if (LimitFloatPrecision <= 6) {
2799       // For floating-point precision of 6:
2800       //
2801       //   TwoToFractionalPartOfX =
2802       //     0.997535578f +
2803       //       (0.735607626f + 0.252464424f * x) * x;
2804       //
2805       // error 0.0144103317, which is 6 bits
2806       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2807                                getF32Constant(DAG, 0x3e814304));
2808       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2809                                getF32Constant(DAG, 0x3f3c50c8));
2810       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2811       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2812                                getF32Constant(DAG, 0x3f7f5e7e));
2813       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
2814
2815       // Add the exponent into the result in integer domain.
2816       SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
2817                                TwoToFracPartOfX, IntegerPartOfX);
2818
2819       result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
2820     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2821       // For floating-point precision of 12:
2822       //
2823       //   TwoToFractionalPartOfX =
2824       //     0.999892986f +
2825       //       (0.696457318f +
2826       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
2827       //
2828       // 0.000107046256 error, which is 13 to 14 bits
2829       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2830                                getF32Constant(DAG, 0x3da235e3));
2831       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2832                                getF32Constant(DAG, 0x3e65b8f3));
2833       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2834       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2835                                getF32Constant(DAG, 0x3f324b07));
2836       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2837       SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
2838                                getF32Constant(DAG, 0x3f7ff8fd));
2839       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
2840
2841       // Add the exponent into the result in integer domain.
2842       SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
2843                                TwoToFracPartOfX, IntegerPartOfX);
2844
2845       result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
2846     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2847       // For floating-point precision of 18:
2848       //
2849       //   TwoToFractionalPartOfX =
2850       //     0.999999982f +
2851       //       (0.693148872f +
2852       //         (0.240227044f +
2853       //           (0.554906021e-1f +
2854       //             (0.961591928e-2f +
2855       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
2856       //
2857       // error 2.47208000*10^(-7), which is better than 18 bits
2858       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2859                                getF32Constant(DAG, 0x3924b03e));
2860       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2861                                getF32Constant(DAG, 0x3ab24b87));
2862       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2863       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2864                                getF32Constant(DAG, 0x3c1d8c17));
2865       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2866       SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
2867                                getF32Constant(DAG, 0x3d634a1d));
2868       SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2869       SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
2870                                getF32Constant(DAG, 0x3e75fe14));
2871       SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2872       SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
2873                                 getF32Constant(DAG, 0x3f317234));
2874       SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
2875       SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
2876                                 getF32Constant(DAG, 0x3f800000));
2877       SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
2878
2879       // Add the exponent into the result in integer domain.
2880       SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
2881                                 TwoToFracPartOfX, IntegerPartOfX);
2882
2883       result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
2884     }
2885   } else {
2886     // No special expansion.
2887     result = DAG.getNode(ISD::FEXP,
2888                          getValue(I.getOperand(1)).getValueType(),
2889                          getValue(I.getOperand(1)));
2890   }
2891
2892   setValue(&I, result);
2893 }
2894
2895 /// visitLog - Lower a log intrinsic. Handles the special sequences for
2896 /// limited-precision mode.
2897 void
2898 SelectionDAGLowering::visitLog(CallInst &I) {
2899   SDValue result;
2900
2901   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2902       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2903     SDValue Op = getValue(I.getOperand(1));
2904     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2905
2906     // Scale the exponent by log(2) [0.69314718f].
2907     SDValue Exp = GetExponent(DAG, Op1);
2908     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
2909                                         getF32Constant(DAG, 0x3f317218));
2910
2911     // Get the significand and build it into a floating-point number with
2912     // exponent of 1.
2913     SDValue X = GetSignificand(DAG, Op1);
2914
2915     if (LimitFloatPrecision <= 6) {
2916       // For floating-point precision of 6:
2917       //
2918       //   LogofMantissa =
2919       //     -1.1609546f +
2920       //       (1.4034025f - 0.23903021f * x) * x;
2921       // 
2922       // error 0.0034276066, which is better than 8 bits
2923       SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2924                                getF32Constant(DAG, 0xbe74c456));
2925       SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2926                                getF32Constant(DAG, 0x3fb3a2b1));
2927       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2928       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2929                                           getF32Constant(DAG, 0x3f949a29));
2930
2931       result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2932     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2933       // For floating-point precision of 12:
2934       //
2935       //   LogOfMantissa =
2936       //     -1.7417939f +
2937       //       (2.8212026f +
2938       //         (-1.4699568f +
2939       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
2940       //
2941       // error 0.000061011436, which is 14 bits
2942       SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2943                                getF32Constant(DAG, 0xbd67b6d6));
2944       SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2945                                getF32Constant(DAG, 0x3ee4f4b8));
2946       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2947       SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2948                                getF32Constant(DAG, 0x3fbc278b));
2949       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2950       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2951                                getF32Constant(DAG, 0x40348e95));
2952       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2953       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
2954                                           getF32Constant(DAG, 0x3fdef31a));
2955
2956       result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2957     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2958       // For floating-point precision of 18:
2959       //
2960       //   LogOfMantissa =
2961       //     -2.1072184f +
2962       //       (4.2372794f +
2963       //         (-3.7029485f +
2964       //           (2.2781945f +
2965       //             (-0.87823314f +
2966       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
2967       //
2968       // error 0.0000023660568, which is better than 18 bits
2969       SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2970                                getF32Constant(DAG, 0xbc91e5ac));
2971       SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2972                                getF32Constant(DAG, 0x3e4350aa));
2973       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2974       SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2975                                getF32Constant(DAG, 0x3f60d3e3));
2976       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2977       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2978                                getF32Constant(DAG, 0x4011cdf0));
2979       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2980       SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
2981                                getF32Constant(DAG, 0x406cfd1c));
2982       SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2983       SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
2984                                getF32Constant(DAG, 0x408797cb));
2985       SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2986       SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
2987                                           getF32Constant(DAG, 0x4006dcab));
2988
2989       result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2990     }
2991   } else {
2992     // No special expansion.
2993     result = DAG.getNode(ISD::FLOG,
2994                          getValue(I.getOperand(1)).getValueType(),
2995                          getValue(I.getOperand(1)));
2996   }
2997
2998   setValue(&I, result);
2999 }
3000
3001 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3002 /// limited-precision mode.
3003 void
3004 SelectionDAGLowering::visitLog2(CallInst &I) {
3005   SDValue result;
3006
3007   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3008       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3009     SDValue Op = getValue(I.getOperand(1));
3010     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3011
3012     // Get the exponent.
3013     SDValue LogOfExponent = GetExponent(DAG, Op1);
3014
3015     // Get the significand and build it into a floating-point number with
3016     // exponent of 1.
3017     SDValue X = GetSignificand(DAG, Op1);
3018     
3019     // Different possible minimax approximations of significand in
3020     // floating-point for various degrees of accuracy over [1,2].
3021     if (LimitFloatPrecision <= 6) {
3022       // For floating-point precision of 6:
3023       //
3024       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3025       //
3026       // error 0.0049451742, which is more than 7 bits
3027       SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3028                                getF32Constant(DAG, 0xbeb08fe0));
3029       SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3030                                getF32Constant(DAG, 0x40019463));
3031       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3032       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3033                                            getF32Constant(DAG, 0x3fd6633d));
3034
3035       result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3036     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3037       // For floating-point precision of 12:
3038       //
3039       //   Log2ofMantissa =
3040       //     -2.51285454f +
3041       //       (4.07009056f +
3042       //         (-2.12067489f +
3043       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3044       //   
3045       // error 0.0000876136000, which is better than 13 bits
3046       SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3047                                getF32Constant(DAG, 0xbda7262e));
3048       SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3049                                getF32Constant(DAG, 0x3f25280b));
3050       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3051       SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3052                                getF32Constant(DAG, 0x4007b923));
3053       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3054       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3055                                getF32Constant(DAG, 0x40823e2f));
3056       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3057       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3058                                            getF32Constant(DAG, 0x4020d29c));
3059
3060       result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3061     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3062       // For floating-point precision of 18:
3063       //
3064       //   Log2ofMantissa =
3065       //     -3.0400495f +
3066       //       (6.1129976f +
3067       //         (-5.3420409f +
3068       //           (3.2865683f +
3069       //             (-1.2669343f +
3070       //               (0.27515199f -
3071       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3072       //
3073       // error 0.0000018516, which is better than 18 bits
3074       SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3075                                getF32Constant(DAG, 0xbcd2769e));
3076       SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3077                                getF32Constant(DAG, 0x3e8ce0b9));
3078       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3079       SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3080                                getF32Constant(DAG, 0x3fa22ae7));
3081       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3082       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3083                                getF32Constant(DAG, 0x40525723));
3084       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3085       SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3086                                getF32Constant(DAG, 0x40aaf200));
3087       SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3088       SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3089                                getF32Constant(DAG, 0x40c39dad));
3090       SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3091       SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3092                                            getF32Constant(DAG, 0x4042902c));
3093
3094       result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3095     }
3096   } else {
3097     // No special expansion.
3098     result = DAG.getNode(ISD::FLOG2,
3099                          getValue(I.getOperand(1)).getValueType(),
3100                          getValue(I.getOperand(1)));
3101   }
3102
3103   setValue(&I, result);
3104 }
3105
3106 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3107 /// limited-precision mode.
3108 void
3109 SelectionDAGLowering::visitLog10(CallInst &I) {
3110   SDValue result;
3111
3112   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3113       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3114     SDValue Op = getValue(I.getOperand(1));
3115     SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3116
3117     // Scale the exponent by log10(2) [0.30102999f].
3118     SDValue Exp = GetExponent(DAG, Op1);
3119     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
3120                                         getF32Constant(DAG, 0x3e9a209a));
3121
3122     // Get the significand and build it into a floating-point number with
3123     // exponent of 1.
3124     SDValue X = GetSignificand(DAG, Op1);
3125
3126     if (LimitFloatPrecision <= 6) {
3127       // For floating-point precision of 6:
3128       // 
3129       //   Log10ofMantissa =
3130       //     -0.50419619f +
3131       //       (0.60948995f - 0.10380950f * x) * x;
3132       //
3133       // error 0.0014886165, which is 6 bits
3134       SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3135                                getF32Constant(DAG, 0xbdd49a13));
3136       SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3137                                getF32Constant(DAG, 0x3f1c0789));
3138       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3139       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3140                                             getF32Constant(DAG, 0x3f011300));
3141
3142       result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3143     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3144       // For floating-point precision of 12:
3145       //
3146       //   Log10ofMantissa =
3147       //     -0.64831180f +
3148       //       (0.91751397f +
3149       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3150       //
3151       // error 0.00019228036, which is better than 12 bits
3152       SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3153                                getF32Constant(DAG, 0x3d431f31));
3154       SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3155                                getF32Constant(DAG, 0x3ea21fb2));
3156       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3157       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3158                                getF32Constant(DAG, 0x3f6ae232));
3159       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3160       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3161                                             getF32Constant(DAG, 0x3f25f7c3));
3162
3163       result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3164     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3165       // For floating-point precision of 18:
3166       //
3167       //   Log10ofMantissa =
3168       //     -0.84299375f +
3169       //       (1.5327582f +
3170       //         (-1.0688956f +
3171       //           (0.49102474f +
3172       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3173       //
3174       // error 0.0000037995730, which is better than 18 bits
3175       SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3176                                getF32Constant(DAG, 0x3c5d51ce));
3177       SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3178                                getF32Constant(DAG, 0x3e00685a));
3179       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3180       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3181                                getF32Constant(DAG, 0x3efb6798));
3182       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3183       SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3184                                getF32Constant(DAG, 0x3f88d192));
3185       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3186       SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3187                                getF32Constant(DAG, 0x3fc4316c));
3188       SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3189       SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
3190                                             getF32Constant(DAG, 0x3f57ce70));
3191
3192       result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3193     }
3194   } else {
3195     // No special expansion.
3196     result = DAG.getNode(ISD::FLOG10,
3197                          getValue(I.getOperand(1)).getValueType(),
3198                          getValue(I.getOperand(1)));
3199   }
3200
3201   setValue(&I, result);
3202 }
3203
3204 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3205 /// limited-precision mode.
3206 void
3207 SelectionDAGLowering::visitExp2(CallInst &I) {
3208   SDValue result;
3209
3210   if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3211       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3212     SDValue Op = getValue(I.getOperand(1));
3213
3214     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3215
3216     //   FractionalPartOfX = x - (float)IntegerPartOfX;
3217     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3218     SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3219
3220     //   IntegerPartOfX <<= 23;
3221     IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3222                                  DAG.getConstant(23, MVT::i32));
3223
3224     if (LimitFloatPrecision <= 6) {
3225       // For floating-point precision of 6:
3226       // 
3227       //   TwoToFractionalPartOfX =
3228       //     0.997535578f +
3229       //       (0.735607626f + 0.252464424f * x) * x;
3230       //
3231       // error 0.0144103317, which is 6 bits
3232       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3233                                getF32Constant(DAG, 0x3e814304));
3234       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3235                                getF32Constant(DAG, 0x3f3c50c8));
3236       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3237       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4, 
3238                                getF32Constant(DAG, 0x3f7f5e7e));
3239       SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3240       SDValue TwoToFractionalPartOfX =
3241         DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3242
3243       result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3244     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3245       // For floating-point precision of 12:
3246       //
3247       //   TwoToFractionalPartOfX =
3248       //     0.999892986f +
3249       //       (0.696457318f +
3250       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3251       //
3252       // error 0.000107046256, which is 13 to 14 bits
3253       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3254                                getF32Constant(DAG, 0x3da235e3));
3255       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3256                                getF32Constant(DAG, 0x3e65b8f3));
3257       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3258       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4, 
3259                                getF32Constant(DAG, 0x3f324b07));
3260       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3261       SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3262                                getF32Constant(DAG, 0x3f7ff8fd));
3263       SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3264       SDValue TwoToFractionalPartOfX =
3265         DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3266
3267       result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3268     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3269       // For floating-point precision of 18:
3270       //
3271       //   TwoToFractionalPartOfX =
3272       //     0.999999982f +
3273       //       (0.693148872f +
3274       //         (0.240227044f +
3275       //           (0.554906021e-1f +
3276       //             (0.961591928e-2f +
3277       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3278       // error 2.47208000*10^(-7), which is better than 18 bits
3279       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3280                                getF32Constant(DAG, 0x3924b03e));
3281       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3282                                getF32Constant(DAG, 0x3ab24b87));
3283       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3284       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4, 
3285                                getF32Constant(DAG, 0x3c1d8c17));
3286       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3287       SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3288                                getF32Constant(DAG, 0x3d634a1d));
3289       SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3290       SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3291                                getF32Constant(DAG, 0x3e75fe14));
3292       SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3293       SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3294                                 getF32Constant(DAG, 0x3f317234));
3295       SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3296       SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3297                                 getF32Constant(DAG, 0x3f800000));
3298       SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3299       SDValue TwoToFractionalPartOfX =
3300         DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3301
3302       result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3303     }
3304   } else {
3305     // No special expansion.
3306     result = DAG.getNode(ISD::FEXP2,
3307                          getValue(I.getOperand(1)).getValueType(),
3308                          getValue(I.getOperand(1)));
3309   }
3310
3311   setValue(&I, result);
3312 }
3313
3314 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3315 /// limited-precision mode with x == 10.0f.
3316 void
3317 SelectionDAGLowering::visitPow(CallInst &I) {
3318   SDValue result;
3319   Value *Val = I.getOperand(1);
3320   bool IsExp10 = false;
3321
3322   if (getValue(Val).getValueType() == MVT::f32 &&
3323       getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3324       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3325     if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3326       if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3327         APFloat Ten(10.0f);
3328         IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3329       }
3330     }
3331   }
3332
3333   if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3334     SDValue Op = getValue(I.getOperand(2));
3335
3336     // Put the exponent in the right bit position for later addition to the
3337     // final result:
3338     //
3339     //   #define LOG2OF10 3.3219281f
3340     //   IntegerPartOfX = (int32_t)(x * LOG2OF10);
3341     SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
3342                              getF32Constant(DAG, 0x40549a78));
3343     SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3344
3345     //   FractionalPartOfX = x - (float)IntegerPartOfX;
3346     SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3347     SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3348
3349     //   IntegerPartOfX <<= 23;
3350     IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3351                                  DAG.getConstant(23, MVT::i32));
3352
3353     if (LimitFloatPrecision <= 6) {
3354       // For floating-point precision of 6:
3355       // 
3356       //   twoToFractionalPartOfX =
3357       //     0.997535578f +
3358       //       (0.735607626f + 0.252464424f * x) * x;
3359       // 
3360       // error 0.0144103317, which is 6 bits
3361       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3362                                getF32Constant(DAG, 0x3e814304));
3363       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3364                                getF32Constant(DAG, 0x3f3c50c8));
3365       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3366       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4, 
3367                                getF32Constant(DAG, 0x3f7f5e7e));
3368       SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3369       SDValue TwoToFractionalPartOfX =
3370         DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3371
3372       result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3373     } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3374       // For floating-point precision of 12:
3375       //
3376       //   TwoToFractionalPartOfX =
3377       //     0.999892986f +
3378       //       (0.696457318f +
3379       //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
3380       //
3381       // error 0.000107046256, which is 13 to 14 bits
3382       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3383                                getF32Constant(DAG, 0x3da235e3));
3384       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3385                                getF32Constant(DAG, 0x3e65b8f3));
3386       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3387       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4, 
3388                                getF32Constant(DAG, 0x3f324b07));
3389       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3390       SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3391                                getF32Constant(DAG, 0x3f7ff8fd));
3392       SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3393       SDValue TwoToFractionalPartOfX =
3394         DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3395
3396       result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3397     } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3398       // For floating-point precision of 18:
3399       //
3400       //   TwoToFractionalPartOfX =
3401       //     0.999999982f +
3402       //       (0.693148872f +
3403       //         (0.240227044f +
3404       //           (0.554906021e-1f +
3405       //             (0.961591928e-2f +
3406       //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3407       // error 2.47208000*10^(-7), which is better than 18 bits
3408       SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3409                                getF32Constant(DAG, 0x3924b03e));
3410       SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3411                                getF32Constant(DAG, 0x3ab24b87));
3412       SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3413       SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4, 
3414                                getF32Constant(DAG, 0x3c1d8c17));
3415       SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3416       SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3417                                getF32Constant(DAG, 0x3d634a1d));
3418       SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3419       SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3420                                getF32Constant(DAG, 0x3e75fe14));
3421       SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3422       SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3423                                 getF32Constant(DAG, 0x3f317234));
3424       SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3425       SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3426                                 getF32Constant(DAG, 0x3f800000));
3427       SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3428       SDValue TwoToFractionalPartOfX =
3429         DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3430
3431       result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3432     }
3433   } else {
3434     // No special expansion.
3435     result = DAG.getNode(ISD::FPOW,
3436                          getValue(I.getOperand(1)).getValueType(),
3437                          getValue(I.getOperand(1)),
3438                          getValue(I.getOperand(2)));
3439   }
3440
3441   setValue(&I, result);
3442 }
3443
3444 /// visitIntrinsicCall - Lower the call to the specified intrinsic function.  If
3445 /// we want to emit this as a call to a named external function, return the name
3446 /// otherwise lower it and return null.
3447 const char *
3448 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3449   switch (Intrinsic) {
3450   default:
3451     // By default, turn this into a target intrinsic node.
3452     visitTargetIntrinsic(I, Intrinsic);
3453     return 0;
3454   case Intrinsic::vastart:  visitVAStart(I); return 0;
3455   case Intrinsic::vaend:    visitVAEnd(I); return 0;
3456   case Intrinsic::vacopy:   visitVACopy(I); return 0;
3457   case Intrinsic::returnaddress:
3458     setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3459                              getValue(I.getOperand(1))));
3460     return 0;
3461   case Intrinsic::frameaddress:
3462     setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3463                              getValue(I.getOperand(1))));
3464     return 0;
3465   case Intrinsic::setjmp:
3466     return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3467     break;
3468   case Intrinsic::longjmp:
3469     return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3470     break;
3471   case Intrinsic::memcpy_i32:
3472   case Intrinsic::memcpy_i64: {
3473     SDValue Op1 = getValue(I.getOperand(1));
3474     SDValue Op2 = getValue(I.getOperand(2));
3475     SDValue Op3 = getValue(I.getOperand(3));
3476     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3477     DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3478                               I.getOperand(1), 0, I.getOperand(2), 0));
3479     return 0;
3480   }
3481   case Intrinsic::memset_i32:
3482   case Intrinsic::memset_i64: {
3483     SDValue Op1 = getValue(I.getOperand(1));
3484     SDValue Op2 = getValue(I.getOperand(2));
3485     SDValue Op3 = getValue(I.getOperand(3));
3486     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3487     DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3488                               I.getOperand(1), 0));
3489     return 0;
3490   }
3491   case Intrinsic::memmove_i32:
3492   case Intrinsic::memmove_i64: {
3493     SDValue Op1 = getValue(I.getOperand(1));
3494     SDValue Op2 = getValue(I.getOperand(2));
3495     SDValue Op3 = getValue(I.getOperand(3));
3496     unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3497
3498     // If the source and destination are known to not be aliases, we can
3499     // lower memmove as memcpy.
3500     uint64_t Size = -1ULL;
3501     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3502       Size = C->getZExtValue();
3503     if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3504         AliasAnalysis::NoAlias) {
3505       DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3506                                 I.getOperand(1), 0, I.getOperand(2), 0));
3507       return 0;
3508     }
3509
3510     DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3511                                I.getOperand(1), 0, I.getOperand(2), 0));
3512     return 0;
3513   }
3514   case Intrinsic::dbg_stoppoint: {
3515     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3516     DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3517     if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3518       DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3519       assert(DD && "Not a debug information descriptor");
3520       DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3521                                       SPI.getLine(),
3522                                       SPI.getColumn(),
3523                                       cast<CompileUnitDesc>(DD)));
3524     }
3525
3526     return 0;
3527   }
3528   case Intrinsic::dbg_region_start: {
3529     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3530     DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3531     if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3532       unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3533       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3534     }
3535
3536     return 0;
3537   }
3538   case Intrinsic::dbg_region_end: {
3539     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3540     DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3541     if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3542       unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3543       DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3544     }
3545
3546     return 0;
3547   }
3548   case Intrinsic::dbg_func_start: {
3549     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3550     if (!MMI) return 0;
3551     DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3552     Value *SP = FSI.getSubprogram();
3553     if (SP && MMI->Verify(SP)) {
3554       // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3555       // what (most?) gdb expects.
3556       DebugInfoDesc *DD = MMI->getDescFor(SP);
3557       assert(DD && "Not a debug information descriptor");
3558       SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3559       const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3560       unsigned SrcFile = MMI->RecordSource(CompileUnit);
3561       // Record the source line but does not create a label for the normal
3562       // function start. It will be emitted at asm emission time. However,
3563       // create a label if this is a beginning of inlined function.
3564       unsigned LabelID = MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3565       if (MMI->getSourceLines().size() != 1)
3566         DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3567     }
3568
3569     return 0;
3570   }
3571   case Intrinsic::dbg_declare: {
3572     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3573     DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3574     Value *Variable = DI.getVariable();
3575     if (MMI && Variable && MMI->Verify(Variable))
3576       DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3577                               getValue(DI.getAddress()), getValue(Variable)));
3578     return 0;
3579   }
3580     
3581   case Intrinsic::eh_exception: {
3582     if (!CurMBB->isLandingPad()) {
3583       // FIXME: Mark exception register as live in.  Hack for PR1508.
3584       unsigned Reg = TLI.getExceptionAddressRegister();
3585       if (Reg) CurMBB->addLiveIn(Reg);
3586     }
3587     // Insert the EXCEPTIONADDR instruction.
3588     SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3589     SDValue Ops[1];
3590     Ops[0] = DAG.getRoot();
3591     SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3592     setValue(&I, Op);
3593     DAG.setRoot(Op.getValue(1));
3594     return 0;
3595   }
3596
3597   case Intrinsic::eh_selector_i32:
3598   case Intrinsic::eh_selector_i64: {
3599     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3600     MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3601                          MVT::i32 : MVT::i64);
3602     
3603     if (MMI) {
3604       if (CurMBB->isLandingPad())
3605         AddCatchInfo(I, MMI, CurMBB);
3606       else {
3607 #ifndef NDEBUG
3608         FuncInfo.CatchInfoLost.insert(&I);
3609 #endif
3610         // FIXME: Mark exception selector register as live in.  Hack for PR1508.
3611         unsigned Reg = TLI.getExceptionSelectorRegister();
3612         if (Reg) CurMBB->addLiveIn(Reg);
3613       }
3614
3615       // Insert the EHSELECTION instruction.
3616       SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3617       SDValue Ops[2];
3618       Ops[0] = getValue(I.getOperand(1));
3619       Ops[1] = getRoot();
3620       SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3621       setValue(&I, Op);
3622       DAG.setRoot(Op.getValue(1));
3623     } else {
3624       setValue(&I, DAG.getConstant(0, VT));
3625     }
3626     
3627     return 0;
3628   }
3629
3630   case Intrinsic::eh_typeid_for_i32:
3631   case Intrinsic::eh_typeid_for_i64: {
3632     MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3633     MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3634                          MVT::i32 : MVT::i64);
3635
3636     if (MMI) {
3637       // Find the type id for the given typeinfo.
3638       GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3639
3640       unsigned TypeID = MMI->getTypeIDFor(GV);
3641       setValue(&I, DAG.getConstant(TypeID, VT));
3642     } else {
3643       // Return something different to eh_selector.
3644       setValue(&I, DAG.getConstant(1, VT));
3645     }
3646
3647     return 0;
3648   }
3649
3650   case Intrinsic::eh_return_i32:
3651   case Intrinsic::eh_return_i64:
3652     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3653       MMI->setCallsEHReturn(true);
3654       DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3655                               MVT::Other,
3656                               getControlRoot(),
3657                               getValue(I.getOperand(1)),
3658                               getValue(I.getOperand(2))));
3659     } else {
3660       setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3661     }
3662
3663     return 0;
3664   case Intrinsic::eh_unwind_init:
3665     if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3666       MMI->setCallsUnwindInit(true);
3667     }
3668
3669     return 0;
3670
3671   case Intrinsic::eh_dwarf_cfa: {
3672     MVT VT = getValue(I.getOperand(1)).getValueType();
3673     SDValue CfaArg;
3674     if (VT.bitsGT(TLI.getPointerTy()))
3675       CfaArg = DAG.getNode(ISD::TRUNCATE,
3676                            TLI.getPointerTy(), getValue(I.getOperand(1)));
3677     else
3678       CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3679                            TLI.getPointerTy(), getValue(I.getOperand(1)));
3680
3681     SDValue Offset = DAG.getNode(ISD::ADD,
3682                                  TLI.getPointerTy(),
3683                                  DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3684                                              TLI.getPointerTy()),
3685                                  CfaArg);
3686     setValue(&I, DAG.getNode(ISD::ADD,
3687                              TLI.getPointerTy(),
3688                              DAG.getNode(ISD::FRAMEADDR,
3689                                          TLI.getPointerTy(),
3690                                          DAG.getConstant(0,
3691                                                          TLI.getPointerTy())),
3692                              Offset));
3693     return 0;
3694   }
3695
3696   case Intrinsic::sqrt:
3697     setValue(&I, DAG.getNode(ISD::FSQRT,
3698                              getValue(I.getOperand(1)).getValueType(),
3699                              getValue(I.getOperand(1))));
3700     return 0;
3701   case Intrinsic::powi:
3702     setValue(&I, DAG.getNode(ISD::FPOWI,
3703                              getValue(I.getOperand(1)).getValueType(),
3704                              getValue(I.getOperand(1)),
3705                              getValue(I.getOperand(2))));
3706     return 0;
3707   case Intrinsic::sin:
3708     setValue(&I, DAG.getNode(ISD::FSIN,
3709                              getValue(I.getOperand(1)).getValueType(),
3710                              getValue(I.getOperand(1))));
3711     return 0;
3712   case Intrinsic::cos:
3713     setValue(&I, DAG.getNode(ISD::FCOS,
3714                              getValue(I.getOperand(1)).getValueType(),
3715                              getValue(I.getOperand(1))));
3716     return 0;
3717   case Intrinsic::log:
3718     visitLog(I);
3719     return 0;
3720   case Intrinsic::log2:
3721     visitLog2(I);
3722     return 0;
3723   case Intrinsic::log10:
3724     visitLog10(I);
3725     return 0;
3726   case Intrinsic::exp:
3727     visitExp(I);
3728     return 0;
3729   case Intrinsic::exp2:
3730     visitExp2(I);
3731     return 0;
3732   case Intrinsic::pow:
3733     visitPow(I);
3734     return 0;
3735   case Intrinsic::pcmarker: {
3736     SDValue Tmp = getValue(I.getOperand(1));
3737     DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3738     return 0;
3739   }
3740   case Intrinsic::readcyclecounter: {
3741     SDValue Op = getRoot();
3742     SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3743                                 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3744                                 &Op, 1);
3745     setValue(&I, Tmp);
3746     DAG.setRoot(Tmp.getValue(1));
3747     return 0;
3748   }
3749   case Intrinsic::part_select: {
3750     // Currently not implemented: just abort
3751     assert(0 && "part_select intrinsic not implemented");
3752     abort();
3753   }
3754   case Intrinsic::part_set: {
3755     // Currently not implemented: just abort
3756     assert(0 && "part_set intrinsic not implemented");
3757     abort();
3758   }
3759   case Intrinsic::bswap:
3760     setValue(&I, DAG.getNode(ISD::BSWAP,
3761                              getValue(I.getOperand(1)).getValueType(),
3762                              getValue(I.getOperand(1))));
3763     return 0;
3764   case Intrinsic::cttz: {
3765     SDValue Arg = getValue(I.getOperand(1));
3766     MVT Ty = Arg.getValueType();
3767     SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3768     setValue(&I, result);
3769     return 0;
3770   }
3771   case Intrinsic::ctlz: {
3772     SDValue Arg = getValue(I.getOperand(1));
3773     MVT Ty = Arg.getValueType();
3774     SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3775     setValue(&I, result);
3776     return 0;
3777   }
3778   case Intrinsic::ctpop: {
3779     SDValue Arg = getValue(I.getOperand(1));
3780     MVT Ty = Arg.getValueType();
3781     SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3782     setValue(&I, result);
3783     return 0;
3784   }
3785   case Intrinsic::stacksave: {
3786     SDValue Op = getRoot();
3787     SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3788               DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3789     setValue(&I, Tmp);
3790     DAG.setRoot(Tmp.getValue(1));
3791     return 0;
3792   }
3793   case Intrinsic::stackrestore: {
3794     SDValue Tmp = getValue(I.getOperand(1));
3795     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3796     return 0;
3797   }
3798   case Intrinsic::stackprotector_create: {
3799     // Emit code into the DAG to store the stack guard onto the stack.
3800     MachineFunction &MF = DAG.getMachineFunction();
3801     MachineFrameInfo *MFI = MF.getFrameInfo();
3802     MVT PtrTy = TLI.getPointerTy();
3803
3804     // Retrieve the stack protector guard's value.
3805     SDValue Src = getValue(I.getOperand(1));
3806
3807     // Create a slot on the stack for the stack protector. It should go first
3808     // before local variables are allocated.
3809     unsigned Align =
3810       TLI.getTargetData()->getPrefTypeAlignment(PtrTy.getTypeForMVT());
3811     int FI = MFI->CreateStackObject(PtrTy.getSizeInBits() / 8, Align);
3812     MFI->setStackProtectorIndex(FI);
3813
3814     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3815
3816     // Store the stack protector onto the stack.
3817     SDValue Result = DAG.getStore(getRoot(), Src, FIN,
3818                                   PseudoSourceValue::getFixedStack(FI),
3819                                   0, true);
3820     setValue(&I, Result);
3821     DAG.setRoot(Result);
3822     return 0;
3823   }
3824   case Intrinsic::stackprotector_check: {
3825     // Emit code into the DAG to retrieve the stack guard off of the stack.
3826     MachineFunction &MF = DAG.getMachineFunction();
3827     MachineFrameInfo *MFI = MF.getFrameInfo();
3828     MVT PtrTy = TLI.getPointerTy();
3829
3830     // Load the value stored on the stack.
3831     int FI = MFI->getStackProtectorIndex();
3832     SDValue FIN = DAG.getFrameIndex(MFI->getStackProtectorIndex(), PtrTy);
3833     setValue(&I, DAG.getLoad(PtrTy, getRoot(), FIN,
3834                              PseudoSourceValue::getFixedStack(FI), 0, true));
3835     return 0;
3836   }
3837   case Intrinsic::var_annotation:
3838     // Discard annotate attributes
3839     return 0;
3840
3841   case Intrinsic::init_trampoline: {
3842     const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3843
3844     SDValue Ops[6];
3845     Ops[0] = getRoot();
3846     Ops[1] = getValue(I.getOperand(1));
3847     Ops[2] = getValue(I.getOperand(2));
3848     Ops[3] = getValue(I.getOperand(3));
3849     Ops[4] = DAG.getSrcValue(I.getOperand(1));
3850     Ops[5] = DAG.getSrcValue(F);
3851
3852     SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3853                                 DAG.getNodeValueTypes(TLI.getPointerTy(),
3854                                                       MVT::Other), 2,
3855                                 Ops, 6);
3856
3857     setValue(&I, Tmp);
3858     DAG.setRoot(Tmp.getValue(1));
3859     return 0;
3860   }
3861
3862   case Intrinsic::gcroot:
3863     if (GFI) {
3864       Value *Alloca = I.getOperand(1);
3865       Constant *TypeMap = cast<Constant>(I.getOperand(2));
3866       
3867       FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
3868       GFI->addStackRoot(FI->getIndex(), TypeMap);
3869     }
3870     return 0;
3871
3872   case Intrinsic::gcread:
3873   case Intrinsic::gcwrite:
3874     assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3875     return 0;
3876
3877   case Intrinsic::flt_rounds: {
3878     setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3879     return 0;
3880   }
3881
3882   case Intrinsic::trap: {
3883     DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3884     return 0;
3885   }
3886   case Intrinsic::prefetch: {
3887     SDValue Ops[4];
3888     Ops[0] = getRoot();
3889     Ops[1] = getValue(I.getOperand(1));
3890     Ops[2] = getValue(I.getOperand(2));
3891     Ops[3] = getValue(I.getOperand(3));
3892     DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3893     return 0;
3894   }
3895   
3896   case Intrinsic::memory_barrier: {
3897     SDValue Ops[6];
3898     Ops[0] = getRoot();
3899     for (int x = 1; x < 6; ++x)
3900       Ops[x] = getValue(I.getOperand(x));
3901
3902     DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3903     return 0;
3904   }
3905   case Intrinsic::atomic_cmp_swap: {
3906     SDValue Root = getRoot();   
3907     SDValue L;
3908     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3909       case MVT::i8:
3910         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root, 
3911                           getValue(I.getOperand(1)), 
3912                           getValue(I.getOperand(2)),
3913                           getValue(I.getOperand(3)),
3914                           I.getOperand(1));
3915         break;
3916       case MVT::i16:
3917         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root, 
3918                           getValue(I.getOperand(1)), 
3919                           getValue(I.getOperand(2)),
3920                           getValue(I.getOperand(3)),
3921                           I.getOperand(1));
3922         break;
3923       case MVT::i32:
3924         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root, 
3925                           getValue(I.getOperand(1)), 
3926                           getValue(I.getOperand(2)),
3927                           getValue(I.getOperand(3)),
3928                           I.getOperand(1));
3929         break;
3930       case MVT::i64:
3931         L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root, 
3932                           getValue(I.getOperand(1)), 
3933                           getValue(I.getOperand(2)),
3934                           getValue(I.getOperand(3)),
3935                           I.getOperand(1));
3936         break;
3937       default:
3938        assert(0 && "Invalid atomic type");
3939        abort();
3940     }
3941     setValue(&I, L);
3942     DAG.setRoot(L.getValue(1));
3943     return 0;
3944   }
3945   case Intrinsic::atomic_load_add:
3946     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3947       case MVT::i8:
3948         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3949       case MVT::i16:
3950         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3951       case MVT::i32:
3952         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3953       case MVT::i64:
3954         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3955       default:
3956        assert(0 && "Invalid atomic type");
3957        abort();
3958     }
3959   case Intrinsic::atomic_load_sub:
3960     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3961       case MVT::i8:
3962         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3963       case MVT::i16:
3964         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3965       case MVT::i32:
3966         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3967       case MVT::i64:
3968         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3969       default:
3970        assert(0 && "Invalid atomic type");
3971        abort();
3972     }
3973   case Intrinsic::atomic_load_or:
3974     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3975       case MVT::i8:
3976         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3977       case MVT::i16:
3978         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3979       case MVT::i32:
3980         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3981       case MVT::i64:
3982         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3983       default:
3984        assert(0 && "Invalid atomic type");
3985        abort();
3986     }
3987   case Intrinsic::atomic_load_xor:
3988     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3989       case MVT::i8:
3990         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3991       case MVT::i16:
3992         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3993       case MVT::i32:
3994         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3995       case MVT::i64:
3996         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3997       default:
3998        assert(0 && "Invalid atomic type");
3999        abort();
4000     }
4001   case Intrinsic::atomic_load_and:
4002     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4003       case MVT::i8:
4004         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
4005       case MVT::i16:
4006         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
4007       case MVT::i32:
4008         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
4009       case MVT::i64:
4010         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
4011       default:
4012        assert(0 && "Invalid atomic type");
4013        abort();
4014     }
4015   case Intrinsic::atomic_load_nand:
4016     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4017       case MVT::i8:
4018         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
4019       case MVT::i16:
4020         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
4021       case MVT::i32:
4022         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
4023       case MVT::i64:
4024         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
4025       default:
4026        assert(0 && "Invalid atomic type");
4027        abort();
4028     }
4029   case Intrinsic::atomic_load_max:
4030     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4031       case MVT::i8:
4032         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
4033       case MVT::i16:
4034         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
4035       case MVT::i32:
4036         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
4037       case MVT::i64:
4038         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
4039       default:
4040        assert(0 && "Invalid atomic type");
4041        abort();
4042     }
4043   case Intrinsic::atomic_load_min:
4044     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4045       case MVT::i8:
4046         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
4047       case MVT::i16:
4048         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
4049       case MVT::i32:
4050         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
4051       case MVT::i64:
4052         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
4053       default:
4054        assert(0 && "Invalid atomic type");
4055        abort();
4056     }
4057   case Intrinsic::atomic_load_umin:
4058     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4059       case MVT::i8:
4060         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
4061       case MVT::i16:
4062         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
4063       case MVT::i32:
4064         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
4065       case MVT::i64:
4066         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
4067       default:
4068        assert(0 && "Invalid atomic type");
4069        abort();
4070     }
4071   case Intrinsic::atomic_load_umax:
4072     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4073       case MVT::i8:
4074         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
4075       case MVT::i16:
4076         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
4077       case MVT::i32:
4078         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
4079       case MVT::i64:
4080         return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
4081       default:
4082        assert(0 && "Invalid atomic type");
4083        abort();
4084     }
4085   case Intrinsic::atomic_swap:
4086     switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4087       case MVT::i8:
4088         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
4089       case MVT::i16:
4090         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
4091       case MVT::i32:
4092         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
4093       case MVT::i64:
4094         return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
4095       default:
4096        assert(0 && "Invalid atomic type");
4097        abort();
4098     }
4099   }
4100 }
4101
4102
4103 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4104                                        bool IsTailCall,
4105                                        MachineBasicBlock *LandingPad) {
4106   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4107   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4108   MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4109   unsigned BeginLabel = 0, EndLabel = 0;
4110
4111   TargetLowering::ArgListTy Args;
4112   TargetLowering::ArgListEntry Entry;
4113   Args.reserve(CS.arg_size());
4114   for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4115        i != e; ++i) {
4116     SDValue ArgNode = getValue(*i);
4117     Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4118
4119     unsigned attrInd = i - CS.arg_begin() + 1;
4120     Entry.isSExt  = CS.paramHasAttr(attrInd, Attribute::SExt);
4121     Entry.isZExt  = CS.paramHasAttr(attrInd, Attribute::ZExt);
4122     Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4123     Entry.isSRet  = CS.paramHasAttr(attrInd, Attribute::StructRet);
4124     Entry.isNest  = CS.paramHasAttr(attrInd, Attribute::Nest);
4125     Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4126     Entry.Alignment = CS.getParamAlignment(attrInd);
4127     Args.push_back(Entry);
4128   }
4129
4130   if (LandingPad && MMI) {
4131     // Insert a label before the invoke call to mark the try range.  This can be
4132     // used to detect deletion of the invoke via the MachineModuleInfo.
4133     BeginLabel = MMI->NextLabelID();
4134     // Both PendingLoads and PendingExports must be flushed here;
4135     // this call might not return.
4136     (void)getRoot();
4137     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4138   }
4139
4140   std::pair<SDValue,SDValue> Result =
4141     TLI.LowerCallTo(getRoot(), CS.getType(),
4142                     CS.paramHasAttr(0, Attribute::SExt),
4143                     CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4144                     CS.paramHasAttr(0, Attribute::InReg),
4145                     CS.getCallingConv(),
4146                     IsTailCall && PerformTailCallOpt,
4147                     Callee, Args, DAG);
4148   if (CS.getType() != Type::VoidTy)
4149     setValue(CS.getInstruction(), Result.first);
4150   DAG.setRoot(Result.second);
4151
4152   if (LandingPad && MMI) {
4153     // Insert a label at the end of the invoke call to mark the try range.  This
4154     // can be used to detect deletion of the invoke via the MachineModuleInfo.
4155     EndLabel = MMI->NextLabelID();
4156     DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4157
4158     // Inform MachineModuleInfo of range.
4159     MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4160   }
4161 }
4162
4163
4164 void SelectionDAGLowering::visitCall(CallInst &I) {
4165   const char *RenameFn = 0;
4166   if (Function *F = I.getCalledFunction()) {
4167     if (F->isDeclaration()) {
4168       if (unsigned IID = F->getIntrinsicID()) {
4169         RenameFn = visitIntrinsicCall(I, IID);
4170         if (!RenameFn)
4171           return;
4172       }
4173     }
4174
4175     // Check for well-known libc/libm calls.  If the function is internal, it
4176     // can't be a library call.
4177     unsigned NameLen = F->getNameLen();
4178     if (!F->hasInternalLinkage() && NameLen) {
4179       const char *NameStr = F->getNameStart();
4180       if (NameStr[0] == 'c' &&
4181           ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4182            (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4183         if (I.getNumOperands() == 3 &&   // Basic sanity checks.
4184             I.getOperand(1)->getType()->isFloatingPoint() &&
4185             I.getType() == I.getOperand(1)->getType() &&
4186             I.getType() == I.getOperand(2)->getType()) {
4187           SDValue LHS = getValue(I.getOperand(1));
4188           SDValue RHS = getValue(I.getOperand(2));
4189           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4190                                    LHS, RHS));
4191           return;
4192         }
4193       } else if (NameStr[0] == 'f' &&
4194                  ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4195                   (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4196                   (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4197         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4198             I.getOperand(1)->getType()->isFloatingPoint() &&
4199             I.getType() == I.getOperand(1)->getType()) {
4200           SDValue Tmp = getValue(I.getOperand(1));
4201           setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4202           return;
4203         }
4204       } else if (NameStr[0] == 's' && 
4205                  ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4206                   (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4207                   (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4208         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4209             I.getOperand(1)->getType()->isFloatingPoint() &&
4210             I.getType() == I.getOperand(1)->getType()) {
4211           SDValue Tmp = getValue(I.getOperand(1));
4212           setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4213           return;
4214         }
4215       } else if (NameStr[0] == 'c' &&
4216                  ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4217                   (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4218                   (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4219         if (I.getNumOperands() == 2 &&   // Basic sanity checks.
4220             I.getOperand(1)->getType()->isFloatingPoint() &&
4221             I.getType() == I.getOperand(1)->getType()) {
4222           SDValue Tmp = getValue(I.getOperand(1));
4223           setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4224           return;
4225         }
4226       }
4227     }
4228   } else if (isa<InlineAsm>(I.getOperand(0))) {
4229     visitInlineAsm(&I);
4230     return;
4231   }
4232
4233   SDValue Callee;
4234   if (!RenameFn)
4235     Callee = getValue(I.getOperand(0));
4236   else
4237     Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4238
4239   LowerCallTo(&I, Callee, I.isTailCall());
4240 }
4241
4242
4243 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4244 /// this value and returns the result as a ValueVT value.  This uses 
4245 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4246 /// If the Flag pointer is NULL, no flag is used.
4247 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, 
4248                                       SDValue &Chain,
4249                                       SDValue *Flag) const {
4250   // Assemble the legal parts into the final values.
4251   SmallVector<SDValue, 4> Values(ValueVTs.size());
4252   SmallVector<SDValue, 8> Parts;
4253   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4254     // Copy the legal parts from the registers.
4255     MVT ValueVT = ValueVTs[Value];
4256     unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4257     MVT RegisterVT = RegVTs[Value];
4258
4259     Parts.resize(NumRegs);
4260     for (unsigned i = 0; i != NumRegs; ++i) {
4261       SDValue P;
4262       if (Flag == 0)
4263         P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4264       else {
4265         P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4266         *Flag = P.getValue(2);
4267       }
4268       Chain = P.getValue(1);
4269       
4270       // If the source register was virtual and if we know something about it,
4271       // add an assert node.
4272       if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4273           RegisterVT.isInteger() && !RegisterVT.isVector()) {
4274         unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4275         FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4276         if (FLI.LiveOutRegInfo.size() > SlotNo) {
4277           FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4278           
4279           unsigned RegSize = RegisterVT.getSizeInBits();
4280           unsigned NumSignBits = LOI.NumSignBits;
4281           unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4282           
4283           // FIXME: We capture more information than the dag can represent.  For
4284           // now, just use the tightest assertzext/assertsext possible.
4285           bool isSExt = true;
4286           MVT FromVT(MVT::Other);
4287           if (NumSignBits == RegSize)
4288             isSExt = true, FromVT = MVT::i1;   // ASSERT SEXT 1
4289           else if (NumZeroBits >= RegSize-1)
4290             isSExt = false, FromVT = MVT::i1;  // ASSERT ZEXT 1
4291           else if (NumSignBits > RegSize-8)
4292             isSExt = true, FromVT = MVT::i8;   // ASSERT SEXT 8
4293           else if (NumZeroBits >= RegSize-9)
4294             isSExt = false, FromVT = MVT::i8;  // ASSERT ZEXT 8
4295           else if (NumSignBits > RegSize-16)
4296             isSExt = true, FromVT = MVT::i16;  // ASSERT SEXT 16
4297           else if (NumZeroBits >= RegSize-17)
4298             isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4299           else if (NumSignBits > RegSize-32)
4300             isSExt = true, FromVT = MVT::i32;  // ASSERT SEXT 32
4301           else if (NumZeroBits >= RegSize-33)
4302             isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4303           
4304           if (FromVT != MVT::Other) {
4305             P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4306                             RegisterVT, P, DAG.getValueType(FromVT));
4307
4308           }
4309         }
4310       }
4311       
4312       Parts[i] = P;
4313     }
4314   
4315     Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4316                                      ValueVT);
4317     Part += NumRegs;
4318     Parts.clear();
4319   }
4320
4321   return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4322                             &Values[0], ValueVTs.size());
4323 }
4324
4325 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4326 /// specified value into the registers specified by this object.  This uses 
4327 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4328 /// If the Flag pointer is NULL, no flag is used.
4329 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4330                                  SDValue &Chain, SDValue *Flag) const {
4331   // Get the list of the values's legal parts.
4332   unsigned NumRegs = Regs.size();
4333   SmallVector<SDValue, 8> Parts(NumRegs);
4334   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4335     MVT ValueVT = ValueVTs[Value];
4336     unsigned NumParts = TLI->getNumRegisters(ValueVT);
4337     MVT RegisterVT = RegVTs[Value];
4338
4339     getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4340                    &Parts[Part], NumParts, RegisterVT);
4341     Part += NumParts;
4342   }
4343
4344   // Copy the parts into the registers.
4345   SmallVector<SDValue, 8> Chains(NumRegs);
4346   for (unsigned i = 0; i != NumRegs; ++i) {
4347     SDValue Part;
4348     if (Flag == 0)
4349       Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4350     else {
4351       Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4352       *Flag = Part.getValue(1);
4353     }
4354     Chains[i] = Part.getValue(0);
4355   }
4356   
4357   if (NumRegs == 1 || Flag)
4358     // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is 
4359     // flagged to it. That is the CopyToReg nodes and the user are considered
4360     // a single scheduling unit. If we create a TokenFactor and return it as
4361     // chain, then the TokenFactor is both a predecessor (operand) of the
4362     // user as well as a successor (the TF operands are flagged to the user).
4363     // c1, f1 = CopyToReg
4364     // c2, f2 = CopyToReg
4365     // c3     = TokenFactor c1, c2
4366     // ...
4367     //        = op c3, ..., f2
4368     Chain = Chains[NumRegs-1];
4369   else
4370     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4371 }
4372
4373 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4374 /// operand list.  This adds the code marker and includes the number of 
4375 /// values added into it.
4376 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4377                                         std::vector<SDValue> &Ops) const {
4378   MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4379   Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4380   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4381     unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4382     MVT RegisterVT = RegVTs[Value];
4383     for (unsigned i = 0; i != NumRegs; ++i) {
4384       assert(Reg < Regs.size() && "Mismatch in # registers expected");
4385       Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4386     }
4387   }
4388 }
4389
4390 /// isAllocatableRegister - If the specified register is safe to allocate, 
4391 /// i.e. it isn't a stack pointer or some other special register, return the
4392 /// register class for the register.  Otherwise, return null.
4393 static const TargetRegisterClass *
4394 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4395                       const TargetLowering &TLI,
4396                       const TargetRegisterInfo *TRI) {
4397   MVT FoundVT = MVT::Other;
4398   const TargetRegisterClass *FoundRC = 0;
4399   for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4400        E = TRI->regclass_end(); RCI != E; ++RCI) {
4401     MVT ThisVT = MVT::Other;
4402
4403     const TargetRegisterClass *RC = *RCI;
4404     // If none of the the value types for this register class are valid, we 
4405     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
4406     for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4407          I != E; ++I) {
4408       if (TLI.isTypeLegal(*I)) {
4409         // If we have already found this register in a different register class,
4410         // choose the one with the largest VT specified.  For example, on
4411         // PowerPC, we favor f64 register classes over f32.
4412         if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4413           ThisVT = *I;
4414           break;
4415         }
4416       }
4417     }
4418     
4419     if (ThisVT == MVT::Other) continue;
4420     
4421     // NOTE: This isn't ideal.  In particular, this might allocate the
4422     // frame pointer in functions that need it (due to them not being taken
4423     // out of allocation, because a variable sized allocation hasn't been seen
4424     // yet).  This is a slight code pessimization, but should still work.
4425     for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4426          E = RC->allocation_order_end(MF); I != E; ++I)
4427       if (*I == Reg) {
4428         // We found a matching register class.  Keep looking at others in case
4429         // we find one with larger registers that this physreg is also in.
4430         FoundRC = RC;
4431         FoundVT = ThisVT;
4432         break;
4433       }
4434   }
4435   return FoundRC;
4436 }    
4437
4438
4439 namespace llvm {
4440 /// AsmOperandInfo - This contains information for each constraint that we are
4441 /// lowering.
4442 struct VISIBILITY_HIDDEN SDISelAsmOperandInfo : 
4443     public TargetLowering::AsmOperandInfo {
4444   /// CallOperand - If this is the result output operand or a clobber
4445   /// this is null, otherwise it is the incoming operand to the CallInst.
4446   /// This gets modified as the asm is processed.
4447   SDValue CallOperand;
4448
4449   /// AssignedRegs - If this is a register or register class operand, this
4450   /// contains the set of register corresponding to the operand.
4451   RegsForValue AssignedRegs;
4452   
4453   explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4454     : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4455   }
4456   
4457   /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4458   /// busy in OutputRegs/InputRegs.
4459   void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4460                          std::set<unsigned> &OutputRegs, 
4461                          std::set<unsigned> &InputRegs,
4462                          const TargetRegisterInfo &TRI) const {
4463     if (isOutReg) {
4464       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4465         MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4466     }
4467     if (isInReg) {
4468       for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4469         MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4470     }
4471   }
4472       
4473   /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4474   /// corresponds to.  If there is no Value* for this operand, it returns
4475   /// MVT::Other.
4476   MVT getCallOperandValMVT(const TargetLowering &TLI,
4477                            const TargetData *TD) const {
4478     if (CallOperandVal == 0) return MVT::Other;
4479     
4480     if (isa<BasicBlock>(CallOperandVal))
4481       return TLI.getPointerTy();
4482     
4483     const llvm::Type *OpTy = CallOperandVal->getType();
4484     
4485     // If this is an indirect operand, the operand is a pointer to the
4486     // accessed type.
4487     if (isIndirect)
4488       OpTy = cast<PointerType>(OpTy)->getElementType();
4489     
4490     // If OpTy is not a single value, it may be a struct/union that we
4491     // can tile with integers.
4492     if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4493       unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4494       switch (BitSize) {
4495       default: break;
4496       case 1:
4497       case 8:
4498       case 16:
4499       case 32:
4500       case 64:
4501       case 128:
4502         OpTy = IntegerType::get(BitSize);
4503         break;
4504       }
4505     }
4506     
4507     return TLI.getValueType(OpTy, true);
4508   }
4509   
4510 private:
4511   /// MarkRegAndAliases - Mark the specified register and all aliases in the
4512   /// specified set.
4513   static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs, 
4514                                 const TargetRegisterInfo &TRI) {
4515     assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4516     Regs.insert(Reg);
4517     if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4518       for (; *Aliases; ++Aliases)
4519         Regs.insert(*Aliases);
4520   }
4521 };
4522 } // end llvm namespace.
4523
4524
4525 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4526 /// specified operand.  We prefer to assign virtual registers, to allow the
4527 /// register allocator handle the assignment process.  However, if the asm uses
4528 /// features that we can't model on machineinstrs, we have SDISel do the
4529 /// allocation.  This produces generally horrible, but correct, code.
4530 ///
4531 ///   OpInfo describes the operand.
4532 ///   Input and OutputRegs are the set of already allocated physical registers.
4533 ///
4534 void SelectionDAGLowering::
4535 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4536                      std::set<unsigned> &OutputRegs, 
4537                      std::set<unsigned> &InputRegs) {
4538   // Compute whether this value requires an input register, an output register,
4539   // or both.
4540   bool isOutReg = false;
4541   bool isInReg = false;
4542   switch (OpInfo.Type) {
4543   case InlineAsm::isOutput:
4544     isOutReg = true;
4545     
4546     // If there is an input constraint that matches this, we need to reserve 
4547     // the input register so no other inputs allocate to it.
4548     isInReg = OpInfo.hasMatchingInput();
4549     break;
4550   case InlineAsm::isInput:
4551     isInReg = true;
4552     isOutReg = false;
4553     break;
4554   case InlineAsm::isClobber:
4555     isOutReg = true;
4556     isInReg = true;
4557     break;
4558   }
4559   
4560   
4561   MachineFunction &MF = DAG.getMachineFunction();
4562   SmallVector<unsigned, 4> Regs;
4563   
4564   // If this is a constraint for a single physreg, or a constraint for a
4565   // register class, find it.
4566   std::pair<unsigned, const TargetRegisterClass*> PhysReg = 
4567     TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4568                                      OpInfo.ConstraintVT);
4569
4570   unsigned NumRegs = 1;
4571   if (OpInfo.ConstraintVT != MVT::Other) {
4572     // If this is a FP input in an integer register (or visa versa) insert a bit
4573     // cast of the input value.  More generally, handle any case where the input
4574     // value disagrees with the register class we plan to stick this in.
4575     if (OpInfo.Type == InlineAsm::isInput &&
4576         PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4577       // Try to convert to the first MVT that the reg class contains.  If the
4578       // types are identical size, use a bitcast to convert (e.g. two differing
4579       // vector types).
4580       MVT RegVT = *PhysReg.second->vt_begin();
4581       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4582         OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4583                                          OpInfo.CallOperand);
4584         OpInfo.ConstraintVT = RegVT;
4585       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4586         // If the input is a FP value and we want it in FP registers, do a
4587         // bitcast to the corresponding integer type.  This turns an f64 value
4588         // into i64, which can be passed with two i32 values on a 32-bit
4589         // machine.
4590         RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4591         OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4592                                          OpInfo.CallOperand);
4593         OpInfo.ConstraintVT = RegVT;
4594       }
4595     }
4596     
4597     NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4598   }
4599   
4600   MVT RegVT;
4601   MVT ValueVT = OpInfo.ConstraintVT;
4602
4603   // If this is a constraint for a specific physical register, like {r17},
4604   // assign it now.
4605   if (PhysReg.first) {
4606     if (OpInfo.ConstraintVT == MVT::Other)
4607       ValueVT = *PhysReg.second->vt_begin();
4608     
4609     // Get the actual register value type.  This is important, because the user
4610     // may have asked for (e.g.) the AX register in i32 type.  We need to
4611     // remember that AX is actually i16 to get the right extension.
4612     RegVT = *PhysReg.second->vt_begin();
4613     
4614     // This is a explicit reference to a physical register.
4615     Regs.push_back(PhysReg.first);
4616
4617     // If this is an expanded reference, add the rest of the regs to Regs.
4618     if (NumRegs != 1) {
4619       TargetRegisterClass::iterator I = PhysReg.second->begin();
4620       for (; *I != PhysReg.first; ++I)
4621         assert(I != PhysReg.second->end() && "Didn't find reg!"); 
4622       
4623       // Already added the first reg.
4624       --NumRegs; ++I;
4625       for (; NumRegs; --NumRegs, ++I) {
4626         assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4627         Regs.push_back(*I);
4628       }
4629     }
4630     OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4631     const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4632     OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4633     return;
4634   }
4635   
4636   // Otherwise, if this was a reference to an LLVM register class, create vregs
4637   // for this reference.
4638   std::vector<unsigned> RegClassRegs;
4639   const TargetRegisterClass *RC = PhysReg.second;
4640   if (RC) {
4641     // If this is a tied register, our regalloc doesn't know how to maintain 
4642     // the constraint, so we have to pick a register to pin the input/output to.
4643     // If it isn't a matched constraint, go ahead and create vreg and let the
4644     // regalloc do its thing.
4645     if (!OpInfo.hasMatchingInput()) {
4646       RegVT = *PhysReg.second->vt_begin();
4647       if (OpInfo.ConstraintVT == MVT::Other)
4648         ValueVT = RegVT;
4649
4650       // Create the appropriate number of virtual registers.
4651       MachineRegisterInfo &RegInfo = MF.getRegInfo();
4652       for (; NumRegs; --NumRegs)
4653         Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4654       
4655       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4656       return;
4657     }
4658     
4659     // Otherwise, we can't allocate it.  Let the code below figure out how to
4660     // maintain these constraints.
4661     RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4662     
4663   } else {
4664     // This is a reference to a register class that doesn't directly correspond
4665     // to an LLVM register class.  Allocate NumRegs consecutive, available,
4666     // registers from the class.
4667     RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4668                                                          OpInfo.ConstraintVT);
4669   }
4670   
4671   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4672   unsigned NumAllocated = 0;
4673   for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4674     unsigned Reg = RegClassRegs[i];
4675     // See if this register is available.
4676     if ((isOutReg && OutputRegs.count(Reg)) ||   // Already used.
4677         (isInReg  && InputRegs.count(Reg))) {    // Already used.
4678       // Make sure we find consecutive registers.
4679       NumAllocated = 0;
4680       continue;
4681     }
4682     
4683     // Check to see if this register is allocatable (i.e. don't give out the
4684     // stack pointer).
4685     if (RC == 0) {
4686       RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4687       if (!RC) {        // Couldn't allocate this register.
4688         // Reset NumAllocated to make sure we return consecutive registers.
4689         NumAllocated = 0;
4690         continue;
4691       }
4692     }
4693     
4694     // Okay, this register is good, we can use it.
4695     ++NumAllocated;
4696
4697     // If we allocated enough consecutive registers, succeed.
4698     if (NumAllocated == NumRegs) {
4699       unsigned RegStart = (i-NumAllocated)+1;
4700       unsigned RegEnd   = i+1;
4701       // Mark all of the allocated registers used.
4702       for (unsigned i = RegStart; i != RegEnd; ++i)
4703         Regs.push_back(RegClassRegs[i]);
4704       
4705       OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(), 
4706                                          OpInfo.ConstraintVT);
4707       OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4708       return;
4709     }
4710   }
4711   
4712   // Otherwise, we couldn't allocate enough registers for this.
4713 }
4714
4715 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4716 /// processed uses a memory 'm' constraint.
4717 static bool
4718 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4719                           TargetLowering &TLI) {
4720   for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4721     InlineAsm::ConstraintInfo &CI = CInfos[i];
4722     for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4723       TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4724       if (CType == TargetLowering::C_Memory)
4725         return true;
4726     }
4727   }
4728
4729   return false;
4730 }
4731
4732 /// visitInlineAsm - Handle a call to an InlineAsm object.
4733 ///
4734 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4735   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4736
4737   /// ConstraintOperands - Information about all of the constraints.
4738   std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4739   
4740   SDValue Chain = getRoot();
4741   SDValue Flag;
4742   
4743   std::set<unsigned> OutputRegs, InputRegs;
4744
4745   // Do a prepass over the constraints, canonicalizing them, and building up the
4746   // ConstraintOperands list.
4747   std::vector<InlineAsm::ConstraintInfo>
4748     ConstraintInfos = IA->ParseConstraints();
4749
4750   bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
4751   
4752   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
4753   unsigned ResNo = 0;   // ResNo - The result number of the next output.
4754   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4755     ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4756     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4757     
4758     MVT OpVT = MVT::Other;
4759
4760     // Compute the value type for each operand.
4761     switch (OpInfo.Type) {
4762     case InlineAsm::isOutput:
4763       // Indirect outputs just consume an argument.
4764       if (OpInfo.isIndirect) {
4765         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4766         break;
4767       }
4768         
4769       // The return value of the call is this value.  As such, there is no
4770       // corresponding argument.
4771       assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4772       if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4773         OpVT = TLI.getValueType(STy->getElementType(ResNo));
4774       } else {
4775         assert(ResNo == 0 && "Asm only has one result!");
4776         OpVT = TLI.getValueType(CS.getType());
4777       }
4778       ++ResNo;
4779       break;
4780     case InlineAsm::isInput:
4781       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4782       break;
4783     case InlineAsm::isClobber:
4784       // Nothing to do.
4785       break;
4786     }
4787
4788     // If this is an input or an indirect output, process the call argument.
4789     // BasicBlocks are labels, currently appearing only in asm's.
4790     if (OpInfo.CallOperandVal) {
4791       if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
4792         OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4793       } else {
4794         OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4795       }
4796       
4797       OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
4798     }
4799     
4800     OpInfo.ConstraintVT = OpVT;
4801   }
4802   
4803   // Second pass over the constraints: compute which constraint option to use
4804   // and assign registers to constraints that want a specific physreg.
4805   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4806     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4807     
4808     // If this is an output operand with a matching input operand, look up the
4809     // matching input.  It might have a different type (e.g. the output might be
4810     // i32 and the input i64) and we need to pick the larger width to ensure we
4811     // reserve the right number of registers.  
4812     if (OpInfo.hasMatchingInput()) {
4813       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4814       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4815         assert(OpInfo.ConstraintVT.isInteger() &&
4816                Input.ConstraintVT.isInteger() &&
4817                "Asm constraints must be the same or different sized integers");
4818         if (OpInfo.ConstraintVT.getSizeInBits() < 
4819             Input.ConstraintVT.getSizeInBits())
4820           OpInfo.ConstraintVT = Input.ConstraintVT;
4821         else
4822           Input.ConstraintVT = OpInfo.ConstraintVT;
4823       }
4824     }
4825     
4826     // Compute the constraint code and ConstraintType to use.
4827     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
4828
4829     // If this is a memory input, and if the operand is not indirect, do what we
4830     // need to to provide an address for the memory input.
4831     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4832         !OpInfo.isIndirect) {
4833       assert(OpInfo.Type == InlineAsm::isInput &&
4834              "Can only indirectify direct input operands!");
4835       
4836       // Memory operands really want the address of the value.  If we don't have
4837       // an indirect input, put it in the constpool if we can, otherwise spill
4838       // it to a stack slot.
4839       
4840       // If the operand is a float, integer, or vector constant, spill to a
4841       // constant pool entry to get its address.
4842       Value *OpVal = OpInfo.CallOperandVal;
4843       if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4844           isa<ConstantVector>(OpVal)) {
4845         OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4846                                                  TLI.getPointerTy());
4847       } else {
4848         // Otherwise, create a stack slot and emit a store to it before the
4849         // asm.
4850         const Type *Ty = OpVal->getType();
4851         uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4852         unsigned Align  = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4853         MachineFunction &MF = DAG.getMachineFunction();
4854         int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4855         SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4856         Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4857         OpInfo.CallOperand = StackSlot;
4858       }
4859      
4860       // There is no longer a Value* corresponding to this operand.
4861       OpInfo.CallOperandVal = 0;
4862       // It is now an indirect operand.
4863       OpInfo.isIndirect = true;
4864     }
4865     
4866     // If this constraint is for a specific register, allocate it before
4867     // anything else.
4868     if (OpInfo.ConstraintType == TargetLowering::C_Register)
4869       GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4870   }
4871   ConstraintInfos.clear();
4872   
4873   
4874   // Second pass - Loop over all of the operands, assigning virtual or physregs
4875   // to register class operands.
4876   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4877     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4878     
4879     // C_Register operands have already been allocated, Other/Memory don't need
4880     // to be.
4881     if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4882       GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4883   }    
4884   
4885   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4886   std::vector<SDValue> AsmNodeOperands;
4887   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
4888   AsmNodeOperands.push_back(
4889           DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4890   
4891   
4892   // Loop over all of the inputs, copying the operand values into the
4893   // appropriate registers and processing the output regs.
4894   RegsForValue RetValRegs;
4895  
4896   // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4897   std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4898   
4899   for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4900     SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4901
4902     switch (OpInfo.Type) {
4903     case InlineAsm::isOutput: {
4904       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4905           OpInfo.ConstraintType != TargetLowering::C_Register) {
4906         // Memory output, or 'other' output (e.g. 'X' constraint).
4907         assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4908
4909         // Add information to the INLINEASM node to know about this output.
4910         unsigned ResOpType = 4/*MEM*/ | (1<<3);
4911         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4912                                                         TLI.getPointerTy()));
4913         AsmNodeOperands.push_back(OpInfo.CallOperand);
4914         break;
4915       }
4916
4917       // Otherwise, this is a register or register class output.
4918
4919       // Copy the output from the appropriate register.  Find a register that
4920       // we can use.
4921       if (OpInfo.AssignedRegs.Regs.empty()) {
4922         cerr << "Couldn't allocate output reg for constraint '"
4923              << OpInfo.ConstraintCode << "'!\n";
4924         exit(1);
4925       }
4926
4927       // If this is an indirect operand, store through the pointer after the
4928       // asm.
4929       if (OpInfo.isIndirect) {
4930         IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4931                                                       OpInfo.CallOperandVal));
4932       } else {
4933         // This is the result value of the call.
4934         assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4935         // Concatenate this output onto the outputs list.
4936         RetValRegs.append(OpInfo.AssignedRegs);
4937       }
4938       
4939       // Add information to the INLINEASM node to know that this register is
4940       // set.
4941       OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
4942                                                6 /* EARLYCLOBBER REGDEF */ :
4943                                                2 /* REGDEF */ ,
4944                                                DAG, AsmNodeOperands);
4945       break;
4946     }
4947     case InlineAsm::isInput: {
4948       SDValue InOperandVal = OpInfo.CallOperand;
4949       
4950       if (OpInfo.isMatchingInputConstraint()) {   // Matching constraint?
4951         // If this is required to match an output register we have already set,
4952         // just use its register.
4953         unsigned OperandNo = OpInfo.getMatchedOperand();
4954         
4955         // Scan until we find the definition we already emitted of this operand.
4956         // When we find it, create a RegsForValue operand.
4957         unsigned CurOp = 2;  // The first operand.
4958         for (; OperandNo; --OperandNo) {
4959           // Advance to the next operand.
4960           unsigned NumOps = 
4961             cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
4962           assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4963                   (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
4964                   (NumOps & 7) == 4 /*MEM*/) &&
4965                  "Skipped past definitions?");
4966           CurOp += (NumOps>>3)+1;
4967         }
4968
4969         unsigned NumOps = 
4970           cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
4971         if ((NumOps & 7) == 2 /*REGDEF*/ 
4972             || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
4973           // Add NumOps>>3 registers to MatchedRegs.
4974           RegsForValue MatchedRegs;
4975           MatchedRegs.TLI = &TLI;
4976           MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4977           MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4978           for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4979             unsigned Reg =
4980               cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4981             MatchedRegs.Regs.push_back(Reg);
4982           }
4983         
4984           // Use the produced MatchedRegs object to 
4985           MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4986           MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4987           break;
4988         } else {
4989           assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
4990           assert((NumOps >> 3) == 1 && "Unexpected number of operands"); 
4991           // Add information to the INLINEASM node to know about this input.
4992           AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
4993                                                           TLI.getPointerTy()));
4994           AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4995           break;
4996         }
4997       }
4998       
4999       if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5000         assert(!OpInfo.isIndirect && 
5001                "Don't know how to handle indirect other inputs yet!");
5002         
5003         std::vector<SDValue> Ops;
5004         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5005                                          hasMemory, Ops, DAG);
5006         if (Ops.empty()) {
5007           cerr << "Invalid operand for inline asm constraint '"
5008                << OpInfo.ConstraintCode << "'!\n";
5009           exit(1);
5010         }
5011         
5012         // Add information to the INLINEASM node to know about this input.
5013         unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5014         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType, 
5015                                                         TLI.getPointerTy()));
5016         AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5017         break;
5018       } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5019         assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5020         assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5021                "Memory operands expect pointer values");
5022                
5023         // Add information to the INLINEASM node to know about this input.
5024         unsigned ResOpType = 4/*MEM*/ | (1<<3);
5025         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5026                                                         TLI.getPointerTy()));
5027         AsmNodeOperands.push_back(InOperandVal);
5028         break;
5029       }
5030         
5031       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5032               OpInfo.ConstraintType == TargetLowering::C_Register) &&
5033              "Unknown constraint type!");
5034       assert(!OpInfo.isIndirect && 
5035              "Don't know how to handle indirect register inputs yet!");
5036
5037       // Copy the input into the appropriate registers.
5038       if (OpInfo.AssignedRegs.Regs.empty()) {
5039         cerr << "Couldn't allocate output reg for constraint '"
5040              << OpInfo.ConstraintCode << "'!\n";
5041         exit(1);
5042       }
5043
5044       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5045       
5046       OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5047                                                DAG, AsmNodeOperands);
5048       break;
5049     }
5050     case InlineAsm::isClobber: {
5051       // Add the clobbered value to the operand list, so that the register
5052       // allocator is aware that the physreg got clobbered.
5053       if (!OpInfo.AssignedRegs.Regs.empty())
5054         OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5055                                                  DAG, AsmNodeOperands);
5056       break;
5057     }
5058     }
5059   }
5060   
5061   // Finish up input operands.
5062   AsmNodeOperands[0] = Chain;
5063   if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5064   
5065   Chain = DAG.getNode(ISD::INLINEASM, 
5066                       DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5067                       &AsmNodeOperands[0], AsmNodeOperands.size());
5068   Flag = Chain.getValue(1);
5069
5070   // If this asm returns a register value, copy the result from that register
5071   // and set it as the value of the call.
5072   if (!RetValRegs.Regs.empty()) {
5073     SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
5074     
5075     // FIXME: Why don't we do this for inline asms with MRVs?
5076     if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5077       MVT ResultType = TLI.getValueType(CS.getType());
5078     
5079       // If any of the results of the inline asm is a vector, it may have the
5080       // wrong width/num elts.  This can happen for register classes that can
5081       // contain multiple different value types.  The preg or vreg allocated may
5082       // not have the same VT as was expected.  Convert it to the right type
5083       // with bit_convert.
5084       if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5085         Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
5086
5087       } else if (ResultType != Val.getValueType() && 
5088                  ResultType.isInteger() && Val.getValueType().isInteger()) {
5089         // If a result value was tied to an input value, the computed result may
5090         // have a wider width than the expected result.  Extract the relevant
5091         // portion.
5092         Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
5093       }
5094     
5095       assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5096     }
5097
5098     setValue(CS.getInstruction(), Val);
5099   }
5100   
5101   std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5102   
5103   // Process indirect outputs, first output all of the flagged copies out of
5104   // physregs.
5105   for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5106     RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5107     Value *Ptr = IndirectStoresToEmit[i].second;
5108     SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5109     StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5110   }
5111   
5112   // Emit the non-flagged stores from the physregs.
5113   SmallVector<SDValue, 8> OutChains;
5114   for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5115     OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5116                                     getValue(StoresToEmit[i].second),
5117                                     StoresToEmit[i].second, 0));
5118   if (!OutChains.empty())
5119     Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5120                         &OutChains[0], OutChains.size());
5121   DAG.setRoot(Chain);
5122 }
5123
5124
5125 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5126   SDValue Src = getValue(I.getOperand(0));
5127
5128   MVT IntPtr = TLI.getPointerTy();
5129
5130   if (IntPtr.bitsLT(Src.getValueType()))
5131     Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5132   else if (IntPtr.bitsGT(Src.getValueType()))
5133     Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5134
5135   // Scale the source by the type size.
5136   uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5137   Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5138                     Src, DAG.getIntPtrConstant(ElementSize));
5139
5140   TargetLowering::ArgListTy Args;
5141   TargetLowering::ArgListEntry Entry;
5142   Entry.Node = Src;
5143   Entry.Ty = TLI.getTargetData()->getIntPtrType();
5144   Args.push_back(Entry);
5145
5146   std::pair<SDValue,SDValue> Result =
5147     TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5148                     CallingConv::C, PerformTailCallOpt, 
5149                     DAG.getExternalSymbol("malloc", IntPtr),
5150                     Args, DAG);
5151   setValue(&I, Result.first);  // Pointers always fit in registers
5152   DAG.setRoot(Result.second);
5153 }
5154
5155 void SelectionDAGLowering::visitFree(FreeInst &I) {
5156   TargetLowering::ArgListTy Args;
5157   TargetLowering::ArgListEntry Entry;
5158   Entry.Node = getValue(I.getOperand(0));
5159   Entry.Ty = TLI.getTargetData()->getIntPtrType();
5160   Args.push_back(Entry);
5161   MVT IntPtr = TLI.getPointerTy();
5162   std::pair<SDValue,SDValue> Result =
5163     TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5164                     CallingConv::C, PerformTailCallOpt,
5165                     DAG.getExternalSymbol("free", IntPtr), Args, DAG);
5166   DAG.setRoot(Result.second);
5167 }
5168
5169 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5170   DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(), 
5171                           getValue(I.getOperand(1)), 
5172                           DAG.getSrcValue(I.getOperand(1))));
5173 }
5174
5175 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5176   SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5177                              getValue(I.getOperand(0)),
5178                              DAG.getSrcValue(I.getOperand(0)));
5179   setValue(&I, V);
5180   DAG.setRoot(V.getValue(1));
5181 }
5182
5183 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5184   DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5185                           getValue(I.getOperand(1)), 
5186                           DAG.getSrcValue(I.getOperand(1))));
5187 }
5188
5189 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5190   DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(), 
5191                           getValue(I.getOperand(1)), 
5192                           getValue(I.getOperand(2)),
5193                           DAG.getSrcValue(I.getOperand(1)),
5194                           DAG.getSrcValue(I.getOperand(2))));
5195 }
5196
5197 /// TargetLowering::LowerArguments - This is the default LowerArguments
5198 /// implementation, which just inserts a FORMAL_ARGUMENTS node.  FIXME: When all
5199 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be 
5200 /// integrated into SDISel.
5201 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5202                                     SmallVectorImpl<SDValue> &ArgValues) {
5203   // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5204   SmallVector<SDValue, 3+16> Ops;
5205   Ops.push_back(DAG.getRoot());
5206   Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5207   Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5208
5209   // Add one result value for each formal argument.
5210   SmallVector<MVT, 16> RetVals;
5211   unsigned j = 1;
5212   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5213        I != E; ++I, ++j) {
5214     SmallVector<MVT, 4> ValueVTs;
5215     ComputeValueVTs(*this, I->getType(), ValueVTs);
5216     for (unsigned Value = 0, NumValues = ValueVTs.size();
5217          Value != NumValues; ++Value) {
5218       MVT VT = ValueVTs[Value];
5219       const Type *ArgTy = VT.getTypeForMVT();
5220       ISD::ArgFlagsTy Flags;
5221       unsigned OriginalAlignment =
5222         getTargetData()->getABITypeAlignment(ArgTy);
5223
5224       if (F.paramHasAttr(j, Attribute::ZExt))
5225         Flags.setZExt();
5226       if (F.paramHasAttr(j, Attribute::SExt))
5227         Flags.setSExt();
5228       if (F.paramHasAttr(j, Attribute::InReg))
5229         Flags.setInReg();
5230       if (F.paramHasAttr(j, Attribute::StructRet))
5231         Flags.setSRet();
5232       if (F.paramHasAttr(j, Attribute::ByVal)) {
5233         Flags.setByVal();
5234         const PointerType *Ty = cast<PointerType>(I->getType());
5235         const Type *ElementTy = Ty->getElementType();
5236         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5237         unsigned FrameSize  = getTargetData()->getABITypeSize(ElementTy);
5238         // For ByVal, alignment should be passed from FE.  BE will guess if
5239         // this info is not there but there are cases it cannot get right.
5240         if (F.getParamAlignment(j))
5241           FrameAlign = F.getParamAlignment(j);
5242         Flags.setByValAlign(FrameAlign);
5243         Flags.setByValSize(FrameSize);
5244       }
5245       if (F.paramHasAttr(j, Attribute::Nest))
5246         Flags.setNest();
5247       Flags.setOrigAlign(OriginalAlignment);
5248
5249       MVT RegisterVT = getRegisterType(VT);
5250       unsigned NumRegs = getNumRegisters(VT);
5251       for (unsigned i = 0; i != NumRegs; ++i) {
5252         RetVals.push_back(RegisterVT);
5253         ISD::ArgFlagsTy MyFlags = Flags;
5254         if (NumRegs > 1 && i == 0)
5255           MyFlags.setSplit();
5256         // if it isn't first piece, alignment must be 1
5257         else if (i > 0)
5258           MyFlags.setOrigAlign(1);
5259         Ops.push_back(DAG.getArgFlags(MyFlags));
5260       }
5261     }
5262   }
5263
5264   RetVals.push_back(MVT::Other);
5265   
5266   // Create the node.
5267   SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5268                                DAG.getVTList(&RetVals[0], RetVals.size()),
5269                                &Ops[0], Ops.size()).getNode();
5270   
5271   // Prelower FORMAL_ARGUMENTS.  This isn't required for functionality, but
5272   // allows exposing the loads that may be part of the argument access to the
5273   // first DAGCombiner pass.
5274   SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5275   
5276   // The number of results should match up, except that the lowered one may have
5277   // an extra flag result.
5278   assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5279           (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5280            TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5281          && "Lowering produced unexpected number of results!");
5282
5283   // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5284   if (Result != TmpRes.getNode() && Result->use_empty()) {
5285     HandleSDNode Dummy(DAG.getRoot());
5286     DAG.RemoveDeadNode(Result);
5287   }
5288
5289   Result = TmpRes.getNode();
5290   
5291   unsigned NumArgRegs = Result->getNumValues() - 1;
5292   DAG.setRoot(SDValue(Result, NumArgRegs));
5293
5294   // Set up the return result vector.
5295   unsigned i = 0;
5296   unsigned Idx = 1;
5297   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; 
5298       ++I, ++Idx) {
5299     SmallVector<MVT, 4> ValueVTs;
5300     ComputeValueVTs(*this, I->getType(), ValueVTs);
5301     for (unsigned Value = 0, NumValues = ValueVTs.size();
5302          Value != NumValues; ++Value) {
5303       MVT VT = ValueVTs[Value];
5304       MVT PartVT = getRegisterType(VT);
5305
5306       unsigned NumParts = getNumRegisters(VT);
5307       SmallVector<SDValue, 4> Parts(NumParts);
5308       for (unsigned j = 0; j != NumParts; ++j)
5309         Parts[j] = SDValue(Result, i++);
5310
5311       ISD::NodeType AssertOp = ISD::DELETED_NODE;
5312       if (F.paramHasAttr(Idx, Attribute::SExt))
5313         AssertOp = ISD::AssertSext;
5314       else if (F.paramHasAttr(Idx, Attribute::ZExt))
5315         AssertOp = ISD::AssertZext;
5316
5317       ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5318                                            AssertOp));
5319     }
5320   }
5321   assert(i == NumArgRegs && "Argument register count mismatch!");
5322 }
5323
5324
5325 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5326 /// implementation, which just inserts an ISD::CALL node, which is later custom
5327 /// lowered by the target to something concrete.  FIXME: When all targets are
5328 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5329 std::pair<SDValue, SDValue>
5330 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5331                             bool RetSExt, bool RetZExt, bool isVarArg,
5332                             bool isInreg,
5333                             unsigned CallingConv, bool isTailCall,
5334                             SDValue Callee,
5335                             ArgListTy &Args, SelectionDAG &DAG) {
5336   assert((!isTailCall || PerformTailCallOpt) &&
5337          "isTailCall set when tail-call optimizations are disabled!");
5338
5339   SmallVector<SDValue, 32> Ops;
5340   Ops.push_back(Chain);   // Op#0 - Chain
5341   Ops.push_back(Callee);
5342   
5343   // Handle all of the outgoing arguments.
5344   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5345     SmallVector<MVT, 4> ValueVTs;
5346     ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5347     for (unsigned Value = 0, NumValues = ValueVTs.size();
5348          Value != NumValues; ++Value) {
5349       MVT VT = ValueVTs[Value];
5350       const Type *ArgTy = VT.getTypeForMVT();
5351       SDValue Op = SDValue(Args[i].Node.getNode(),
5352                            Args[i].Node.getResNo() + Value);
5353       ISD::ArgFlagsTy Flags;
5354       unsigned OriginalAlignment =
5355         getTargetData()->getABITypeAlignment(ArgTy);
5356
5357       if (Args[i].isZExt)
5358         Flags.setZExt();
5359       if (Args[i].isSExt)
5360         Flags.setSExt();
5361       if (Args[i].isInReg)
5362         Flags.setInReg();
5363       if (Args[i].isSRet)
5364         Flags.setSRet();
5365       if (Args[i].isByVal) {
5366         Flags.setByVal();
5367         const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5368         const Type *ElementTy = Ty->getElementType();
5369         unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5370         unsigned FrameSize  = getTargetData()->getABITypeSize(ElementTy);
5371         // For ByVal, alignment should come from FE.  BE will guess if this
5372         // info is not there but there are cases it cannot get right.
5373         if (Args[i].Alignment)
5374           FrameAlign = Args[i].Alignment;
5375         Flags.setByValAlign(FrameAlign);
5376         Flags.setByValSize(FrameSize);
5377       }
5378       if (Args[i].isNest)
5379         Flags.setNest();
5380       Flags.setOrigAlign(OriginalAlignment);
5381
5382       MVT PartVT = getRegisterType(VT);
5383       unsigned NumParts = getNumRegisters(VT);
5384       SmallVector<SDValue, 4> Parts(NumParts);
5385       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5386
5387       if (Args[i].isSExt)
5388         ExtendKind = ISD::SIGN_EXTEND;
5389       else if (Args[i].isZExt)
5390         ExtendKind = ISD::ZERO_EXTEND;
5391
5392       getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5393
5394       for (unsigned i = 0; i != NumParts; ++i) {
5395         // if it isn't first piece, alignment must be 1
5396         ISD::ArgFlagsTy MyFlags = Flags;
5397         if (NumParts > 1 && i == 0)
5398           MyFlags.setSplit();
5399         else if (i != 0)
5400           MyFlags.setOrigAlign(1);
5401
5402         Ops.push_back(Parts[i]);
5403         Ops.push_back(DAG.getArgFlags(MyFlags));
5404       }
5405     }
5406   }
5407   
5408   // Figure out the result value types. We start by making a list of
5409   // the potentially illegal return value types.
5410   SmallVector<MVT, 4> LoweredRetTys;
5411   SmallVector<MVT, 4> RetTys;
5412   ComputeValueVTs(*this, RetTy, RetTys);
5413
5414   // Then we translate that to a list of legal types.
5415   for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5416     MVT VT = RetTys[I];
5417     MVT RegisterVT = getRegisterType(VT);
5418     unsigned NumRegs = getNumRegisters(VT);
5419     for (unsigned i = 0; i != NumRegs; ++i)
5420       LoweredRetTys.push_back(RegisterVT);
5421   }
5422   
5423   LoweredRetTys.push_back(MVT::Other);  // Always has a chain.
5424   
5425   // Create the CALL node.
5426   SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
5427                             DAG.getVTList(&LoweredRetTys[0],
5428                                           LoweredRetTys.size()),
5429                             &Ops[0], Ops.size()
5430                             );
5431   Chain = Res.getValue(LoweredRetTys.size() - 1);
5432
5433   // Gather up the call result into a single value.
5434   if (RetTy != Type::VoidTy && !RetTys.empty()) {
5435     ISD::NodeType AssertOp = ISD::DELETED_NODE;
5436
5437     if (RetSExt)
5438       AssertOp = ISD::AssertSext;
5439     else if (RetZExt)
5440       AssertOp = ISD::AssertZext;
5441
5442     SmallVector<SDValue, 4> ReturnValues;
5443     unsigned RegNo = 0;
5444     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5445       MVT VT = RetTys[I];
5446       MVT RegisterVT = getRegisterType(VT);
5447       unsigned NumRegs = getNumRegisters(VT);
5448       unsigned RegNoEnd = NumRegs + RegNo;
5449       SmallVector<SDValue, 4> Results;
5450       for (; RegNo != RegNoEnd; ++RegNo)
5451         Results.push_back(Res.getValue(RegNo));
5452       SDValue ReturnValue =
5453         getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5454                          AssertOp);
5455       ReturnValues.push_back(ReturnValue);
5456     }
5457     Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
5458                              &ReturnValues[0], ReturnValues.size());
5459   }
5460
5461   return std::make_pair(Res, Chain);
5462 }
5463
5464 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5465   assert(0 && "LowerOperation not implemented for this target!");
5466   abort();
5467   return SDValue();
5468 }
5469
5470
5471 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5472   SDValue Op = getValue(V);
5473   assert((Op.getOpcode() != ISD::CopyFromReg ||
5474           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5475          "Copy from a reg to the same reg!");
5476   assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5477
5478   RegsForValue RFV(TLI, Reg, V->getType());
5479   SDValue Chain = DAG.getEntryNode();
5480   RFV.getCopyToRegs(Op, DAG, Chain, 0);
5481   PendingExports.push_back(Chain);
5482 }
5483
5484 #include "llvm/CodeGen/SelectionDAGISel.h"
5485
5486 void SelectionDAGISel::
5487 LowerArguments(BasicBlock *LLVMBB) {
5488   // If this is the entry block, emit arguments.
5489   Function &F = *LLVMBB->getParent();
5490   SDValue OldRoot = SDL->DAG.getRoot();
5491   SmallVector<SDValue, 16> Args;
5492   TLI.LowerArguments(F, SDL->DAG, Args);
5493
5494   unsigned a = 0;
5495   for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5496        AI != E; ++AI) {
5497     SmallVector<MVT, 4> ValueVTs;
5498     ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5499     unsigned NumValues = ValueVTs.size();
5500     if (!AI->use_empty()) {
5501       SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5502       // If this argument is live outside of the entry block, insert a copy from
5503       // whereever we got it to the vreg that other BB's will reference it as.
5504       DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5505       if (VMI != FuncInfo->ValueMap.end()) {
5506         SDL->CopyValueToVirtualRegister(AI, VMI->second);
5507       }
5508     }
5509     a += NumValues;
5510   }
5511
5512   // Finally, if the target has anything special to do, allow it to do so.
5513   // FIXME: this should insert code into the DAG!
5514   EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5515 }
5516
5517 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
5518 /// ensure constants are generated when needed.  Remember the virtual registers
5519 /// that need to be added to the Machine PHI nodes as input.  We cannot just
5520 /// directly add them, because expansion might result in multiple MBB's for one
5521 /// BB.  As such, the start of the BB might correspond to a different MBB than
5522 /// the end.
5523 ///
5524 void
5525 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5526   TerminatorInst *TI = LLVMBB->getTerminator();
5527
5528   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5529
5530   // Check successor nodes' PHI nodes that expect a constant to be available
5531   // from this block.
5532   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5533     BasicBlock *SuccBB = TI->getSuccessor(succ);
5534     if (!isa<PHINode>(SuccBB->begin())) continue;
5535     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5536     
5537     // If this terminator has multiple identical successors (common for
5538     // switches), only handle each succ once.
5539     if (!SuccsHandled.insert(SuccMBB)) continue;
5540     
5541     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5542     PHINode *PN;
5543
5544     // At this point we know that there is a 1-1 correspondence between LLVM PHI
5545     // nodes and Machine PHI nodes, but the incoming operands have not been
5546     // emitted yet.
5547     for (BasicBlock::iterator I = SuccBB->begin();
5548          (PN = dyn_cast<PHINode>(I)); ++I) {
5549       // Ignore dead phi's.
5550       if (PN->use_empty()) continue;
5551
5552       unsigned Reg;
5553       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5554
5555       if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5556         unsigned &RegOut = SDL->ConstantsOut[C];
5557         if (RegOut == 0) {
5558           RegOut = FuncInfo->CreateRegForValue(C);
5559           SDL->CopyValueToVirtualRegister(C, RegOut);
5560         }
5561         Reg = RegOut;
5562       } else {
5563         Reg = FuncInfo->ValueMap[PHIOp];
5564         if (Reg == 0) {
5565           assert(isa<AllocaInst>(PHIOp) &&
5566                  FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5567                  "Didn't codegen value into a register!??");
5568           Reg = FuncInfo->CreateRegForValue(PHIOp);
5569           SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5570         }
5571       }
5572
5573       // Remember that this register needs to added to the machine PHI node as
5574       // the input for this MBB.
5575       SmallVector<MVT, 4> ValueVTs;
5576       ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5577       for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5578         MVT VT = ValueVTs[vti];
5579         unsigned NumRegisters = TLI.getNumRegisters(VT);
5580         for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5581           SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5582         Reg += NumRegisters;
5583       }
5584     }
5585   }
5586   SDL->ConstantsOut.clear();
5587 }
5588
5589 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5590 /// supports legal types, and it emits MachineInstrs directly instead of
5591 /// creating SelectionDAG nodes.
5592 ///
5593 bool
5594 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5595                                                       FastISel *F) {
5596   TerminatorInst *TI = LLVMBB->getTerminator();
5597
5598   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5599   unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5600
5601   // Check successor nodes' PHI nodes that expect a constant to be available
5602   // from this block.
5603   for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5604     BasicBlock *SuccBB = TI->getSuccessor(succ);
5605     if (!isa<PHINode>(SuccBB->begin())) continue;
5606     MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5607     
5608     // If this terminator has multiple identical successors (common for
5609     // switches), only handle each succ once.
5610     if (!SuccsHandled.insert(SuccMBB)) continue;
5611     
5612     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5613     PHINode *PN;
5614
5615     // At this point we know that there is a 1-1 correspondence between LLVM PHI
5616     // nodes and Machine PHI nodes, but the incoming operands have not been
5617     // emitted yet.
5618     for (BasicBlock::iterator I = SuccBB->begin();
5619          (PN = dyn_cast<PHINode>(I)); ++I) {
5620       // Ignore dead phi's.
5621       if (PN->use_empty()) continue;
5622
5623       // Only handle legal types. Two interesting things to note here. First,
5624       // by bailing out early, we may leave behind some dead instructions,
5625       // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5626       // own moves. Second, this check is necessary becuase FastISel doesn't
5627       // use CreateRegForValue to create registers, so it always creates
5628       // exactly one register for each non-void instruction.
5629       MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5630       if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5631         // Promote MVT::i1.
5632         if (VT == MVT::i1)
5633           VT = TLI.getTypeToTransformTo(VT);
5634         else {
5635           SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5636           return false;
5637         }
5638       }
5639
5640       Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5641
5642       unsigned Reg = F->getRegForValue(PHIOp);
5643       if (Reg == 0) {
5644         SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5645         return false;
5646       }
5647       SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5648     }
5649   }
5650
5651   return true;
5652 }