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