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