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