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