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