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