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