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