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