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