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