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