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