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