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