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