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