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