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