xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 421557974a3e0f469e6f4c3caecbf8aba69bb5bf)
1 //===- SelectionDAGBuilder.cpp - Selection-DAG building -------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements routines for translating from LLVM IR into SelectionDAG IR.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "SelectionDAGBuilder.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/BranchProbabilityInfo.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/Loads.h"
27 #include "llvm/Analysis/MemoryLocation.h"
28 #include "llvm/Analysis/TargetLibraryInfo.h"
29 #include "llvm/Analysis/TargetTransformInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Analysis/VectorUtils.h"
32 #include "llvm/CodeGen/Analysis.h"
33 #include "llvm/CodeGen/AssignmentTrackingAnalysis.h"
34 #include "llvm/CodeGen/CodeGenCommonISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCMetadata.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
43 #include "llvm/CodeGen/MachineMemOperand.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineOperand.h"
46 #include "llvm/CodeGen/MachineRegisterInfo.h"
47 #include "llvm/CodeGen/RuntimeLibcalls.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
50 #include "llvm/CodeGen/StackMaps.h"
51 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
52 #include "llvm/CodeGen/TargetFrameLowering.h"
53 #include "llvm/CodeGen/TargetInstrInfo.h"
54 #include "llvm/CodeGen/TargetOpcodes.h"
55 #include "llvm/CodeGen/TargetRegisterInfo.h"
56 #include "llvm/CodeGen/TargetSubtargetInfo.h"
57 #include "llvm/CodeGen/WinEHFuncInfo.h"
58 #include "llvm/IR/Argument.h"
59 #include "llvm/IR/Attributes.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/ConstantRange.h"
65 #include "llvm/IR/Constants.h"
66 #include "llvm/IR/DataLayout.h"
67 #include "llvm/IR/DebugInfo.h"
68 #include "llvm/IR/DebugInfoMetadata.h"
69 #include "llvm/IR/DerivedTypes.h"
70 #include "llvm/IR/DiagnosticInfo.h"
71 #include "llvm/IR/EHPersonalities.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GetElementPtrTypeIterator.h"
74 #include "llvm/IR/InlineAsm.h"
75 #include "llvm/IR/InstrTypes.h"
76 #include "llvm/IR/Instructions.h"
77 #include "llvm/IR/IntrinsicInst.h"
78 #include "llvm/IR/Intrinsics.h"
79 #include "llvm/IR/IntrinsicsAArch64.h"
80 #include "llvm/IR/IntrinsicsAMDGPU.h"
81 #include "llvm/IR/IntrinsicsWebAssembly.h"
82 #include "llvm/IR/LLVMContext.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Module.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Statepoint.h"
88 #include "llvm/IR/Type.h"
89 #include "llvm/IR/User.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/MC/MCContext.h"
92 #include "llvm/Support/AtomicOrdering.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/InstructionCost.h"
98 #include "llvm/Support/MathExtras.h"
99 #include "llvm/Support/raw_ostream.h"
100 #include "llvm/Target/TargetIntrinsicInfo.h"
101 #include "llvm/Target/TargetMachine.h"
102 #include "llvm/Target/TargetOptions.h"
103 #include "llvm/TargetParser/Triple.h"
104 #include "llvm/Transforms/Utils/Local.h"
105 #include <cstddef>
106 #include <iterator>
107 #include <limits>
108 #include <optional>
109 #include <tuple>
110 
111 using namespace llvm;
112 using namespace PatternMatch;
113 using namespace SwitchCG;
114 
115 #define DEBUG_TYPE "isel"
116 
117 /// LimitFloatPrecision - Generate low-precision inline sequences for
118 /// some float libcalls (6, 8 or 12 bits).
119 static unsigned LimitFloatPrecision;
120 
121 static cl::opt<bool>
122     InsertAssertAlign("insert-assert-align", cl::init(true),
123                       cl::desc("Insert the experimental `assertalign` node."),
124                       cl::ReallyHidden);
125 
126 static cl::opt<unsigned, true>
127     LimitFPPrecision("limit-float-precision",
128                      cl::desc("Generate low-precision inline sequences "
129                               "for some float libcalls"),
130                      cl::location(LimitFloatPrecision), cl::Hidden,
131                      cl::init(0));
132 
133 static cl::opt<unsigned> SwitchPeelThreshold(
134     "switch-peel-threshold", cl::Hidden, cl::init(66),
135     cl::desc("Set the case probability threshold for peeling the case from a "
136              "switch statement. A value greater than 100 will void this "
137              "optimization"));
138 
139 // Limit the width of DAG chains. This is important in general to prevent
140 // DAG-based analysis from blowing up. For example, alias analysis and
141 // load clustering may not complete in reasonable time. It is difficult to
142 // recognize and avoid this situation within each individual analysis, and
143 // future analyses are likely to have the same behavior. Limiting DAG width is
144 // the safe approach and will be especially important with global DAGs.
145 //
146 // MaxParallelChains default is arbitrarily high to avoid affecting
147 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
148 // sequence over this should have been converted to llvm.memcpy by the
149 // frontend. It is easy to induce this behavior with .ll code such as:
150 // %buffer = alloca [4096 x i8]
151 // %data = load [4096 x i8]* %argPtr
152 // store [4096 x i8] %data, [4096 x i8]* %buffer
153 static const unsigned MaxParallelChains = 64;
154 
155 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
156                                       const SDValue *Parts, unsigned NumParts,
157                                       MVT PartVT, EVT ValueVT, const Value *V,
158                                       SDValue InChain,
159                                       std::optional<CallingConv::ID> CC);
160 
161 /// getCopyFromParts - Create a value that contains the specified legal parts
162 /// combined into the value they represent.  If the parts combine to a type
163 /// larger than ValueVT then AssertOp can be used to specify whether the extra
164 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
165 /// (ISD::AssertSext).
166 static SDValue
167 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
168                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
169                  SDValue InChain,
170                  std::optional<CallingConv::ID> CC = std::nullopt,
171                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
172   // Let the target assemble the parts if it wants to
173   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
174   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
175                                                    PartVT, ValueVT, CC))
176     return Val;
177 
178   if (ValueVT.isVector())
179     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
180                                   InChain, CC);
181 
182   assert(NumParts > 0 && "No parts to assemble!");
183   SDValue Val = Parts[0];
184 
185   if (NumParts > 1) {
186     // Assemble the value from multiple parts.
187     if (ValueVT.isInteger()) {
188       unsigned PartBits = PartVT.getSizeInBits();
189       unsigned ValueBits = ValueVT.getSizeInBits();
190 
191       // Assemble the power of 2 part.
192       unsigned RoundParts = llvm::bit_floor(NumParts);
193       unsigned RoundBits = PartBits * RoundParts;
194       EVT RoundVT = RoundBits == ValueBits ?
195         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
196       SDValue Lo, Hi;
197 
198       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
199 
200       if (RoundParts > 2) {
201         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
202                               InChain);
203         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
204                               PartVT, HalfVT, V, InChain);
205       } else {
206         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
207         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
208       }
209 
210       if (DAG.getDataLayout().isBigEndian())
211         std::swap(Lo, Hi);
212 
213       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
214 
215       if (RoundParts < NumParts) {
216         // Assemble the trailing non-power-of-2 part.
217         unsigned OddParts = NumParts - RoundParts;
218         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
219         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
220                               OddVT, V, InChain, CC);
221 
222         // Combine the round and odd parts.
223         Lo = Val;
224         if (DAG.getDataLayout().isBigEndian())
225           std::swap(Lo, Hi);
226         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
227         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
228         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
229                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
230                                          TLI.getShiftAmountTy(
231                                              TotalVT, DAG.getDataLayout())));
232         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
233         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
234       }
235     } else if (PartVT.isFloatingPoint()) {
236       // FP split into multiple FP parts (for ppcf128)
237       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
238              "Unexpected split");
239       SDValue Lo, Hi;
240       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
241       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
242       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
243         std::swap(Lo, Hi);
244       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
245     } else {
246       // FP split into integer parts (soft fp)
247       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
248              !PartVT.isVector() && "Unexpected split");
249       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
250       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
251                              InChain, CC);
252     }
253   }
254 
255   // There is now one part, held in Val.  Correct it to match ValueVT.
256   // PartEVT is the type of the register class that holds the value.
257   // ValueVT is the type of the inline asm operation.
258   EVT PartEVT = Val.getValueType();
259 
260   if (PartEVT == ValueVT)
261     return Val;
262 
263   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
264       ValueVT.bitsLT(PartEVT)) {
265     // For an FP value in an integer part, we need to truncate to the right
266     // width first.
267     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
268     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
269   }
270 
271   // Handle types that have the same size.
272   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
273     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
274 
275   // Handle types with different sizes.
276   if (PartEVT.isInteger() && ValueVT.isInteger()) {
277     if (ValueVT.bitsLT(PartEVT)) {
278       // For a truncate, see if we have any information to
279       // indicate whether the truncated bits will always be
280       // zero or sign-extension.
281       if (AssertOp)
282         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
283                           DAG.getValueType(ValueVT));
284       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
285     }
286     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
287   }
288 
289   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
290     // FP_ROUND's are always exact here.
291     if (ValueVT.bitsLT(Val.getValueType())) {
292 
293       SDValue NoChange =
294           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
295 
296       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
297               llvm::Attribute::StrictFP)) {
298         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
299                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
300                            NoChange);
301       }
302 
303       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
304     }
305 
306     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
307   }
308 
309   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
310   // then truncating.
311   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
312       ValueVT.bitsLT(PartEVT)) {
313     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
314     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
315   }
316 
317   report_fatal_error("Unknown mismatch in getCopyFromParts!");
318 }
319 
320 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
321                                               const Twine &ErrMsg) {
322   const Instruction *I = dyn_cast_or_null<Instruction>(V);
323   if (!V)
324     return Ctx.emitError(ErrMsg);
325 
326   const char *AsmError = ", possible invalid constraint for vector type";
327   if (const CallInst *CI = dyn_cast<CallInst>(I))
328     if (CI->isInlineAsm())
329       return Ctx.emitError(I, ErrMsg + AsmError);
330 
331   return Ctx.emitError(I, ErrMsg);
332 }
333 
334 /// getCopyFromPartsVector - Create a value that contains the specified legal
335 /// parts combined into the value they represent.  If the parts combine to a
336 /// type larger than ValueVT then AssertOp can be used to specify whether the
337 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
338 /// ValueVT (ISD::AssertSext).
339 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
340                                       const SDValue *Parts, unsigned NumParts,
341                                       MVT PartVT, EVT ValueVT, const Value *V,
342                                       SDValue InChain,
343                                       std::optional<CallingConv::ID> CallConv) {
344   assert(ValueVT.isVector() && "Not a vector value");
345   assert(NumParts > 0 && "No parts to assemble!");
346   const bool IsABIRegCopy = CallConv.has_value();
347 
348   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
349   SDValue Val = Parts[0];
350 
351   // Handle a multi-element vector.
352   if (NumParts > 1) {
353     EVT IntermediateVT;
354     MVT RegisterVT;
355     unsigned NumIntermediates;
356     unsigned NumRegs;
357 
358     if (IsABIRegCopy) {
359       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
360           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
361           NumIntermediates, RegisterVT);
362     } else {
363       NumRegs =
364           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
365                                      NumIntermediates, RegisterVT);
366     }
367 
368     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
369     NumParts = NumRegs; // Silence a compiler warning.
370     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
371     assert(RegisterVT.getSizeInBits() ==
372            Parts[0].getSimpleValueType().getSizeInBits() &&
373            "Part type sizes don't match!");
374 
375     // Assemble the parts into intermediate operands.
376     SmallVector<SDValue, 8> Ops(NumIntermediates);
377     if (NumIntermediates == NumParts) {
378       // If the register was not expanded, truncate or copy the value,
379       // as appropriate.
380       for (unsigned i = 0; i != NumParts; ++i)
381         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
382                                   V, InChain, CallConv);
383     } else if (NumParts > 0) {
384       // If the intermediate type was expanded, build the intermediate
385       // operands from the parts.
386       assert(NumParts % NumIntermediates == 0 &&
387              "Must expand into a divisible number of parts!");
388       unsigned Factor = NumParts / NumIntermediates;
389       for (unsigned i = 0; i != NumIntermediates; ++i)
390         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
391                                   IntermediateVT, V, InChain, CallConv);
392     }
393 
394     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
395     // intermediate operands.
396     EVT BuiltVectorTy =
397         IntermediateVT.isVector()
398             ? EVT::getVectorVT(
399                   *DAG.getContext(), IntermediateVT.getScalarType(),
400                   IntermediateVT.getVectorElementCount() * NumParts)
401             : EVT::getVectorVT(*DAG.getContext(),
402                                IntermediateVT.getScalarType(),
403                                NumIntermediates);
404     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
405                                                 : ISD::BUILD_VECTOR,
406                       DL, BuiltVectorTy, Ops);
407   }
408 
409   // There is now one part, held in Val.  Correct it to match ValueVT.
410   EVT PartEVT = Val.getValueType();
411 
412   if (PartEVT == ValueVT)
413     return Val;
414 
415   if (PartEVT.isVector()) {
416     // Vector/Vector bitcast.
417     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
418       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419 
420     // If the parts vector has more elements than the value vector, then we
421     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
422     // Extract the elements we want.
423     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
424       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
425               ValueVT.getVectorElementCount().getKnownMinValue()) &&
426              (PartEVT.getVectorElementCount().isScalable() ==
427               ValueVT.getVectorElementCount().isScalable()) &&
428              "Cannot narrow, it would be a lossy transformation");
429       PartEVT =
430           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
431                            ValueVT.getVectorElementCount());
432       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
433                         DAG.getVectorIdxConstant(0, DL));
434       if (PartEVT == ValueVT)
435         return Val;
436       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
437         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438 
439       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
440       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
441         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
442     }
443 
444     // Promoted vector extract
445     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
446   }
447 
448   // Trivial bitcast if the types are the same size and the destination
449   // vector type is legal.
450   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
451       TLI.isTypeLegal(ValueVT))
452     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
453 
454   if (ValueVT.getVectorNumElements() != 1) {
455      // Certain ABIs require that vectors are passed as integers. For vectors
456      // are the same size, this is an obvious bitcast.
457      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
458        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
459      } else if (ValueVT.bitsLT(PartEVT)) {
460        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
461        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
462        // Drop the extra bits.
463        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
464        return DAG.getBitcast(ValueVT, Val);
465      }
466 
467      diagnosePossiblyInvalidConstraint(
468          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
469      return DAG.getUNDEF(ValueVT);
470   }
471 
472   // Handle cases such as i8 -> <1 x i1>
473   EVT ValueSVT = ValueVT.getVectorElementType();
474   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
475     unsigned ValueSize = ValueSVT.getSizeInBits();
476     if (ValueSize == PartEVT.getSizeInBits()) {
477       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
478     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
479       // It's possible a scalar floating point type gets softened to integer and
480       // then promoted to a larger integer. If PartEVT is the larger integer
481       // we need to truncate it and then bitcast to the FP type.
482       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
483       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
484       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
485       Val = DAG.getBitcast(ValueSVT, Val);
486     } else {
487       Val = ValueVT.isFloatingPoint()
488                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
489                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
490     }
491   }
492 
493   return DAG.getBuildVector(ValueVT, DL, Val);
494 }
495 
496 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
497                                  SDValue Val, SDValue *Parts, unsigned NumParts,
498                                  MVT PartVT, const Value *V,
499                                  std::optional<CallingConv::ID> CallConv);
500 
501 /// getCopyToParts - Create a series of nodes that contain the specified value
502 /// split into legal parts.  If the parts contain more bits than Val, then, for
503 /// integers, ExtendKind can be used to specify how to generate the extra bits.
504 static void
505 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
506                unsigned NumParts, MVT PartVT, const Value *V,
507                std::optional<CallingConv::ID> CallConv = std::nullopt,
508                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
509   // Let the target split the parts if it wants to
510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
511   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
512                                       CallConv))
513     return;
514   EVT ValueVT = Val.getValueType();
515 
516   // Handle the vector case separately.
517   if (ValueVT.isVector())
518     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
519                                 CallConv);
520 
521   unsigned OrigNumParts = NumParts;
522   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
523          "Copying to an illegal type!");
524 
525   if (NumParts == 0)
526     return;
527 
528   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
529   EVT PartEVT = PartVT;
530   if (PartEVT == ValueVT) {
531     assert(NumParts == 1 && "No-op copy with multiple parts!");
532     Parts[0] = Val;
533     return;
534   }
535 
536   unsigned PartBits = PartVT.getSizeInBits();
537   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
538     // If the parts cover more bits than the value has, promote the value.
539     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
540       assert(NumParts == 1 && "Do not know what to promote to!");
541       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
542     } else {
543       if (ValueVT.isFloatingPoint()) {
544         // FP values need to be bitcast, then extended if they are being put
545         // into a larger container.
546         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
547         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
548       }
549       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
550              ValueVT.isInteger() &&
551              "Unknown mismatch!");
552       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
553       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
554       if (PartVT == MVT::x86mmx)
555         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
556     }
557   } else if (PartBits == ValueVT.getSizeInBits()) {
558     // Different types of the same size.
559     assert(NumParts == 1 && PartEVT != ValueVT);
560     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
562     // If the parts cover less bits than value has, truncate the value.
563     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
564            ValueVT.isInteger() &&
565            "Unknown mismatch!");
566     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
567     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
568     if (PartVT == MVT::x86mmx)
569       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
570   }
571 
572   // The value may have changed - recompute ValueVT.
573   ValueVT = Val.getValueType();
574   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
575          "Failed to tile the value with PartVT!");
576 
577   if (NumParts == 1) {
578     if (PartEVT != ValueVT) {
579       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
580                                         "scalar-to-vector conversion failed");
581       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
582     }
583 
584     Parts[0] = Val;
585     return;
586   }
587 
588   // Expand the value into multiple parts.
589   if (NumParts & (NumParts - 1)) {
590     // The number of parts is not a power of 2.  Split off and copy the tail.
591     assert(PartVT.isInteger() && ValueVT.isInteger() &&
592            "Do not know what to expand to!");
593     unsigned RoundParts = llvm::bit_floor(NumParts);
594     unsigned RoundBits = RoundParts * PartBits;
595     unsigned OddParts = NumParts - RoundParts;
596     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
597       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
598 
599     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
600                    CallConv);
601 
602     if (DAG.getDataLayout().isBigEndian())
603       // The odd parts were reversed by getCopyToParts - unreverse them.
604       std::reverse(Parts + RoundParts, Parts + NumParts);
605 
606     NumParts = RoundParts;
607     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
608     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
609   }
610 
611   // The number of parts is a power of 2.  Repeatedly bisect the value using
612   // EXTRACT_ELEMENT.
613   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
614                          EVT::getIntegerVT(*DAG.getContext(),
615                                            ValueVT.getSizeInBits()),
616                          Val);
617 
618   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
619     for (unsigned i = 0; i < NumParts; i += StepSize) {
620       unsigned ThisBits = StepSize * PartBits / 2;
621       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
622       SDValue &Part0 = Parts[i];
623       SDValue &Part1 = Parts[i+StepSize/2];
624 
625       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
626                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
627       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
628                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
629 
630       if (ThisBits == PartBits && ThisVT != PartVT) {
631         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
632         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
633       }
634     }
635   }
636 
637   if (DAG.getDataLayout().isBigEndian())
638     std::reverse(Parts, Parts + OrigNumParts);
639 }
640 
641 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
642                                      const SDLoc &DL, EVT PartVT) {
643   if (!PartVT.isVector())
644     return SDValue();
645 
646   EVT ValueVT = Val.getValueType();
647   EVT PartEVT = PartVT.getVectorElementType();
648   EVT ValueEVT = ValueVT.getVectorElementType();
649   ElementCount PartNumElts = PartVT.getVectorElementCount();
650   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
651 
652   // We only support widening vectors with equivalent element types and
653   // fixed/scalable properties. If a target needs to widen a fixed-length type
654   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
655   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
656       PartNumElts.isScalable() != ValueNumElts.isScalable())
657     return SDValue();
658 
659   // Have a try for bf16 because some targets share its ABI with fp16.
660   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
661     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
662            "Cannot widen to illegal type");
663     Val = DAG.getNode(ISD::BITCAST, DL,
664                       ValueVT.changeVectorElementType(MVT::f16), Val);
665   } else if (PartEVT != ValueEVT) {
666     return SDValue();
667   }
668 
669   // Widening a scalable vector to another scalable vector is done by inserting
670   // the vector into a larger undef one.
671   if (PartNumElts.isScalable())
672     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
673                        Val, DAG.getVectorIdxConstant(0, DL));
674 
675   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
676   // undef elements.
677   SmallVector<SDValue, 16> Ops;
678   DAG.ExtractVectorElements(Val, Ops);
679   SDValue EltUndef = DAG.getUNDEF(PartEVT);
680   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
681 
682   // FIXME: Use CONCAT for 2x -> 4x.
683   return DAG.getBuildVector(PartVT, DL, Ops);
684 }
685 
686 /// getCopyToPartsVector - Create a series of nodes that contain the specified
687 /// value split into legal parts.
688 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
689                                  SDValue Val, SDValue *Parts, unsigned NumParts,
690                                  MVT PartVT, const Value *V,
691                                  std::optional<CallingConv::ID> CallConv) {
692   EVT ValueVT = Val.getValueType();
693   assert(ValueVT.isVector() && "Not a vector");
694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
695   const bool IsABIRegCopy = CallConv.has_value();
696 
697   if (NumParts == 1) {
698     EVT PartEVT = PartVT;
699     if (PartEVT == ValueVT) {
700       // Nothing to do.
701     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
702       // Bitconvert vector->vector case.
703       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
704     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
705       Val = Widened;
706     } else if (PartVT.isVector() &&
707                PartEVT.getVectorElementType().bitsGE(
708                    ValueVT.getVectorElementType()) &&
709                PartEVT.getVectorElementCount() ==
710                    ValueVT.getVectorElementCount()) {
711 
712       // Promoted vector extract
713       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
714     } else if (PartEVT.isVector() &&
715                PartEVT.getVectorElementType() !=
716                    ValueVT.getVectorElementType() &&
717                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
718                    TargetLowering::TypeWidenVector) {
719       // Combination of widening and promotion.
720       EVT WidenVT =
721           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
722                            PartVT.getVectorElementCount());
723       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
724       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
725     } else {
726       // Don't extract an integer from a float vector. This can happen if the
727       // FP type gets softened to integer and then promoted. The promotion
728       // prevents it from being picked up by the earlier bitcast case.
729       if (ValueVT.getVectorElementCount().isScalar() &&
730           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
731         Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
732                           DAG.getVectorIdxConstant(0, DL));
733       } else {
734         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
735         assert(PartVT.getFixedSizeInBits() > ValueSize &&
736                "lossy conversion of vector to scalar type");
737         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
738         Val = DAG.getBitcast(IntermediateType, Val);
739         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
740       }
741     }
742 
743     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
744     Parts[0] = Val;
745     return;
746   }
747 
748   // Handle a multi-element vector.
749   EVT IntermediateVT;
750   MVT RegisterVT;
751   unsigned NumIntermediates;
752   unsigned NumRegs;
753   if (IsABIRegCopy) {
754     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
755         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
756         RegisterVT);
757   } else {
758     NumRegs =
759         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
760                                    NumIntermediates, RegisterVT);
761   }
762 
763   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
764   NumParts = NumRegs; // Silence a compiler warning.
765   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
766 
767   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
768          "Mixing scalable and fixed vectors when copying in parts");
769 
770   std::optional<ElementCount> DestEltCnt;
771 
772   if (IntermediateVT.isVector())
773     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
774   else
775     DestEltCnt = ElementCount::getFixed(NumIntermediates);
776 
777   EVT BuiltVectorTy = EVT::getVectorVT(
778       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
779 
780   if (ValueVT == BuiltVectorTy) {
781     // Nothing to do.
782   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
783     // Bitconvert vector->vector case.
784     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
785   } else {
786     if (BuiltVectorTy.getVectorElementType().bitsGT(
787             ValueVT.getVectorElementType())) {
788       // Integer promotion.
789       ValueVT = EVT::getVectorVT(*DAG.getContext(),
790                                  BuiltVectorTy.getVectorElementType(),
791                                  ValueVT.getVectorElementCount());
792       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
793     }
794 
795     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
796       Val = Widened;
797     }
798   }
799 
800   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
801 
802   // Split the vector into intermediate operands.
803   SmallVector<SDValue, 8> Ops(NumIntermediates);
804   for (unsigned i = 0; i != NumIntermediates; ++i) {
805     if (IntermediateVT.isVector()) {
806       // This does something sensible for scalable vectors - see the
807       // definition of EXTRACT_SUBVECTOR for further details.
808       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
809       Ops[i] =
810           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
811                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
812     } else {
813       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
814                            DAG.getVectorIdxConstant(i, DL));
815     }
816   }
817 
818   // Split the intermediate operands into legal parts.
819   if (NumParts == NumIntermediates) {
820     // If the register was not expanded, promote or copy the value,
821     // as appropriate.
822     for (unsigned i = 0; i != NumParts; ++i)
823       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
824   } else if (NumParts > 0) {
825     // If the intermediate type was expanded, split each the value into
826     // legal parts.
827     assert(NumIntermediates != 0 && "division by zero");
828     assert(NumParts % NumIntermediates == 0 &&
829            "Must expand into a divisible number of parts!");
830     unsigned Factor = NumParts / NumIntermediates;
831     for (unsigned i = 0; i != NumIntermediates; ++i)
832       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
833                      CallConv);
834   }
835 }
836 
837 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
838                            EVT valuevt, std::optional<CallingConv::ID> CC)
839     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
840       RegCount(1, regs.size()), CallConv(CC) {}
841 
842 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
843                            const DataLayout &DL, unsigned Reg, Type *Ty,
844                            std::optional<CallingConv::ID> CC) {
845   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
846 
847   CallConv = CC;
848 
849   for (EVT ValueVT : ValueVTs) {
850     unsigned NumRegs =
851         isABIMangled()
852             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
853             : TLI.getNumRegisters(Context, ValueVT);
854     MVT RegisterVT =
855         isABIMangled()
856             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
857             : TLI.getRegisterType(Context, ValueVT);
858     for (unsigned i = 0; i != NumRegs; ++i)
859       Regs.push_back(Reg + i);
860     RegVTs.push_back(RegisterVT);
861     RegCount.push_back(NumRegs);
862     Reg += NumRegs;
863   }
864 }
865 
866 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
867                                       FunctionLoweringInfo &FuncInfo,
868                                       const SDLoc &dl, SDValue &Chain,
869                                       SDValue *Glue, const Value *V) const {
870   // A Value with type {} or [0 x %t] needs no registers.
871   if (ValueVTs.empty())
872     return SDValue();
873 
874   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
875 
876   // Assemble the legal parts into the final values.
877   SmallVector<SDValue, 4> Values(ValueVTs.size());
878   SmallVector<SDValue, 8> Parts;
879   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
880     // Copy the legal parts from the registers.
881     EVT ValueVT = ValueVTs[Value];
882     unsigned NumRegs = RegCount[Value];
883     MVT RegisterVT = isABIMangled()
884                          ? TLI.getRegisterTypeForCallingConv(
885                                *DAG.getContext(), *CallConv, RegVTs[Value])
886                          : RegVTs[Value];
887 
888     Parts.resize(NumRegs);
889     for (unsigned i = 0; i != NumRegs; ++i) {
890       SDValue P;
891       if (!Glue) {
892         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
893       } else {
894         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
895         *Glue = P.getValue(2);
896       }
897 
898       Chain = P.getValue(1);
899       Parts[i] = P;
900 
901       // If the source register was virtual and if we know something about it,
902       // add an assert node.
903       if (!Register::isVirtualRegister(Regs[Part + i]) ||
904           !RegisterVT.isInteger())
905         continue;
906 
907       const FunctionLoweringInfo::LiveOutInfo *LOI =
908         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
909       if (!LOI)
910         continue;
911 
912       unsigned RegSize = RegisterVT.getScalarSizeInBits();
913       unsigned NumSignBits = LOI->NumSignBits;
914       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
915 
916       if (NumZeroBits == RegSize) {
917         // The current value is a zero.
918         // Explicitly express that as it would be easier for
919         // optimizations to kick in.
920         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
921         continue;
922       }
923 
924       // FIXME: We capture more information than the dag can represent.  For
925       // now, just use the tightest assertzext/assertsext possible.
926       bool isSExt;
927       EVT FromVT(MVT::Other);
928       if (NumZeroBits) {
929         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
930         isSExt = false;
931       } else if (NumSignBits > 1) {
932         FromVT =
933             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
934         isSExt = true;
935       } else {
936         continue;
937       }
938       // Add an assertion node.
939       assert(FromVT != MVT::Other);
940       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
941                              RegisterVT, P, DAG.getValueType(FromVT));
942     }
943 
944     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
945                                      RegisterVT, ValueVT, V, Chain, CallConv);
946     Part += NumRegs;
947     Parts.clear();
948   }
949 
950   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
951 }
952 
953 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
954                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
955                                  const Value *V,
956                                  ISD::NodeType PreferredExtendType) const {
957   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
958   ISD::NodeType ExtendKind = PreferredExtendType;
959 
960   // Get the list of the values's legal parts.
961   unsigned NumRegs = Regs.size();
962   SmallVector<SDValue, 8> Parts(NumRegs);
963   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
964     unsigned NumParts = RegCount[Value];
965 
966     MVT RegisterVT = isABIMangled()
967                          ? TLI.getRegisterTypeForCallingConv(
968                                *DAG.getContext(), *CallConv, RegVTs[Value])
969                          : RegVTs[Value];
970 
971     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
972       ExtendKind = ISD::ZERO_EXTEND;
973 
974     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
975                    NumParts, RegisterVT, V, CallConv, ExtendKind);
976     Part += NumParts;
977   }
978 
979   // Copy the parts into the registers.
980   SmallVector<SDValue, 8> Chains(NumRegs);
981   for (unsigned i = 0; i != NumRegs; ++i) {
982     SDValue Part;
983     if (!Glue) {
984       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
985     } else {
986       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
987       *Glue = Part.getValue(1);
988     }
989 
990     Chains[i] = Part.getValue(0);
991   }
992 
993   if (NumRegs == 1 || Glue)
994     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
995     // flagged to it. That is the CopyToReg nodes and the user are considered
996     // a single scheduling unit. If we create a TokenFactor and return it as
997     // chain, then the TokenFactor is both a predecessor (operand) of the
998     // user as well as a successor (the TF operands are flagged to the user).
999     // c1, f1 = CopyToReg
1000     // c2, f2 = CopyToReg
1001     // c3     = TokenFactor c1, c2
1002     // ...
1003     //        = op c3, ..., f2
1004     Chain = Chains[NumRegs-1];
1005   else
1006     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1007 }
1008 
1009 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1010                                         unsigned MatchingIdx, const SDLoc &dl,
1011                                         SelectionDAG &DAG,
1012                                         std::vector<SDValue> &Ops) const {
1013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1014 
1015   InlineAsm::Flag Flag(Code, Regs.size());
1016   if (HasMatching)
1017     Flag.setMatchingOp(MatchingIdx);
1018   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1019     // Put the register class of the virtual registers in the flag word.  That
1020     // way, later passes can recompute register class constraints for inline
1021     // assembly as well as normal instructions.
1022     // Don't do this for tied operands that can use the regclass information
1023     // from the def.
1024     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1025     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1026     Flag.setRegClass(RC->getID());
1027   }
1028 
1029   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1030   Ops.push_back(Res);
1031 
1032   if (Code == InlineAsm::Kind::Clobber) {
1033     // Clobbers should always have a 1:1 mapping with registers, and may
1034     // reference registers that have illegal (e.g. vector) types. Hence, we
1035     // shouldn't try to apply any sort of splitting logic to them.
1036     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1037            "No 1:1 mapping from clobbers to regs?");
1038     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1039     (void)SP;
1040     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1041       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1042       assert(
1043           (Regs[I] != SP ||
1044            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1045           "If we clobbered the stack pointer, MFI should know about it.");
1046     }
1047     return;
1048   }
1049 
1050   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1051     MVT RegisterVT = RegVTs[Value];
1052     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1053                                            RegisterVT);
1054     for (unsigned i = 0; i != NumRegs; ++i) {
1055       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1056       unsigned TheReg = Regs[Reg++];
1057       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1058     }
1059   }
1060 }
1061 
1062 SmallVector<std::pair<unsigned, TypeSize>, 4>
1063 RegsForValue::getRegsAndSizes() const {
1064   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1065   unsigned I = 0;
1066   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1067     unsigned RegCount = std::get<0>(CountAndVT);
1068     MVT RegisterVT = std::get<1>(CountAndVT);
1069     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1070     for (unsigned E = I + RegCount; I != E; ++I)
1071       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1072   }
1073   return OutVec;
1074 }
1075 
1076 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1077                                AssumptionCache *ac,
1078                                const TargetLibraryInfo *li) {
1079   AA = aa;
1080   AC = ac;
1081   GFI = gfi;
1082   LibInfo = li;
1083   Context = DAG.getContext();
1084   LPadToCallSiteMap.clear();
1085   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1086   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1087       *DAG.getMachineFunction().getFunction().getParent());
1088 }
1089 
1090 void SelectionDAGBuilder::clear() {
1091   NodeMap.clear();
1092   UnusedArgNodeMap.clear();
1093   PendingLoads.clear();
1094   PendingExports.clear();
1095   PendingConstrainedFP.clear();
1096   PendingConstrainedFPStrict.clear();
1097   CurInst = nullptr;
1098   HasTailCall = false;
1099   SDNodeOrder = LowestSDNodeOrder;
1100   StatepointLowering.clear();
1101 }
1102 
1103 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1104   DanglingDebugInfoMap.clear();
1105 }
1106 
1107 // Update DAG root to include dependencies on Pending chains.
1108 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1109   SDValue Root = DAG.getRoot();
1110 
1111   if (Pending.empty())
1112     return Root;
1113 
1114   // Add current root to PendingChains, unless we already indirectly
1115   // depend on it.
1116   if (Root.getOpcode() != ISD::EntryToken) {
1117     unsigned i = 0, e = Pending.size();
1118     for (; i != e; ++i) {
1119       assert(Pending[i].getNode()->getNumOperands() > 1);
1120       if (Pending[i].getNode()->getOperand(0) == Root)
1121         break;  // Don't add the root if we already indirectly depend on it.
1122     }
1123 
1124     if (i == e)
1125       Pending.push_back(Root);
1126   }
1127 
1128   if (Pending.size() == 1)
1129     Root = Pending[0];
1130   else
1131     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1132 
1133   DAG.setRoot(Root);
1134   Pending.clear();
1135   return Root;
1136 }
1137 
1138 SDValue SelectionDAGBuilder::getMemoryRoot() {
1139   return updateRoot(PendingLoads);
1140 }
1141 
1142 SDValue SelectionDAGBuilder::getRoot() {
1143   // Chain up all pending constrained intrinsics together with all
1144   // pending loads, by simply appending them to PendingLoads and
1145   // then calling getMemoryRoot().
1146   PendingLoads.reserve(PendingLoads.size() +
1147                        PendingConstrainedFP.size() +
1148                        PendingConstrainedFPStrict.size());
1149   PendingLoads.append(PendingConstrainedFP.begin(),
1150                       PendingConstrainedFP.end());
1151   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1152                       PendingConstrainedFPStrict.end());
1153   PendingConstrainedFP.clear();
1154   PendingConstrainedFPStrict.clear();
1155   return getMemoryRoot();
1156 }
1157 
1158 SDValue SelectionDAGBuilder::getControlRoot() {
1159   // We need to emit pending fpexcept.strict constrained intrinsics,
1160   // so append them to the PendingExports list.
1161   PendingExports.append(PendingConstrainedFPStrict.begin(),
1162                         PendingConstrainedFPStrict.end());
1163   PendingConstrainedFPStrict.clear();
1164   return updateRoot(PendingExports);
1165 }
1166 
1167 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1168                                              DILocalVariable *Variable,
1169                                              DIExpression *Expression,
1170                                              DebugLoc DL) {
1171   assert(Variable && "Missing variable");
1172 
1173   // Check if address has undef value.
1174   if (!Address || isa<UndefValue>(Address) ||
1175       (Address->use_empty() && !isa<Argument>(Address))) {
1176     LLVM_DEBUG(
1177         dbgs()
1178         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1179     return;
1180   }
1181 
1182   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1183 
1184   SDValue &N = NodeMap[Address];
1185   if (!N.getNode() && isa<Argument>(Address))
1186     // Check unused arguments map.
1187     N = UnusedArgNodeMap[Address];
1188   SDDbgValue *SDV;
1189   if (N.getNode()) {
1190     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1191       Address = BCI->getOperand(0);
1192     // Parameters are handled specially.
1193     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1194     if (IsParameter && FINode) {
1195       // Byval parameter. We have a frame index at this point.
1196       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1197                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1198     } else if (isa<Argument>(Address)) {
1199       // Address is an argument, so try to emit its dbg value using
1200       // virtual register info from the FuncInfo.ValueMap.
1201       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1202                                FuncArgumentDbgValueKind::Declare, N);
1203       return;
1204     } else {
1205       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1206                             true, DL, SDNodeOrder);
1207     }
1208     DAG.AddDbgValue(SDV, IsParameter);
1209   } else {
1210     // If Address is an argument then try to emit its dbg value using
1211     // virtual register info from the FuncInfo.ValueMap.
1212     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1213                                   FuncArgumentDbgValueKind::Declare, N)) {
1214       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1215                         << " (could not emit func-arg dbg_value)\n");
1216     }
1217   }
1218   return;
1219 }
1220 
1221 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1222   // Add SDDbgValue nodes for any var locs here. Do so before updating
1223   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1224   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1225     // Add SDDbgValue nodes for any var locs here. Do so before updating
1226     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1227     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1228          It != End; ++It) {
1229       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1230       dropDanglingDebugInfo(Var, It->Expr);
1231       if (It->Values.isKillLocation(It->Expr)) {
1232         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1233         continue;
1234       }
1235       SmallVector<Value *> Values(It->Values.location_ops());
1236       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1237                             It->Values.hasArgList())) {
1238         SmallVector<Value *, 4> Vals;
1239         for (Value *V : It->Values.location_ops())
1240           Vals.push_back(V);
1241         addDanglingDebugInfo(Vals,
1242                              FnVarLocs->getDILocalVariable(It->VariableID),
1243                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1244       }
1245     }
1246   }
1247 
1248   // We must skip DbgVariableRecords if they've already been processed above as
1249   // we have just emitted the debug values resulting from assignment tracking
1250   // analysis, making any existing DbgVariableRecords redundant (and probably
1251   // less correct). We still need to process DbgLabelRecords. This does sink
1252   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1253   // be important as it does so deterministcally and ordering between
1254   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1255   // printing).
1256   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1257   // Is there is any debug-info attached to this instruction, in the form of
1258   // DbgRecord non-instruction debug-info records.
1259   for (DbgRecord &DR : I.getDbgRecordRange()) {
1260     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1261       assert(DLR->getLabel() && "Missing label");
1262       SDDbgLabel *SDV =
1263           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1264       DAG.AddDbgLabel(SDV);
1265       continue;
1266     }
1267 
1268     if (SkipDbgVariableRecords)
1269       continue;
1270     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1271     DILocalVariable *Variable = DVR.getVariable();
1272     DIExpression *Expression = DVR.getExpression();
1273     dropDanglingDebugInfo(Variable, Expression);
1274 
1275     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1276       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1277         continue;
1278       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1279                         << "\n");
1280       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1281                          DVR.getDebugLoc());
1282       continue;
1283     }
1284 
1285     // A DbgVariableRecord with no locations is a kill location.
1286     SmallVector<Value *, 4> Values(DVR.location_ops());
1287     if (Values.empty()) {
1288       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1289                            SDNodeOrder);
1290       continue;
1291     }
1292 
1293     // A DbgVariableRecord with an undef or absent location is also a kill
1294     // location.
1295     if (llvm::any_of(Values,
1296                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1297       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1298                            SDNodeOrder);
1299       continue;
1300     }
1301 
1302     bool IsVariadic = DVR.hasArgList();
1303     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1304                           SDNodeOrder, IsVariadic)) {
1305       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1306                            DVR.getDebugLoc(), SDNodeOrder);
1307     }
1308   }
1309 }
1310 
1311 void SelectionDAGBuilder::visit(const Instruction &I) {
1312   visitDbgInfo(I);
1313 
1314   // Set up outgoing PHI node register values before emitting the terminator.
1315   if (I.isTerminator()) {
1316     HandlePHINodesInSuccessorBlocks(I.getParent());
1317   }
1318 
1319   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1320   if (!isa<DbgInfoIntrinsic>(I))
1321     ++SDNodeOrder;
1322 
1323   CurInst = &I;
1324 
1325   // Set inserted listener only if required.
1326   bool NodeInserted = false;
1327   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1328   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1329   if (PCSectionsMD) {
1330     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1331         DAG, [&](SDNode *) { NodeInserted = true; });
1332   }
1333 
1334   visit(I.getOpcode(), I);
1335 
1336   if (!I.isTerminator() && !HasTailCall &&
1337       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1338     CopyToExportRegsIfNeeded(&I);
1339 
1340   // Handle metadata.
1341   if (PCSectionsMD) {
1342     auto It = NodeMap.find(&I);
1343     if (It != NodeMap.end()) {
1344       DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1345     } else if (NodeInserted) {
1346       // This should not happen; if it does, don't let it go unnoticed so we can
1347       // fix it. Relevant visit*() function is probably missing a setValue().
1348       errs() << "warning: loosing !pcsections metadata ["
1349              << I.getModule()->getName() << "]\n";
1350       LLVM_DEBUG(I.dump());
1351       assert(false);
1352     }
1353   }
1354 
1355   CurInst = nullptr;
1356 }
1357 
1358 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1359   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1360 }
1361 
1362 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1363   // Note: this doesn't use InstVisitor, because it has to work with
1364   // ConstantExpr's in addition to instructions.
1365   switch (Opcode) {
1366   default: llvm_unreachable("Unknown instruction type encountered!");
1367     // Build the switch statement using the Instruction.def file.
1368 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1369     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1370 #include "llvm/IR/Instruction.def"
1371   }
1372 }
1373 
1374 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1375                                             DILocalVariable *Variable,
1376                                             DebugLoc DL, unsigned Order,
1377                                             SmallVectorImpl<Value *> &Values,
1378                                             DIExpression *Expression) {
1379   // For variadic dbg_values we will now insert an undef.
1380   // FIXME: We can potentially recover these!
1381   SmallVector<SDDbgOperand, 2> Locs;
1382   for (const Value *V : Values) {
1383     auto *Undef = UndefValue::get(V->getType());
1384     Locs.push_back(SDDbgOperand::fromConst(Undef));
1385   }
1386   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1387                                         /*IsIndirect=*/false, DL, Order,
1388                                         /*IsVariadic=*/true);
1389   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1390   return true;
1391 }
1392 
1393 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1394                                                DILocalVariable *Var,
1395                                                DIExpression *Expr,
1396                                                bool IsVariadic, DebugLoc DL,
1397                                                unsigned Order) {
1398   if (IsVariadic) {
1399     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1400     return;
1401   }
1402   // TODO: Dangling debug info will eventually either be resolved or produce
1403   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1404   // between the original dbg.value location and its resolved DBG_VALUE,
1405   // which we should ideally fill with an extra Undef DBG_VALUE.
1406   assert(Values.size() == 1);
1407   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1408 }
1409 
1410 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1411                                                 const DIExpression *Expr) {
1412   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1413     DIVariable *DanglingVariable = DDI.getVariable();
1414     DIExpression *DanglingExpr = DDI.getExpression();
1415     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1416       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1417                         << printDDI(nullptr, DDI) << "\n");
1418       return true;
1419     }
1420     return false;
1421   };
1422 
1423   for (auto &DDIMI : DanglingDebugInfoMap) {
1424     DanglingDebugInfoVector &DDIV = DDIMI.second;
1425 
1426     // If debug info is to be dropped, run it through final checks to see
1427     // whether it can be salvaged.
1428     for (auto &DDI : DDIV)
1429       if (isMatchingDbgValue(DDI))
1430         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1431 
1432     erase_if(DDIV, isMatchingDbgValue);
1433   }
1434 }
1435 
1436 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1437 // generate the debug data structures now that we've seen its definition.
1438 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1439                                                    SDValue Val) {
1440   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1441   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1442     return;
1443 
1444   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1445   for (auto &DDI : DDIV) {
1446     DebugLoc DL = DDI.getDebugLoc();
1447     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1448     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1449     DILocalVariable *Variable = DDI.getVariable();
1450     DIExpression *Expr = DDI.getExpression();
1451     assert(Variable->isValidLocationForIntrinsic(DL) &&
1452            "Expected inlined-at fields to agree");
1453     SDDbgValue *SDV;
1454     if (Val.getNode()) {
1455       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1456       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1457       // we couldn't resolve it directly when examining the DbgValue intrinsic
1458       // in the first place we should not be more successful here). Unless we
1459       // have some test case that prove this to be correct we should avoid
1460       // calling EmitFuncArgumentDbgValue here.
1461       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1462                                     FuncArgumentDbgValueKind::Value, Val)) {
1463         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1464                           << printDDI(V, DDI) << "\n");
1465         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1466         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1467         // inserted after the definition of Val when emitting the instructions
1468         // after ISel. An alternative could be to teach
1469         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1470         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1471                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1472                    << ValSDNodeOrder << "\n");
1473         SDV = getDbgValue(Val, Variable, Expr, DL,
1474                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1475         DAG.AddDbgValue(SDV, false);
1476       } else
1477         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1478                           << printDDI(V, DDI)
1479                           << " in EmitFuncArgumentDbgValue\n");
1480     } else {
1481       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1482                         << "\n");
1483       auto Undef = UndefValue::get(V->getType());
1484       auto SDV =
1485           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1486       DAG.AddDbgValue(SDV, false);
1487     }
1488   }
1489   DDIV.clear();
1490 }
1491 
1492 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1493                                                     DanglingDebugInfo &DDI) {
1494   // TODO: For the variadic implementation, instead of only checking the fail
1495   // state of `handleDebugValue`, we need know specifically which values were
1496   // invalid, so that we attempt to salvage only those values when processing
1497   // a DIArgList.
1498   const Value *OrigV = V;
1499   DILocalVariable *Var = DDI.getVariable();
1500   DIExpression *Expr = DDI.getExpression();
1501   DebugLoc DL = DDI.getDebugLoc();
1502   unsigned SDOrder = DDI.getSDNodeOrder();
1503 
1504   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1505   // that DW_OP_stack_value is desired.
1506   bool StackValue = true;
1507 
1508   // Can this Value can be encoded without any further work?
1509   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1510     return;
1511 
1512   // Attempt to salvage back through as many instructions as possible. Bail if
1513   // a non-instruction is seen, such as a constant expression or global
1514   // variable. FIXME: Further work could recover those too.
1515   while (isa<Instruction>(V)) {
1516     const Instruction &VAsInst = *cast<const Instruction>(V);
1517     // Temporary "0", awaiting real implementation.
1518     SmallVector<uint64_t, 16> Ops;
1519     SmallVector<Value *, 4> AdditionalValues;
1520     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1521                              Expr->getNumLocationOperands(), Ops,
1522                              AdditionalValues);
1523     // If we cannot salvage any further, and haven't yet found a suitable debug
1524     // expression, bail out.
1525     if (!V)
1526       break;
1527 
1528     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1529     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1530     // here for variadic dbg_values, remove that condition.
1531     if (!AdditionalValues.empty())
1532       break;
1533 
1534     // New value and expr now represent this debuginfo.
1535     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1536 
1537     // Some kind of simplification occurred: check whether the operand of the
1538     // salvaged debug expression can be encoded in this DAG.
1539     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1540       LLVM_DEBUG(
1541           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1542                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1543       return;
1544     }
1545   }
1546 
1547   // This was the final opportunity to salvage this debug information, and it
1548   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1549   // any earlier variable location.
1550   assert(OrigV && "V shouldn't be null");
1551   auto *Undef = UndefValue::get(OrigV->getType());
1552   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1553   DAG.AddDbgValue(SDV, false);
1554   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1555                     << printDDI(OrigV, DDI) << "\n");
1556 }
1557 
1558 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1559                                                DIExpression *Expr,
1560                                                DebugLoc DbgLoc,
1561                                                unsigned Order) {
1562   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1563   DIExpression *NewExpr =
1564       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1565   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1566                    /*IsVariadic*/ false);
1567 }
1568 
1569 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1570                                            DILocalVariable *Var,
1571                                            DIExpression *Expr, DebugLoc DbgLoc,
1572                                            unsigned Order, bool IsVariadic) {
1573   if (Values.empty())
1574     return true;
1575 
1576   // Filter EntryValue locations out early.
1577   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1578     return true;
1579 
1580   SmallVector<SDDbgOperand> LocationOps;
1581   SmallVector<SDNode *> Dependencies;
1582   for (const Value *V : Values) {
1583     // Constant value.
1584     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1585         isa<ConstantPointerNull>(V)) {
1586       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1587       continue;
1588     }
1589 
1590     // Look through IntToPtr constants.
1591     if (auto *CE = dyn_cast<ConstantExpr>(V))
1592       if (CE->getOpcode() == Instruction::IntToPtr) {
1593         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1594         continue;
1595       }
1596 
1597     // If the Value is a frame index, we can create a FrameIndex debug value
1598     // without relying on the DAG at all.
1599     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1600       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1601       if (SI != FuncInfo.StaticAllocaMap.end()) {
1602         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1603         continue;
1604       }
1605     }
1606 
1607     // Do not use getValue() in here; we don't want to generate code at
1608     // this point if it hasn't been done yet.
1609     SDValue N = NodeMap[V];
1610     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1611       N = UnusedArgNodeMap[V];
1612     if (N.getNode()) {
1613       // Only emit func arg dbg value for non-variadic dbg.values for now.
1614       if (!IsVariadic &&
1615           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1616                                    FuncArgumentDbgValueKind::Value, N))
1617         return true;
1618       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1619         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1620         // describe stack slot locations.
1621         //
1622         // Consider "int x = 0; int *px = &x;". There are two kinds of
1623         // interesting debug values here after optimization:
1624         //
1625         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1626         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1627         //
1628         // Both describe the direct values of their associated variables.
1629         Dependencies.push_back(N.getNode());
1630         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1631         continue;
1632       }
1633       LocationOps.emplace_back(
1634           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1635       continue;
1636     }
1637 
1638     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1639     // Special rules apply for the first dbg.values of parameter variables in a
1640     // function. Identify them by the fact they reference Argument Values, that
1641     // they're parameters, and they are parameters of the current function. We
1642     // need to let them dangle until they get an SDNode.
1643     bool IsParamOfFunc =
1644         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1645     if (IsParamOfFunc)
1646       return false;
1647 
1648     // The value is not used in this block yet (or it would have an SDNode).
1649     // We still want the value to appear for the user if possible -- if it has
1650     // an associated VReg, we can refer to that instead.
1651     auto VMI = FuncInfo.ValueMap.find(V);
1652     if (VMI != FuncInfo.ValueMap.end()) {
1653       unsigned Reg = VMI->second;
1654       // If this is a PHI node, it may be split up into several MI PHI nodes
1655       // (in FunctionLoweringInfo::set).
1656       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1657                        V->getType(), std::nullopt);
1658       if (RFV.occupiesMultipleRegs()) {
1659         // FIXME: We could potentially support variadic dbg_values here.
1660         if (IsVariadic)
1661           return false;
1662         unsigned Offset = 0;
1663         unsigned BitsToDescribe = 0;
1664         if (auto VarSize = Var->getSizeInBits())
1665           BitsToDescribe = *VarSize;
1666         if (auto Fragment = Expr->getFragmentInfo())
1667           BitsToDescribe = Fragment->SizeInBits;
1668         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1669           // Bail out if all bits are described already.
1670           if (Offset >= BitsToDescribe)
1671             break;
1672           // TODO: handle scalable vectors.
1673           unsigned RegisterSize = RegAndSize.second;
1674           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1675                                       ? BitsToDescribe - Offset
1676                                       : RegisterSize;
1677           auto FragmentExpr = DIExpression::createFragmentExpression(
1678               Expr, Offset, FragmentSize);
1679           if (!FragmentExpr)
1680             continue;
1681           SDDbgValue *SDV = DAG.getVRegDbgValue(
1682               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, SDNodeOrder);
1683           DAG.AddDbgValue(SDV, false);
1684           Offset += RegisterSize;
1685         }
1686         return true;
1687       }
1688       // We can use simple vreg locations for variadic dbg_values as well.
1689       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1690       continue;
1691     }
1692     // We failed to create a SDDbgOperand for V.
1693     return false;
1694   }
1695 
1696   // We have created a SDDbgOperand for each Value in Values.
1697   // Should use Order instead of SDNodeOrder?
1698   assert(!LocationOps.empty());
1699   SDDbgValue *SDV = DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1700                                         /*IsIndirect=*/false, DbgLoc,
1701                                         SDNodeOrder, IsVariadic);
1702   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1703   return true;
1704 }
1705 
1706 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1707   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1708   for (auto &Pair : DanglingDebugInfoMap)
1709     for (auto &DDI : Pair.second)
1710       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1711   clearDanglingDebugInfo();
1712 }
1713 
1714 /// getCopyFromRegs - If there was virtual register allocated for the value V
1715 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1716 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1717   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1718   SDValue Result;
1719 
1720   if (It != FuncInfo.ValueMap.end()) {
1721     Register InReg = It->second;
1722 
1723     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1724                      DAG.getDataLayout(), InReg, Ty,
1725                      std::nullopt); // This is not an ABI copy.
1726     SDValue Chain = DAG.getEntryNode();
1727     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1728                                  V);
1729     resolveDanglingDebugInfo(V, Result);
1730   }
1731 
1732   return Result;
1733 }
1734 
1735 /// getValue - Return an SDValue for the given Value.
1736 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1737   // If we already have an SDValue for this value, use it. It's important
1738   // to do this first, so that we don't create a CopyFromReg if we already
1739   // have a regular SDValue.
1740   SDValue &N = NodeMap[V];
1741   if (N.getNode()) return N;
1742 
1743   // If there's a virtual register allocated and initialized for this
1744   // value, use it.
1745   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1746     return copyFromReg;
1747 
1748   // Otherwise create a new SDValue and remember it.
1749   SDValue Val = getValueImpl(V);
1750   NodeMap[V] = Val;
1751   resolveDanglingDebugInfo(V, Val);
1752   return Val;
1753 }
1754 
1755 /// getNonRegisterValue - Return an SDValue for the given Value, but
1756 /// don't look in FuncInfo.ValueMap for a virtual register.
1757 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1758   // If we already have an SDValue for this value, use it.
1759   SDValue &N = NodeMap[V];
1760   if (N.getNode()) {
1761     if (isIntOrFPConstant(N)) {
1762       // Remove the debug location from the node as the node is about to be used
1763       // in a location which may differ from the original debug location.  This
1764       // is relevant to Constant and ConstantFP nodes because they can appear
1765       // as constant expressions inside PHI nodes.
1766       N->setDebugLoc(DebugLoc());
1767     }
1768     return N;
1769   }
1770 
1771   // Otherwise create a new SDValue and remember it.
1772   SDValue Val = getValueImpl(V);
1773   NodeMap[V] = Val;
1774   resolveDanglingDebugInfo(V, Val);
1775   return Val;
1776 }
1777 
1778 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1779 /// Create an SDValue for the given value.
1780 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1782 
1783   if (const Constant *C = dyn_cast<Constant>(V)) {
1784     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1785 
1786     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1787       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1788 
1789     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1790       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1791 
1792     if (isa<ConstantPointerNull>(C)) {
1793       unsigned AS = V->getType()->getPointerAddressSpace();
1794       return DAG.getConstant(0, getCurSDLoc(),
1795                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1796     }
1797 
1798     if (match(C, m_VScale()))
1799       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1800 
1801     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1802       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1803 
1804     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1805       return DAG.getUNDEF(VT);
1806 
1807     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1808       visit(CE->getOpcode(), *CE);
1809       SDValue N1 = NodeMap[V];
1810       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1811       return N1;
1812     }
1813 
1814     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1815       SmallVector<SDValue, 4> Constants;
1816       for (const Use &U : C->operands()) {
1817         SDNode *Val = getValue(U).getNode();
1818         // If the operand is an empty aggregate, there are no values.
1819         if (!Val) continue;
1820         // Add each leaf value from the operand to the Constants list
1821         // to form a flattened list of all the values.
1822         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1823           Constants.push_back(SDValue(Val, i));
1824       }
1825 
1826       return DAG.getMergeValues(Constants, getCurSDLoc());
1827     }
1828 
1829     if (const ConstantDataSequential *CDS =
1830           dyn_cast<ConstantDataSequential>(C)) {
1831       SmallVector<SDValue, 4> Ops;
1832       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1833         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1834         // Add each leaf value from the operand to the Constants list
1835         // to form a flattened list of all the values.
1836         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1837           Ops.push_back(SDValue(Val, i));
1838       }
1839 
1840       if (isa<ArrayType>(CDS->getType()))
1841         return DAG.getMergeValues(Ops, getCurSDLoc());
1842       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1843     }
1844 
1845     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1846       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1847              "Unknown struct or array constant!");
1848 
1849       SmallVector<EVT, 4> ValueVTs;
1850       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1851       unsigned NumElts = ValueVTs.size();
1852       if (NumElts == 0)
1853         return SDValue(); // empty struct
1854       SmallVector<SDValue, 4> Constants(NumElts);
1855       for (unsigned i = 0; i != NumElts; ++i) {
1856         EVT EltVT = ValueVTs[i];
1857         if (isa<UndefValue>(C))
1858           Constants[i] = DAG.getUNDEF(EltVT);
1859         else if (EltVT.isFloatingPoint())
1860           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1861         else
1862           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1863       }
1864 
1865       return DAG.getMergeValues(Constants, getCurSDLoc());
1866     }
1867 
1868     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1869       return DAG.getBlockAddress(BA, VT);
1870 
1871     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1872       return getValue(Equiv->getGlobalValue());
1873 
1874     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1875       return getValue(NC->getGlobalValue());
1876 
1877     if (VT == MVT::aarch64svcount) {
1878       assert(C->isNullValue() && "Can only zero this target type!");
1879       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1880                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1881     }
1882 
1883     VectorType *VecTy = cast<VectorType>(V->getType());
1884 
1885     // Now that we know the number and type of the elements, get that number of
1886     // elements into the Ops array based on what kind of constant it is.
1887     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1888       SmallVector<SDValue, 16> Ops;
1889       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1890       for (unsigned i = 0; i != NumElements; ++i)
1891         Ops.push_back(getValue(CV->getOperand(i)));
1892 
1893       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1894     }
1895 
1896     if (isa<ConstantAggregateZero>(C)) {
1897       EVT EltVT =
1898           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1899 
1900       SDValue Op;
1901       if (EltVT.isFloatingPoint())
1902         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1903       else
1904         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1905 
1906       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1907     }
1908 
1909     llvm_unreachable("Unknown vector constant");
1910   }
1911 
1912   // If this is a static alloca, generate it as the frameindex instead of
1913   // computation.
1914   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1915     DenseMap<const AllocaInst*, int>::iterator SI =
1916       FuncInfo.StaticAllocaMap.find(AI);
1917     if (SI != FuncInfo.StaticAllocaMap.end())
1918       return DAG.getFrameIndex(
1919           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1920   }
1921 
1922   // If this is an instruction which fast-isel has deferred, select it now.
1923   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1924     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1925 
1926     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1927                      Inst->getType(), std::nullopt);
1928     SDValue Chain = DAG.getEntryNode();
1929     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1930   }
1931 
1932   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1933     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1934 
1935   if (const auto *BB = dyn_cast<BasicBlock>(V))
1936     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1937 
1938   llvm_unreachable("Can't get register for value!");
1939 }
1940 
1941 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1942   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1943   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1944   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1945   bool IsSEH = isAsynchronousEHPersonality(Pers);
1946   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1947   if (!IsSEH)
1948     CatchPadMBB->setIsEHScopeEntry();
1949   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1950   if (IsMSVCCXX || IsCoreCLR)
1951     CatchPadMBB->setIsEHFuncletEntry();
1952 }
1953 
1954 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1955   // Update machine-CFG edge.
1956   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1957   FuncInfo.MBB->addSuccessor(TargetMBB);
1958   TargetMBB->setIsEHCatchretTarget(true);
1959   DAG.getMachineFunction().setHasEHCatchret(true);
1960 
1961   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1962   bool IsSEH = isAsynchronousEHPersonality(Pers);
1963   if (IsSEH) {
1964     // If this is not a fall-through branch or optimizations are switched off,
1965     // emit the branch.
1966     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1967         TM.getOptLevel() == CodeGenOptLevel::None)
1968       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1969                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1970     return;
1971   }
1972 
1973   // Figure out the funclet membership for the catchret's successor.
1974   // This will be used by the FuncletLayout pass to determine how to order the
1975   // BB's.
1976   // A 'catchret' returns to the outer scope's color.
1977   Value *ParentPad = I.getCatchSwitchParentPad();
1978   const BasicBlock *SuccessorColor;
1979   if (isa<ConstantTokenNone>(ParentPad))
1980     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1981   else
1982     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1983   assert(SuccessorColor && "No parent funclet for catchret!");
1984   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1985   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1986 
1987   // Create the terminator node.
1988   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
1989                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
1990                             DAG.getBasicBlock(SuccessorColorMBB));
1991   DAG.setRoot(Ret);
1992 }
1993 
1994 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
1995   // Don't emit any special code for the cleanuppad instruction. It just marks
1996   // the start of an EH scope/funclet.
1997   FuncInfo.MBB->setIsEHScopeEntry();
1998   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1999   if (Pers != EHPersonality::Wasm_CXX) {
2000     FuncInfo.MBB->setIsEHFuncletEntry();
2001     FuncInfo.MBB->setIsCleanupFuncletEntry();
2002   }
2003 }
2004 
2005 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2006 // not match, it is OK to add only the first unwind destination catchpad to the
2007 // successors, because there will be at least one invoke instruction within the
2008 // catch scope that points to the next unwind destination, if one exists, so
2009 // CFGSort cannot mess up with BB sorting order.
2010 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2011 // call within them, and catchpads only consisting of 'catch (...)' have a
2012 // '__cxa_end_catch' call within them, both of which generate invokes in case
2013 // the next unwind destination exists, i.e., the next unwind destination is not
2014 // the caller.)
2015 //
2016 // Having at most one EH pad successor is also simpler and helps later
2017 // transformations.
2018 //
2019 // For example,
2020 // current:
2021 //   invoke void @foo to ... unwind label %catch.dispatch
2022 // catch.dispatch:
2023 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2024 // catch.start:
2025 //   ...
2026 //   ... in this BB or some other child BB dominated by this BB there will be an
2027 //   invoke that points to 'next' BB as an unwind destination
2028 //
2029 // next: ; We don't need to add this to 'current' BB's successor
2030 //   ...
2031 static void findWasmUnwindDestinations(
2032     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2033     BranchProbability Prob,
2034     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2035         &UnwindDests) {
2036   while (EHPadBB) {
2037     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2038     if (isa<CleanupPadInst>(Pad)) {
2039       // Stop on cleanup pads.
2040       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2041       UnwindDests.back().first->setIsEHScopeEntry();
2042       break;
2043     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2044       // Add the catchpad handlers to the possible destinations. We don't
2045       // continue to the unwind destination of the catchswitch for wasm.
2046       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2047         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2048         UnwindDests.back().first->setIsEHScopeEntry();
2049       }
2050       break;
2051     } else {
2052       continue;
2053     }
2054   }
2055 }
2056 
2057 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2058 /// many places it could ultimately go. In the IR, we have a single unwind
2059 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2060 /// This function skips over imaginary basic blocks that hold catchswitch
2061 /// instructions, and finds all the "real" machine
2062 /// basic block destinations. As those destinations may not be successors of
2063 /// EHPadBB, here we also calculate the edge probability to those destinations.
2064 /// The passed-in Prob is the edge probability to EHPadBB.
2065 static void findUnwindDestinations(
2066     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2067     BranchProbability Prob,
2068     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2069         &UnwindDests) {
2070   EHPersonality Personality =
2071     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2072   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2073   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2074   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2075   bool IsSEH = isAsynchronousEHPersonality(Personality);
2076 
2077   if (IsWasmCXX) {
2078     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2079     assert(UnwindDests.size() <= 1 &&
2080            "There should be at most one unwind destination for wasm");
2081     return;
2082   }
2083 
2084   while (EHPadBB) {
2085     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2086     BasicBlock *NewEHPadBB = nullptr;
2087     if (isa<LandingPadInst>(Pad)) {
2088       // Stop on landingpads. They are not funclets.
2089       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2090       break;
2091     } else if (isa<CleanupPadInst>(Pad)) {
2092       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2093       // personalities.
2094       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2095       UnwindDests.back().first->setIsEHScopeEntry();
2096       UnwindDests.back().first->setIsEHFuncletEntry();
2097       break;
2098     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2099       // Add the catchpad handlers to the possible destinations.
2100       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2101         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2102         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2103         if (IsMSVCCXX || IsCoreCLR)
2104           UnwindDests.back().first->setIsEHFuncletEntry();
2105         if (!IsSEH)
2106           UnwindDests.back().first->setIsEHScopeEntry();
2107       }
2108       NewEHPadBB = CatchSwitch->getUnwindDest();
2109     } else {
2110       continue;
2111     }
2112 
2113     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2114     if (BPI && NewEHPadBB)
2115       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2116     EHPadBB = NewEHPadBB;
2117   }
2118 }
2119 
2120 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2121   // Update successor info.
2122   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2123   auto UnwindDest = I.getUnwindDest();
2124   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2125   BranchProbability UnwindDestProb =
2126       (BPI && UnwindDest)
2127           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2128           : BranchProbability::getZero();
2129   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2130   for (auto &UnwindDest : UnwindDests) {
2131     UnwindDest.first->setIsEHPad();
2132     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2133   }
2134   FuncInfo.MBB->normalizeSuccProbs();
2135 
2136   // Create the terminator node.
2137   SDValue Ret =
2138       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2139   DAG.setRoot(Ret);
2140 }
2141 
2142 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2143   report_fatal_error("visitCatchSwitch not yet implemented!");
2144 }
2145 
2146 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2147   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2148   auto &DL = DAG.getDataLayout();
2149   SDValue Chain = getControlRoot();
2150   SmallVector<ISD::OutputArg, 8> Outs;
2151   SmallVector<SDValue, 8> OutVals;
2152 
2153   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2154   // lower
2155   //
2156   //   %val = call <ty> @llvm.experimental.deoptimize()
2157   //   ret <ty> %val
2158   //
2159   // differently.
2160   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2161     LowerDeoptimizingReturn();
2162     return;
2163   }
2164 
2165   if (!FuncInfo.CanLowerReturn) {
2166     unsigned DemoteReg = FuncInfo.DemoteRegister;
2167     const Function *F = I.getParent()->getParent();
2168 
2169     // Emit a store of the return value through the virtual register.
2170     // Leave Outs empty so that LowerReturn won't try to load return
2171     // registers the usual way.
2172     SmallVector<EVT, 1> PtrValueVTs;
2173     ComputeValueVTs(TLI, DL,
2174                     PointerType::get(F->getContext(),
2175                                      DAG.getDataLayout().getAllocaAddrSpace()),
2176                     PtrValueVTs);
2177 
2178     SDValue RetPtr =
2179         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2180     SDValue RetOp = getValue(I.getOperand(0));
2181 
2182     SmallVector<EVT, 4> ValueVTs, MemVTs;
2183     SmallVector<uint64_t, 4> Offsets;
2184     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2185                     &Offsets, 0);
2186     unsigned NumValues = ValueVTs.size();
2187 
2188     SmallVector<SDValue, 4> Chains(NumValues);
2189     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2190     for (unsigned i = 0; i != NumValues; ++i) {
2191       // An aggregate return value cannot wrap around the address space, so
2192       // offsets to its parts don't wrap either.
2193       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2194                                            TypeSize::getFixed(Offsets[i]));
2195 
2196       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2197       if (MemVTs[i] != ValueVTs[i])
2198         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2199       Chains[i] = DAG.getStore(
2200           Chain, getCurSDLoc(), Val,
2201           // FIXME: better loc info would be nice.
2202           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2203           commonAlignment(BaseAlign, Offsets[i]));
2204     }
2205 
2206     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2207                         MVT::Other, Chains);
2208   } else if (I.getNumOperands() != 0) {
2209     SmallVector<EVT, 4> ValueVTs;
2210     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2211     unsigned NumValues = ValueVTs.size();
2212     if (NumValues) {
2213       SDValue RetOp = getValue(I.getOperand(0));
2214 
2215       const Function *F = I.getParent()->getParent();
2216 
2217       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2218           I.getOperand(0)->getType(), F->getCallingConv(),
2219           /*IsVarArg*/ false, DL);
2220 
2221       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2222       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2223         ExtendKind = ISD::SIGN_EXTEND;
2224       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2225         ExtendKind = ISD::ZERO_EXTEND;
2226 
2227       LLVMContext &Context = F->getContext();
2228       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2229 
2230       for (unsigned j = 0; j != NumValues; ++j) {
2231         EVT VT = ValueVTs[j];
2232 
2233         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2234           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2235 
2236         CallingConv::ID CC = F->getCallingConv();
2237 
2238         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2239         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2240         SmallVector<SDValue, 4> Parts(NumParts);
2241         getCopyToParts(DAG, getCurSDLoc(),
2242                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2243                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2244 
2245         // 'inreg' on function refers to return value
2246         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2247         if (RetInReg)
2248           Flags.setInReg();
2249 
2250         if (I.getOperand(0)->getType()->isPointerTy()) {
2251           Flags.setPointer();
2252           Flags.setPointerAddrSpace(
2253               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2254         }
2255 
2256         if (NeedsRegBlock) {
2257           Flags.setInConsecutiveRegs();
2258           if (j == NumValues - 1)
2259             Flags.setInConsecutiveRegsLast();
2260         }
2261 
2262         // Propagate extension type if any
2263         if (ExtendKind == ISD::SIGN_EXTEND)
2264           Flags.setSExt();
2265         else if (ExtendKind == ISD::ZERO_EXTEND)
2266           Flags.setZExt();
2267 
2268         for (unsigned i = 0; i < NumParts; ++i) {
2269           Outs.push_back(ISD::OutputArg(Flags,
2270                                         Parts[i].getValueType().getSimpleVT(),
2271                                         VT, /*isfixed=*/true, 0, 0));
2272           OutVals.push_back(Parts[i]);
2273         }
2274       }
2275     }
2276   }
2277 
2278   // Push in swifterror virtual register as the last element of Outs. This makes
2279   // sure swifterror virtual register will be returned in the swifterror
2280   // physical register.
2281   const Function *F = I.getParent()->getParent();
2282   if (TLI.supportSwiftError() &&
2283       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2284     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2285     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2286     Flags.setSwiftError();
2287     Outs.push_back(ISD::OutputArg(
2288         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2289         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2290     // Create SDNode for the swifterror virtual register.
2291     OutVals.push_back(
2292         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2293                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2294                         EVT(TLI.getPointerTy(DL))));
2295   }
2296 
2297   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2298   CallingConv::ID CallConv =
2299     DAG.getMachineFunction().getFunction().getCallingConv();
2300   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2301       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2302 
2303   // Verify that the target's LowerReturn behaved as expected.
2304   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2305          "LowerReturn didn't return a valid chain!");
2306 
2307   // Update the DAG with the new chain value resulting from return lowering.
2308   DAG.setRoot(Chain);
2309 }
2310 
2311 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2312 /// created for it, emit nodes to copy the value into the virtual
2313 /// registers.
2314 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2315   // Skip empty types
2316   if (V->getType()->isEmptyTy())
2317     return;
2318 
2319   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2320   if (VMI != FuncInfo.ValueMap.end()) {
2321     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2322            "Unused value assigned virtual registers!");
2323     CopyValueToVirtualRegister(V, VMI->second);
2324   }
2325 }
2326 
2327 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2328 /// the current basic block, add it to ValueMap now so that we'll get a
2329 /// CopyTo/FromReg.
2330 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2331   // No need to export constants.
2332   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2333 
2334   // Already exported?
2335   if (FuncInfo.isExportedInst(V)) return;
2336 
2337   Register Reg = FuncInfo.InitializeRegForValue(V);
2338   CopyValueToVirtualRegister(V, Reg);
2339 }
2340 
2341 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2342                                                      const BasicBlock *FromBB) {
2343   // The operands of the setcc have to be in this block.  We don't know
2344   // how to export them from some other block.
2345   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2346     // Can export from current BB.
2347     if (VI->getParent() == FromBB)
2348       return true;
2349 
2350     // Is already exported, noop.
2351     return FuncInfo.isExportedInst(V);
2352   }
2353 
2354   // If this is an argument, we can export it if the BB is the entry block or
2355   // if it is already exported.
2356   if (isa<Argument>(V)) {
2357     if (FromBB->isEntryBlock())
2358       return true;
2359 
2360     // Otherwise, can only export this if it is already exported.
2361     return FuncInfo.isExportedInst(V);
2362   }
2363 
2364   // Otherwise, constants can always be exported.
2365   return true;
2366 }
2367 
2368 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2369 BranchProbability
2370 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2371                                         const MachineBasicBlock *Dst) const {
2372   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2373   const BasicBlock *SrcBB = Src->getBasicBlock();
2374   const BasicBlock *DstBB = Dst->getBasicBlock();
2375   if (!BPI) {
2376     // If BPI is not available, set the default probability as 1 / N, where N is
2377     // the number of successors.
2378     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2379     return BranchProbability(1, SuccSize);
2380   }
2381   return BPI->getEdgeProbability(SrcBB, DstBB);
2382 }
2383 
2384 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2385                                                MachineBasicBlock *Dst,
2386                                                BranchProbability Prob) {
2387   if (!FuncInfo.BPI)
2388     Src->addSuccessorWithoutProb(Dst);
2389   else {
2390     if (Prob.isUnknown())
2391       Prob = getEdgeProbability(Src, Dst);
2392     Src->addSuccessor(Dst, Prob);
2393   }
2394 }
2395 
2396 static bool InBlock(const Value *V, const BasicBlock *BB) {
2397   if (const Instruction *I = dyn_cast<Instruction>(V))
2398     return I->getParent() == BB;
2399   return true;
2400 }
2401 
2402 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2403 /// This function emits a branch and is used at the leaves of an OR or an
2404 /// AND operator tree.
2405 void
2406 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2407                                                   MachineBasicBlock *TBB,
2408                                                   MachineBasicBlock *FBB,
2409                                                   MachineBasicBlock *CurBB,
2410                                                   MachineBasicBlock *SwitchBB,
2411                                                   BranchProbability TProb,
2412                                                   BranchProbability FProb,
2413                                                   bool InvertCond) {
2414   const BasicBlock *BB = CurBB->getBasicBlock();
2415 
2416   // If the leaf of the tree is a comparison, merge the condition into
2417   // the caseblock.
2418   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2419     // The operands of the cmp have to be in this block.  We don't know
2420     // how to export them from some other block.  If this is the first block
2421     // of the sequence, no exporting is needed.
2422     if (CurBB == SwitchBB ||
2423         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2424          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2425       ISD::CondCode Condition;
2426       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2427         ICmpInst::Predicate Pred =
2428             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2429         Condition = getICmpCondCode(Pred);
2430       } else {
2431         const FCmpInst *FC = cast<FCmpInst>(Cond);
2432         FCmpInst::Predicate Pred =
2433             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2434         Condition = getFCmpCondCode(Pred);
2435         if (TM.Options.NoNaNsFPMath)
2436           Condition = getFCmpCodeWithoutNaN(Condition);
2437       }
2438 
2439       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2440                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2441       SL->SwitchCases.push_back(CB);
2442       return;
2443     }
2444   }
2445 
2446   // Create a CaseBlock record representing this branch.
2447   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2448   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2449                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2450   SL->SwitchCases.push_back(CB);
2451 }
2452 
2453 // Collect dependencies on V recursively. This is used for the cost analysis in
2454 // `shouldKeepJumpConditionsTogether`.
2455 static bool collectInstructionDeps(
2456     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2457     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2458     unsigned Depth = 0) {
2459   // Return false if we have an incomplete count.
2460   if (Depth >= SelectionDAG::MaxRecursionDepth)
2461     return false;
2462 
2463   auto *I = dyn_cast<Instruction>(V);
2464   if (I == nullptr)
2465     return true;
2466 
2467   if (Necessary != nullptr) {
2468     // This instruction is necessary for the other side of the condition so
2469     // don't count it.
2470     if (Necessary->contains(I))
2471       return true;
2472   }
2473 
2474   // Already added this dep.
2475   if (!Deps->try_emplace(I, false).second)
2476     return true;
2477 
2478   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2479     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2480                                 Depth + 1))
2481       return false;
2482   return true;
2483 }
2484 
2485 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2486     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2487     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2488     TargetLoweringBase::CondMergingParams Params) const {
2489   if (I.getNumSuccessors() != 2)
2490     return false;
2491 
2492   if (!I.isConditional())
2493     return false;
2494 
2495   if (Params.BaseCost < 0)
2496     return false;
2497 
2498   // Baseline cost.
2499   InstructionCost CostThresh = Params.BaseCost;
2500 
2501   BranchProbabilityInfo *BPI = nullptr;
2502   if (Params.LikelyBias || Params.UnlikelyBias)
2503     BPI = FuncInfo.BPI;
2504   if (BPI != nullptr) {
2505     // See if we are either likely to get an early out or compute both lhs/rhs
2506     // of the condition.
2507     BasicBlock *IfFalse = I.getSuccessor(0);
2508     BasicBlock *IfTrue = I.getSuccessor(1);
2509 
2510     std::optional<bool> Likely;
2511     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2512       Likely = true;
2513     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2514       Likely = false;
2515 
2516     if (Likely) {
2517       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2518         // Its likely we will have to compute both lhs and rhs of condition
2519         CostThresh += Params.LikelyBias;
2520       else {
2521         if (Params.UnlikelyBias < 0)
2522           return false;
2523         // Its likely we will get an early out.
2524         CostThresh -= Params.UnlikelyBias;
2525       }
2526     }
2527   }
2528 
2529   if (CostThresh <= 0)
2530     return false;
2531 
2532   // Collect "all" instructions that lhs condition is dependent on.
2533   // Use map for stable iteration (to avoid non-determanism of iteration of
2534   // SmallPtrSet). The `bool` value is just a dummy.
2535   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2536   collectInstructionDeps(&LhsDeps, Lhs);
2537   // Collect "all" instructions that rhs condition is dependent on AND are
2538   // dependencies of lhs. This gives us an estimate on which instructions we
2539   // stand to save by splitting the condition.
2540   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2541     return false;
2542   // Add the compare instruction itself unless its a dependency on the LHS.
2543   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2544     if (!LhsDeps.contains(RhsI))
2545       RhsDeps.try_emplace(RhsI, false);
2546 
2547   const auto &TLI = DAG.getTargetLoweringInfo();
2548   const auto &TTI =
2549       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2550 
2551   InstructionCost CostOfIncluding = 0;
2552   // See if this instruction will need to computed independently of whether RHS
2553   // is.
2554   Value *BrCond = I.getCondition();
2555   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2556     for (const auto *U : Ins->users()) {
2557       // If user is independent of RHS calculation we don't need to count it.
2558       if (auto *UIns = dyn_cast<Instruction>(U))
2559         if (UIns != BrCond && !RhsDeps.contains(UIns))
2560           return false;
2561     }
2562     return true;
2563   };
2564 
2565   // Prune instructions from RHS Deps that are dependencies of unrelated
2566   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2567   // arbitrary and just meant to cap the how much time we spend in the pruning
2568   // loop. Its highly unlikely to come into affect.
2569   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2570   // Stop after a certain point. No incorrectness from including too many
2571   // instructions.
2572   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2573     const Instruction *ToDrop = nullptr;
2574     for (const auto &InsPair : RhsDeps) {
2575       if (!ShouldCountInsn(InsPair.first)) {
2576         ToDrop = InsPair.first;
2577         break;
2578       }
2579     }
2580     if (ToDrop == nullptr)
2581       break;
2582     RhsDeps.erase(ToDrop);
2583   }
2584 
2585   for (const auto &InsPair : RhsDeps) {
2586     // Finally accumulate latency that we can only attribute to computing the
2587     // RHS condition. Use latency because we are essentially trying to calculate
2588     // the cost of the dependency chain.
2589     // Possible TODO: We could try to estimate ILP and make this more precise.
2590     CostOfIncluding +=
2591         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2592 
2593     if (CostOfIncluding > CostThresh)
2594       return false;
2595   }
2596   return true;
2597 }
2598 
2599 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2600                                                MachineBasicBlock *TBB,
2601                                                MachineBasicBlock *FBB,
2602                                                MachineBasicBlock *CurBB,
2603                                                MachineBasicBlock *SwitchBB,
2604                                                Instruction::BinaryOps Opc,
2605                                                BranchProbability TProb,
2606                                                BranchProbability FProb,
2607                                                bool InvertCond) {
2608   // Skip over not part of the tree and remember to invert op and operands at
2609   // next level.
2610   Value *NotCond;
2611   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2612       InBlock(NotCond, CurBB->getBasicBlock())) {
2613     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2614                          !InvertCond);
2615     return;
2616   }
2617 
2618   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2619   const Value *BOpOp0, *BOpOp1;
2620   // Compute the effective opcode for Cond, taking into account whether it needs
2621   // to be inverted, e.g.
2622   //   and (not (or A, B)), C
2623   // gets lowered as
2624   //   and (and (not A, not B), C)
2625   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2626   if (BOp) {
2627     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2628                ? Instruction::And
2629                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2630                       ? Instruction::Or
2631                       : (Instruction::BinaryOps)0);
2632     if (InvertCond) {
2633       if (BOpc == Instruction::And)
2634         BOpc = Instruction::Or;
2635       else if (BOpc == Instruction::Or)
2636         BOpc = Instruction::And;
2637     }
2638   }
2639 
2640   // If this node is not part of the or/and tree, emit it as a branch.
2641   // Note that all nodes in the tree should have same opcode.
2642   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2643   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2644       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2645       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2646     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2647                                  TProb, FProb, InvertCond);
2648     return;
2649   }
2650 
2651   //  Create TmpBB after CurBB.
2652   MachineFunction::iterator BBI(CurBB);
2653   MachineFunction &MF = DAG.getMachineFunction();
2654   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2655   CurBB->getParent()->insert(++BBI, TmpBB);
2656 
2657   if (Opc == Instruction::Or) {
2658     // Codegen X | Y as:
2659     // BB1:
2660     //   jmp_if_X TBB
2661     //   jmp TmpBB
2662     // TmpBB:
2663     //   jmp_if_Y TBB
2664     //   jmp FBB
2665     //
2666 
2667     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2668     // The requirement is that
2669     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2670     //     = TrueProb for original BB.
2671     // Assuming the original probabilities are A and B, one choice is to set
2672     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2673     // A/(1+B) and 2B/(1+B). This choice assumes that
2674     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2675     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2676     // TmpBB, but the math is more complicated.
2677 
2678     auto NewTrueProb = TProb / 2;
2679     auto NewFalseProb = TProb / 2 + FProb;
2680     // Emit the LHS condition.
2681     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2682                          NewFalseProb, InvertCond);
2683 
2684     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2685     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2686     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2687     // Emit the RHS condition into TmpBB.
2688     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2689                          Probs[1], InvertCond);
2690   } else {
2691     assert(Opc == Instruction::And && "Unknown merge op!");
2692     // Codegen X & Y as:
2693     // BB1:
2694     //   jmp_if_X TmpBB
2695     //   jmp FBB
2696     // TmpBB:
2697     //   jmp_if_Y TBB
2698     //   jmp FBB
2699     //
2700     //  This requires creation of TmpBB after CurBB.
2701 
2702     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2703     // The requirement is that
2704     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2705     //     = FalseProb for original BB.
2706     // Assuming the original probabilities are A and B, one choice is to set
2707     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2708     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2709     // TrueProb for BB1 * FalseProb for TmpBB.
2710 
2711     auto NewTrueProb = TProb + FProb / 2;
2712     auto NewFalseProb = FProb / 2;
2713     // Emit the LHS condition.
2714     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2715                          NewFalseProb, InvertCond);
2716 
2717     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2718     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2719     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2720     // Emit the RHS condition into TmpBB.
2721     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2722                          Probs[1], InvertCond);
2723   }
2724 }
2725 
2726 /// If the set of cases should be emitted as a series of branches, return true.
2727 /// If we should emit this as a bunch of and/or'd together conditions, return
2728 /// false.
2729 bool
2730 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2731   if (Cases.size() != 2) return true;
2732 
2733   // If this is two comparisons of the same values or'd or and'd together, they
2734   // will get folded into a single comparison, so don't emit two blocks.
2735   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2736        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2737       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2738        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2739     return false;
2740   }
2741 
2742   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2743   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2744   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2745       Cases[0].CC == Cases[1].CC &&
2746       isa<Constant>(Cases[0].CmpRHS) &&
2747       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2748     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2749       return false;
2750     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2751       return false;
2752   }
2753 
2754   return true;
2755 }
2756 
2757 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2758   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2759 
2760   // Update machine-CFG edges.
2761   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2762 
2763   if (I.isUnconditional()) {
2764     // Update machine-CFG edges.
2765     BrMBB->addSuccessor(Succ0MBB);
2766 
2767     // If this is not a fall-through branch or optimizations are switched off,
2768     // emit the branch.
2769     if (Succ0MBB != NextBlock(BrMBB) ||
2770         TM.getOptLevel() == CodeGenOptLevel::None) {
2771       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2772                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2773       setValue(&I, Br);
2774       DAG.setRoot(Br);
2775     }
2776 
2777     return;
2778   }
2779 
2780   // If this condition is one of the special cases we handle, do special stuff
2781   // now.
2782   const Value *CondVal = I.getCondition();
2783   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2784 
2785   // If this is a series of conditions that are or'd or and'd together, emit
2786   // this as a sequence of branches instead of setcc's with and/or operations.
2787   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2788   // unpredictable branches, and vector extracts because those jumps are likely
2789   // expensive for any target), this should improve performance.
2790   // For example, instead of something like:
2791   //     cmp A, B
2792   //     C = seteq
2793   //     cmp D, E
2794   //     F = setle
2795   //     or C, F
2796   //     jnz foo
2797   // Emit:
2798   //     cmp A, B
2799   //     je foo
2800   //     cmp D, E
2801   //     jle foo
2802   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2803   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2804       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2805     Value *Vec;
2806     const Value *BOp0, *BOp1;
2807     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2808     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2809       Opcode = Instruction::And;
2810     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2811       Opcode = Instruction::Or;
2812 
2813     if (Opcode &&
2814         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2815           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2816         !shouldKeepJumpConditionsTogether(
2817             FuncInfo, I, Opcode, BOp0, BOp1,
2818             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2819                 Opcode, BOp0, BOp1))) {
2820       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2821                            getEdgeProbability(BrMBB, Succ0MBB),
2822                            getEdgeProbability(BrMBB, Succ1MBB),
2823                            /*InvertCond=*/false);
2824       // If the compares in later blocks need to use values not currently
2825       // exported from this block, export them now.  This block should always
2826       // be the first entry.
2827       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2828 
2829       // Allow some cases to be rejected.
2830       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2831         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2832           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2833           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2834         }
2835 
2836         // Emit the branch for this block.
2837         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2838         SL->SwitchCases.erase(SL->SwitchCases.begin());
2839         return;
2840       }
2841 
2842       // Okay, we decided not to do this, remove any inserted MBB's and clear
2843       // SwitchCases.
2844       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2845         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2846 
2847       SL->SwitchCases.clear();
2848     }
2849   }
2850 
2851   // Create a CaseBlock record representing this branch.
2852   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2853                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2854 
2855   // Use visitSwitchCase to actually insert the fast branch sequence for this
2856   // cond branch.
2857   visitSwitchCase(CB, BrMBB);
2858 }
2859 
2860 /// visitSwitchCase - Emits the necessary code to represent a single node in
2861 /// the binary search tree resulting from lowering a switch instruction.
2862 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2863                                           MachineBasicBlock *SwitchBB) {
2864   SDValue Cond;
2865   SDValue CondLHS = getValue(CB.CmpLHS);
2866   SDLoc dl = CB.DL;
2867 
2868   if (CB.CC == ISD::SETTRUE) {
2869     // Branch or fall through to TrueBB.
2870     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2871     SwitchBB->normalizeSuccProbs();
2872     if (CB.TrueBB != NextBlock(SwitchBB)) {
2873       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2874                               DAG.getBasicBlock(CB.TrueBB)));
2875     }
2876     return;
2877   }
2878 
2879   auto &TLI = DAG.getTargetLoweringInfo();
2880   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2881 
2882   // Build the setcc now.
2883   if (!CB.CmpMHS) {
2884     // Fold "(X == true)" to X and "(X == false)" to !X to
2885     // handle common cases produced by branch lowering.
2886     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2887         CB.CC == ISD::SETEQ)
2888       Cond = CondLHS;
2889     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2890              CB.CC == ISD::SETEQ) {
2891       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2892       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2893     } else {
2894       SDValue CondRHS = getValue(CB.CmpRHS);
2895 
2896       // If a pointer's DAG type is larger than its memory type then the DAG
2897       // values are zero-extended. This breaks signed comparisons so truncate
2898       // back to the underlying type before doing the compare.
2899       if (CondLHS.getValueType() != MemVT) {
2900         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2901         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2902       }
2903       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2904     }
2905   } else {
2906     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2907 
2908     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2909     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2910 
2911     SDValue CmpOp = getValue(CB.CmpMHS);
2912     EVT VT = CmpOp.getValueType();
2913 
2914     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2915       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2916                           ISD::SETLE);
2917     } else {
2918       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2919                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2920       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2921                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2922     }
2923   }
2924 
2925   // Update successor info
2926   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2927   // TrueBB and FalseBB are always different unless the incoming IR is
2928   // degenerate. This only happens when running llc on weird IR.
2929   if (CB.TrueBB != CB.FalseBB)
2930     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2931   SwitchBB->normalizeSuccProbs();
2932 
2933   // If the lhs block is the next block, invert the condition so that we can
2934   // fall through to the lhs instead of the rhs block.
2935   if (CB.TrueBB == NextBlock(SwitchBB)) {
2936     std::swap(CB.TrueBB, CB.FalseBB);
2937     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2938     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2939   }
2940 
2941   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2942                                MVT::Other, getControlRoot(), Cond,
2943                                DAG.getBasicBlock(CB.TrueBB));
2944 
2945   setValue(CurInst, BrCond);
2946 
2947   // Insert the false branch. Do this even if it's a fall through branch,
2948   // this makes it easier to do DAG optimizations which require inverting
2949   // the branch condition.
2950   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2951                        DAG.getBasicBlock(CB.FalseBB));
2952 
2953   DAG.setRoot(BrCond);
2954 }
2955 
2956 /// visitJumpTable - Emit JumpTable node in the current MBB
2957 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2958   // Emit the code for the jump table
2959   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2960   assert(JT.Reg != -1U && "Should lower JT Header first!");
2961   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2962   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2963   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2964   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2965                                     Index.getValue(1), Table, Index);
2966   DAG.setRoot(BrJumpTable);
2967 }
2968 
2969 /// visitJumpTableHeader - This function emits necessary code to produce index
2970 /// in the JumpTable from switch case.
2971 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2972                                                JumpTableHeader &JTH,
2973                                                MachineBasicBlock *SwitchBB) {
2974   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2975   const SDLoc &dl = *JT.SL;
2976 
2977   // Subtract the lowest switch case value from the value being switched on.
2978   SDValue SwitchOp = getValue(JTH.SValue);
2979   EVT VT = SwitchOp.getValueType();
2980   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2981                             DAG.getConstant(JTH.First, dl, VT));
2982 
2983   // The SDNode we just created, which holds the value being switched on minus
2984   // the smallest case value, needs to be copied to a virtual register so it
2985   // can be used as an index into the jump table in a subsequent basic block.
2986   // This value may be smaller or larger than the target's pointer type, and
2987   // therefore require extension or truncating.
2988   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2989   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
2990 
2991   unsigned JumpTableReg =
2992       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
2993   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
2994                                     JumpTableReg, SwitchOp);
2995   JT.Reg = JumpTableReg;
2996 
2997   if (!JTH.FallthroughUnreachable) {
2998     // Emit the range check for the jump table, and branch to the default block
2999     // for the switch statement if the value being switched on exceeds the
3000     // largest case in the switch.
3001     SDValue CMP = DAG.getSetCC(
3002         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3003                                    Sub.getValueType()),
3004         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3005 
3006     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3007                                  MVT::Other, CopyTo, CMP,
3008                                  DAG.getBasicBlock(JT.Default));
3009 
3010     // Avoid emitting unnecessary branches to the next block.
3011     if (JT.MBB != NextBlock(SwitchBB))
3012       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3013                            DAG.getBasicBlock(JT.MBB));
3014 
3015     DAG.setRoot(BrCond);
3016   } else {
3017     // Avoid emitting unnecessary branches to the next block.
3018     if (JT.MBB != NextBlock(SwitchBB))
3019       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3020                               DAG.getBasicBlock(JT.MBB)));
3021     else
3022       DAG.setRoot(CopyTo);
3023   }
3024 }
3025 
3026 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3027 /// variable if there exists one.
3028 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3029                                  SDValue &Chain) {
3030   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3031   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3032   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3033   MachineFunction &MF = DAG.getMachineFunction();
3034   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3035   MachineSDNode *Node =
3036       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3037   if (Global) {
3038     MachinePointerInfo MPInfo(Global);
3039     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3040                  MachineMemOperand::MODereferenceable;
3041     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3042         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3043         DAG.getEVTAlign(PtrTy));
3044     DAG.setNodeMemRefs(Node, {MemRef});
3045   }
3046   if (PtrTy != PtrMemTy)
3047     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3048   return SDValue(Node, 0);
3049 }
3050 
3051 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3052 /// tail spliced into a stack protector check success bb.
3053 ///
3054 /// For a high level explanation of how this fits into the stack protector
3055 /// generation see the comment on the declaration of class
3056 /// StackProtectorDescriptor.
3057 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3058                                                   MachineBasicBlock *ParentBB) {
3059 
3060   // First create the loads to the guard/stack slot for the comparison.
3061   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3062   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3063   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3064 
3065   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3066   int FI = MFI.getStackProtectorIndex();
3067 
3068   SDValue Guard;
3069   SDLoc dl = getCurSDLoc();
3070   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3071   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3072   Align Align =
3073       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3074 
3075   // Generate code to load the content of the guard slot.
3076   SDValue GuardVal = DAG.getLoad(
3077       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3078       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3079       MachineMemOperand::MOVolatile);
3080 
3081   if (TLI.useStackGuardXorFP())
3082     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3083 
3084   // Retrieve guard check function, nullptr if instrumentation is inlined.
3085   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3086     // The target provides a guard check function to validate the guard value.
3087     // Generate a call to that function with the content of the guard slot as
3088     // argument.
3089     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3090     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3091 
3092     TargetLowering::ArgListTy Args;
3093     TargetLowering::ArgListEntry Entry;
3094     Entry.Node = GuardVal;
3095     Entry.Ty = FnTy->getParamType(0);
3096     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3097       Entry.IsInReg = true;
3098     Args.push_back(Entry);
3099 
3100     TargetLowering::CallLoweringInfo CLI(DAG);
3101     CLI.setDebugLoc(getCurSDLoc())
3102         .setChain(DAG.getEntryNode())
3103         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3104                    getValue(GuardCheckFn), std::move(Args));
3105 
3106     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3107     DAG.setRoot(Result.second);
3108     return;
3109   }
3110 
3111   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3112   // Otherwise, emit a volatile load to retrieve the stack guard value.
3113   SDValue Chain = DAG.getEntryNode();
3114   if (TLI.useLoadStackGuardNode()) {
3115     Guard = getLoadStackGuard(DAG, dl, Chain);
3116   } else {
3117     const Value *IRGuard = TLI.getSDagStackGuard(M);
3118     SDValue GuardPtr = getValue(IRGuard);
3119 
3120     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3121                         MachinePointerInfo(IRGuard, 0), Align,
3122                         MachineMemOperand::MOVolatile);
3123   }
3124 
3125   // Perform the comparison via a getsetcc.
3126   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3127                                                         *DAG.getContext(),
3128                                                         Guard.getValueType()),
3129                              Guard, GuardVal, ISD::SETNE);
3130 
3131   // If the guard/stackslot do not equal, branch to failure MBB.
3132   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3133                                MVT::Other, GuardVal.getOperand(0),
3134                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3135   // Otherwise branch to success MBB.
3136   SDValue Br = DAG.getNode(ISD::BR, dl,
3137                            MVT::Other, BrCond,
3138                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3139 
3140   DAG.setRoot(Br);
3141 }
3142 
3143 /// Codegen the failure basic block for a stack protector check.
3144 ///
3145 /// A failure stack protector machine basic block consists simply of a call to
3146 /// __stack_chk_fail().
3147 ///
3148 /// For a high level explanation of how this fits into the stack protector
3149 /// generation see the comment on the declaration of class
3150 /// StackProtectorDescriptor.
3151 void
3152 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3154   TargetLowering::MakeLibCallOptions CallOptions;
3155   CallOptions.setDiscardResult(true);
3156   SDValue Chain =
3157       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3158                       std::nullopt, CallOptions, getCurSDLoc())
3159           .second;
3160   // On PS4/PS5, the "return address" must still be within the calling
3161   // function, even if it's at the very end, so emit an explicit TRAP here.
3162   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3163   if (TM.getTargetTriple().isPS())
3164     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3165   // WebAssembly needs an unreachable instruction after a non-returning call,
3166   // because the function return type can be different from __stack_chk_fail's
3167   // return type (void).
3168   if (TM.getTargetTriple().isWasm())
3169     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3170 
3171   DAG.setRoot(Chain);
3172 }
3173 
3174 /// visitBitTestHeader - This function emits necessary code to produce value
3175 /// suitable for "bit tests"
3176 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3177                                              MachineBasicBlock *SwitchBB) {
3178   SDLoc dl = getCurSDLoc();
3179 
3180   // Subtract the minimum value.
3181   SDValue SwitchOp = getValue(B.SValue);
3182   EVT VT = SwitchOp.getValueType();
3183   SDValue RangeSub =
3184       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3185 
3186   // Determine the type of the test operands.
3187   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3188   bool UsePtrType = false;
3189   if (!TLI.isTypeLegal(VT)) {
3190     UsePtrType = true;
3191   } else {
3192     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3193       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3194         // Switch table case range are encoded into series of masks.
3195         // Just use pointer type, it's guaranteed to fit.
3196         UsePtrType = true;
3197         break;
3198       }
3199   }
3200   SDValue Sub = RangeSub;
3201   if (UsePtrType) {
3202     VT = TLI.getPointerTy(DAG.getDataLayout());
3203     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3204   }
3205 
3206   B.RegVT = VT.getSimpleVT();
3207   B.Reg = FuncInfo.CreateReg(B.RegVT);
3208   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3209 
3210   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3211 
3212   if (!B.FallthroughUnreachable)
3213     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3214   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3215   SwitchBB->normalizeSuccProbs();
3216 
3217   SDValue Root = CopyTo;
3218   if (!B.FallthroughUnreachable) {
3219     // Conditional branch to the default block.
3220     SDValue RangeCmp = DAG.getSetCC(dl,
3221         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3222                                RangeSub.getValueType()),
3223         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3224         ISD::SETUGT);
3225 
3226     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3227                        DAG.getBasicBlock(B.Default));
3228   }
3229 
3230   // Avoid emitting unnecessary branches to the next block.
3231   if (MBB != NextBlock(SwitchBB))
3232     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3233 
3234   DAG.setRoot(Root);
3235 }
3236 
3237 /// visitBitTestCase - this function produces one "bit test"
3238 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3239                                            MachineBasicBlock* NextMBB,
3240                                            BranchProbability BranchProbToNext,
3241                                            unsigned Reg,
3242                                            BitTestCase &B,
3243                                            MachineBasicBlock *SwitchBB) {
3244   SDLoc dl = getCurSDLoc();
3245   MVT VT = BB.RegVT;
3246   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3247   SDValue Cmp;
3248   unsigned PopCount = llvm::popcount(B.Mask);
3249   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3250   if (PopCount == 1) {
3251     // Testing for a single bit; just compare the shift count with what it
3252     // would need to be to shift a 1 bit in that position.
3253     Cmp = DAG.getSetCC(
3254         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3255         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3256         ISD::SETEQ);
3257   } else if (PopCount == BB.Range) {
3258     // There is only one zero bit in the range, test for it directly.
3259     Cmp = DAG.getSetCC(
3260         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3261         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3262   } else {
3263     // Make desired shift
3264     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3265                                     DAG.getConstant(1, dl, VT), ShiftOp);
3266 
3267     // Emit bit tests and jumps
3268     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3269                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3270     Cmp = DAG.getSetCC(
3271         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3272         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3273   }
3274 
3275   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3276   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3277   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3278   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3279   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3280   // one as they are relative probabilities (and thus work more like weights),
3281   // and hence we need to normalize them to let the sum of them become one.
3282   SwitchBB->normalizeSuccProbs();
3283 
3284   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3285                               MVT::Other, getControlRoot(),
3286                               Cmp, DAG.getBasicBlock(B.TargetBB));
3287 
3288   // Avoid emitting unnecessary branches to the next block.
3289   if (NextMBB != NextBlock(SwitchBB))
3290     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3291                         DAG.getBasicBlock(NextMBB));
3292 
3293   DAG.setRoot(BrAnd);
3294 }
3295 
3296 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3297   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3298 
3299   // Retrieve successors. Look through artificial IR level blocks like
3300   // catchswitch for successors.
3301   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3302   const BasicBlock *EHPadBB = I.getSuccessor(1);
3303   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3304 
3305   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3306   // have to do anything here to lower funclet bundles.
3307   assert(!I.hasOperandBundlesOtherThan(
3308              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3309               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3310               LLVMContext::OB_cfguardtarget,
3311               LLVMContext::OB_clang_arc_attachedcall}) &&
3312          "Cannot lower invokes with arbitrary operand bundles yet!");
3313 
3314   const Value *Callee(I.getCalledOperand());
3315   const Function *Fn = dyn_cast<Function>(Callee);
3316   if (isa<InlineAsm>(Callee))
3317     visitInlineAsm(I, EHPadBB);
3318   else if (Fn && Fn->isIntrinsic()) {
3319     switch (Fn->getIntrinsicID()) {
3320     default:
3321       llvm_unreachable("Cannot invoke this intrinsic");
3322     case Intrinsic::donothing:
3323       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3324     case Intrinsic::seh_try_begin:
3325     case Intrinsic::seh_scope_begin:
3326     case Intrinsic::seh_try_end:
3327     case Intrinsic::seh_scope_end:
3328       if (EHPadMBB)
3329           // a block referenced by EH table
3330           // so dtor-funclet not removed by opts
3331           EHPadMBB->setMachineBlockAddressTaken();
3332       break;
3333     case Intrinsic::experimental_patchpoint_void:
3334     case Intrinsic::experimental_patchpoint:
3335       visitPatchpoint(I, EHPadBB);
3336       break;
3337     case Intrinsic::experimental_gc_statepoint:
3338       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3339       break;
3340     case Intrinsic::wasm_rethrow: {
3341       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3342       // special because it can be invoked, so we manually lower it to a DAG
3343       // node here.
3344       SmallVector<SDValue, 8> Ops;
3345       Ops.push_back(getRoot()); // inchain
3346       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3347       Ops.push_back(
3348           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3349                                 TLI.getPointerTy(DAG.getDataLayout())));
3350       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3351       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3352       break;
3353     }
3354     }
3355   } else if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) {
3356     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3357     // Eventually we will support lowering the @llvm.experimental.deoptimize
3358     // intrinsic, and right now there are no plans to support other intrinsics
3359     // with deopt state.
3360     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3361   } else {
3362     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3363   }
3364 
3365   // If the value of the invoke is used outside of its defining block, make it
3366   // available as a virtual register.
3367   // We already took care of the exported value for the statepoint instruction
3368   // during call to the LowerStatepoint.
3369   if (!isa<GCStatepointInst>(I)) {
3370     CopyToExportRegsIfNeeded(&I);
3371   }
3372 
3373   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3374   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3375   BranchProbability EHPadBBProb =
3376       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3377           : BranchProbability::getZero();
3378   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3379 
3380   // Update successor info.
3381   addSuccessorWithProb(InvokeMBB, Return);
3382   for (auto &UnwindDest : UnwindDests) {
3383     UnwindDest.first->setIsEHPad();
3384     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3385   }
3386   InvokeMBB->normalizeSuccProbs();
3387 
3388   // Drop into normal successor.
3389   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3390                           DAG.getBasicBlock(Return)));
3391 }
3392 
3393 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3394   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3395 
3396   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3397   // have to do anything here to lower funclet bundles.
3398   assert(!I.hasOperandBundlesOtherThan(
3399              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3400          "Cannot lower callbrs with arbitrary operand bundles yet!");
3401 
3402   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3403   visitInlineAsm(I);
3404   CopyToExportRegsIfNeeded(&I);
3405 
3406   // Retrieve successors.
3407   SmallPtrSet<BasicBlock *, 8> Dests;
3408   Dests.insert(I.getDefaultDest());
3409   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3410 
3411   // Update successor info.
3412   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3413   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3414     BasicBlock *Dest = I.getIndirectDest(i);
3415     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3416     Target->setIsInlineAsmBrIndirectTarget();
3417     Target->setMachineBlockAddressTaken();
3418     Target->setLabelMustBeEmitted();
3419     // Don't add duplicate machine successors.
3420     if (Dests.insert(Dest).second)
3421       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3422   }
3423   CallBrMBB->normalizeSuccProbs();
3424 
3425   // Drop into default successor.
3426   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3427                           MVT::Other, getControlRoot(),
3428                           DAG.getBasicBlock(Return)));
3429 }
3430 
3431 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3432   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3433 }
3434 
3435 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3436   assert(FuncInfo.MBB->isEHPad() &&
3437          "Call to landingpad not in landing pad!");
3438 
3439   // If there aren't registers to copy the values into (e.g., during SjLj
3440   // exceptions), then don't bother to create these DAG nodes.
3441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3442   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3443   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3444       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3445     return;
3446 
3447   // If landingpad's return type is token type, we don't create DAG nodes
3448   // for its exception pointer and selector value. The extraction of exception
3449   // pointer or selector value from token type landingpads is not currently
3450   // supported.
3451   if (LP.getType()->isTokenTy())
3452     return;
3453 
3454   SmallVector<EVT, 2> ValueVTs;
3455   SDLoc dl = getCurSDLoc();
3456   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3457   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3458 
3459   // Get the two live-in registers as SDValues. The physregs have already been
3460   // copied into virtual registers.
3461   SDValue Ops[2];
3462   if (FuncInfo.ExceptionPointerVirtReg) {
3463     Ops[0] = DAG.getZExtOrTrunc(
3464         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3465                            FuncInfo.ExceptionPointerVirtReg,
3466                            TLI.getPointerTy(DAG.getDataLayout())),
3467         dl, ValueVTs[0]);
3468   } else {
3469     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3470   }
3471   Ops[1] = DAG.getZExtOrTrunc(
3472       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3473                          FuncInfo.ExceptionSelectorVirtReg,
3474                          TLI.getPointerTy(DAG.getDataLayout())),
3475       dl, ValueVTs[1]);
3476 
3477   // Merge into one.
3478   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3479                             DAG.getVTList(ValueVTs), Ops);
3480   setValue(&LP, Res);
3481 }
3482 
3483 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3484                                            MachineBasicBlock *Last) {
3485   // Update JTCases.
3486   for (JumpTableBlock &JTB : SL->JTCases)
3487     if (JTB.first.HeaderBB == First)
3488       JTB.first.HeaderBB = Last;
3489 
3490   // Update BitTestCases.
3491   for (BitTestBlock &BTB : SL->BitTestCases)
3492     if (BTB.Parent == First)
3493       BTB.Parent = Last;
3494 }
3495 
3496 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3497   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3498 
3499   // Update machine-CFG edges with unique successors.
3500   SmallSet<BasicBlock*, 32> Done;
3501   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3502     BasicBlock *BB = I.getSuccessor(i);
3503     bool Inserted = Done.insert(BB).second;
3504     if (!Inserted)
3505         continue;
3506 
3507     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3508     addSuccessorWithProb(IndirectBrMBB, Succ);
3509   }
3510   IndirectBrMBB->normalizeSuccProbs();
3511 
3512   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3513                           MVT::Other, getControlRoot(),
3514                           getValue(I.getAddress())));
3515 }
3516 
3517 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3518   if (!DAG.getTarget().Options.TrapUnreachable)
3519     return;
3520 
3521   // We may be able to ignore unreachable behind a noreturn call.
3522   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3523     if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
3524       if (Call->doesNotReturn())
3525         return;
3526     }
3527   }
3528 
3529   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3530 }
3531 
3532 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3533   SDNodeFlags Flags;
3534   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3535     Flags.copyFMF(*FPOp);
3536 
3537   SDValue Op = getValue(I.getOperand(0));
3538   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3539                                     Op, Flags);
3540   setValue(&I, UnNodeValue);
3541 }
3542 
3543 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3544   SDNodeFlags Flags;
3545   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3546     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3547     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3548   }
3549   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3550     Flags.setExact(ExactOp->isExact());
3551   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3552     Flags.setDisjoint(DisjointOp->isDisjoint());
3553   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3554     Flags.copyFMF(*FPOp);
3555 
3556   SDValue Op1 = getValue(I.getOperand(0));
3557   SDValue Op2 = getValue(I.getOperand(1));
3558   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3559                                      Op1, Op2, Flags);
3560   setValue(&I, BinNodeValue);
3561 }
3562 
3563 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3564   SDValue Op1 = getValue(I.getOperand(0));
3565   SDValue Op2 = getValue(I.getOperand(1));
3566 
3567   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3568       Op1.getValueType(), DAG.getDataLayout());
3569 
3570   // Coerce the shift amount to the right type if we can. This exposes the
3571   // truncate or zext to optimization early.
3572   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3573     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3574            "Unexpected shift type");
3575     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3576   }
3577 
3578   bool nuw = false;
3579   bool nsw = false;
3580   bool exact = false;
3581 
3582   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3583 
3584     if (const OverflowingBinaryOperator *OFBinOp =
3585             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3586       nuw = OFBinOp->hasNoUnsignedWrap();
3587       nsw = OFBinOp->hasNoSignedWrap();
3588     }
3589     if (const PossiblyExactOperator *ExactOp =
3590             dyn_cast<const PossiblyExactOperator>(&I))
3591       exact = ExactOp->isExact();
3592   }
3593   SDNodeFlags Flags;
3594   Flags.setExact(exact);
3595   Flags.setNoSignedWrap(nsw);
3596   Flags.setNoUnsignedWrap(nuw);
3597   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3598                             Flags);
3599   setValue(&I, Res);
3600 }
3601 
3602 void SelectionDAGBuilder::visitSDiv(const User &I) {
3603   SDValue Op1 = getValue(I.getOperand(0));
3604   SDValue Op2 = getValue(I.getOperand(1));
3605 
3606   SDNodeFlags Flags;
3607   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3608                  cast<PossiblyExactOperator>(&I)->isExact());
3609   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3610                            Op2, Flags));
3611 }
3612 
3613 void SelectionDAGBuilder::visitICmp(const User &I) {
3614   ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
3615   if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
3616     predicate = IC->getPredicate();
3617   else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
3618     predicate = ICmpInst::Predicate(IC->getPredicate());
3619   SDValue Op1 = getValue(I.getOperand(0));
3620   SDValue Op2 = getValue(I.getOperand(1));
3621   ISD::CondCode Opcode = getICmpCondCode(predicate);
3622 
3623   auto &TLI = DAG.getTargetLoweringInfo();
3624   EVT MemVT =
3625       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3626 
3627   // If a pointer's DAG type is larger than its memory type then the DAG values
3628   // are zero-extended. This breaks signed comparisons so truncate back to the
3629   // underlying type before doing the compare.
3630   if (Op1.getValueType() != MemVT) {
3631     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3632     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3633   }
3634 
3635   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3636                                                         I.getType());
3637   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3638 }
3639 
3640 void SelectionDAGBuilder::visitFCmp(const User &I) {
3641   FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
3642   if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
3643     predicate = FC->getPredicate();
3644   else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
3645     predicate = FCmpInst::Predicate(FC->getPredicate());
3646   SDValue Op1 = getValue(I.getOperand(0));
3647   SDValue Op2 = getValue(I.getOperand(1));
3648 
3649   ISD::CondCode Condition = getFCmpCondCode(predicate);
3650   auto *FPMO = cast<FPMathOperator>(&I);
3651   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3652     Condition = getFCmpCodeWithoutNaN(Condition);
3653 
3654   SDNodeFlags Flags;
3655   Flags.copyFMF(*FPMO);
3656   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3657 
3658   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3659                                                         I.getType());
3660   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3661 }
3662 
3663 // Check if the condition of the select has one use or two users that are both
3664 // selects with the same condition.
3665 static bool hasOnlySelectUsers(const Value *Cond) {
3666   return llvm::all_of(Cond->users(), [](const Value *V) {
3667     return isa<SelectInst>(V);
3668   });
3669 }
3670 
3671 void SelectionDAGBuilder::visitSelect(const User &I) {
3672   SmallVector<EVT, 4> ValueVTs;
3673   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3674                   ValueVTs);
3675   unsigned NumValues = ValueVTs.size();
3676   if (NumValues == 0) return;
3677 
3678   SmallVector<SDValue, 4> Values(NumValues);
3679   SDValue Cond     = getValue(I.getOperand(0));
3680   SDValue LHSVal   = getValue(I.getOperand(1));
3681   SDValue RHSVal   = getValue(I.getOperand(2));
3682   SmallVector<SDValue, 1> BaseOps(1, Cond);
3683   ISD::NodeType OpCode =
3684       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3685 
3686   bool IsUnaryAbs = false;
3687   bool Negate = false;
3688 
3689   SDNodeFlags Flags;
3690   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3691     Flags.copyFMF(*FPOp);
3692 
3693   Flags.setUnpredictable(
3694       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3695 
3696   // Min/max matching is only viable if all output VTs are the same.
3697   if (all_equal(ValueVTs)) {
3698     EVT VT = ValueVTs[0];
3699     LLVMContext &Ctx = *DAG.getContext();
3700     auto &TLI = DAG.getTargetLoweringInfo();
3701 
3702     // We care about the legality of the operation after it has been type
3703     // legalized.
3704     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3705       VT = TLI.getTypeToTransformTo(Ctx, VT);
3706 
3707     // If the vselect is legal, assume we want to leave this as a vector setcc +
3708     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3709     // min/max is legal on the scalar type.
3710     bool UseScalarMinMax = VT.isVector() &&
3711       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3712 
3713     // ValueTracking's select pattern matching does not account for -0.0,
3714     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3715     // -0.0 is less than +0.0.
3716     Value *LHS, *RHS;
3717     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3718     ISD::NodeType Opc = ISD::DELETED_NODE;
3719     switch (SPR.Flavor) {
3720     case SPF_UMAX:    Opc = ISD::UMAX; break;
3721     case SPF_UMIN:    Opc = ISD::UMIN; break;
3722     case SPF_SMAX:    Opc = ISD::SMAX; break;
3723     case SPF_SMIN:    Opc = ISD::SMIN; break;
3724     case SPF_FMINNUM:
3725       switch (SPR.NaNBehavior) {
3726       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3727       case SPNB_RETURNS_NAN: break;
3728       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3729       case SPNB_RETURNS_ANY:
3730         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3731             (UseScalarMinMax &&
3732              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3733           Opc = ISD::FMINNUM;
3734         break;
3735       }
3736       break;
3737     case SPF_FMAXNUM:
3738       switch (SPR.NaNBehavior) {
3739       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3740       case SPNB_RETURNS_NAN: break;
3741       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3742       case SPNB_RETURNS_ANY:
3743         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3744             (UseScalarMinMax &&
3745              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3746           Opc = ISD::FMAXNUM;
3747         break;
3748       }
3749       break;
3750     case SPF_NABS:
3751       Negate = true;
3752       [[fallthrough]];
3753     case SPF_ABS:
3754       IsUnaryAbs = true;
3755       Opc = ISD::ABS;
3756       break;
3757     default: break;
3758     }
3759 
3760     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3761         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3762          (UseScalarMinMax &&
3763           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3764         // If the underlying comparison instruction is used by any other
3765         // instruction, the consumed instructions won't be destroyed, so it is
3766         // not profitable to convert to a min/max.
3767         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3768       OpCode = Opc;
3769       LHSVal = getValue(LHS);
3770       RHSVal = getValue(RHS);
3771       BaseOps.clear();
3772     }
3773 
3774     if (IsUnaryAbs) {
3775       OpCode = Opc;
3776       LHSVal = getValue(LHS);
3777       BaseOps.clear();
3778     }
3779   }
3780 
3781   if (IsUnaryAbs) {
3782     for (unsigned i = 0; i != NumValues; ++i) {
3783       SDLoc dl = getCurSDLoc();
3784       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3785       Values[i] =
3786           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3787       if (Negate)
3788         Values[i] = DAG.getNegative(Values[i], dl, VT);
3789     }
3790   } else {
3791     for (unsigned i = 0; i != NumValues; ++i) {
3792       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3793       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3794       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3795       Values[i] = DAG.getNode(
3796           OpCode, getCurSDLoc(),
3797           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3798     }
3799   }
3800 
3801   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3802                            DAG.getVTList(ValueVTs), Values));
3803 }
3804 
3805 void SelectionDAGBuilder::visitTrunc(const User &I) {
3806   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3807   SDValue N = getValue(I.getOperand(0));
3808   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3809                                                         I.getType());
3810   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3811 }
3812 
3813 void SelectionDAGBuilder::visitZExt(const User &I) {
3814   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3815   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3816   SDValue N = getValue(I.getOperand(0));
3817   auto &TLI = DAG.getTargetLoweringInfo();
3818   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3819 
3820   SDNodeFlags Flags;
3821   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3822     Flags.setNonNeg(PNI->hasNonNeg());
3823 
3824   // Eagerly use nonneg information to canonicalize towards sign_extend if
3825   // that is the target's preference.
3826   // TODO: Let the target do this later.
3827   if (Flags.hasNonNeg() &&
3828       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3829     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3830     return;
3831   }
3832 
3833   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3834 }
3835 
3836 void SelectionDAGBuilder::visitSExt(const User &I) {
3837   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3838   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3839   SDValue N = getValue(I.getOperand(0));
3840   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3841                                                         I.getType());
3842   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3843 }
3844 
3845 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3846   // FPTrunc is never a no-op cast, no need to check
3847   SDValue N = getValue(I.getOperand(0));
3848   SDLoc dl = getCurSDLoc();
3849   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3850   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3851   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3852                            DAG.getTargetConstant(
3853                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3854 }
3855 
3856 void SelectionDAGBuilder::visitFPExt(const User &I) {
3857   // FPExt is never a no-op cast, no need to check
3858   SDValue N = getValue(I.getOperand(0));
3859   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3860                                                         I.getType());
3861   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3862 }
3863 
3864 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3865   // FPToUI is never a no-op cast, no need to check
3866   SDValue N = getValue(I.getOperand(0));
3867   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3868                                                         I.getType());
3869   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3870 }
3871 
3872 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3873   // FPToSI is never a no-op cast, no need to check
3874   SDValue N = getValue(I.getOperand(0));
3875   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3876                                                         I.getType());
3877   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3878 }
3879 
3880 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3881   // UIToFP is never a no-op cast, no need to check
3882   SDValue N = getValue(I.getOperand(0));
3883   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3884                                                         I.getType());
3885   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N));
3886 }
3887 
3888 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3889   // SIToFP is never a no-op cast, no need to check
3890   SDValue N = getValue(I.getOperand(0));
3891   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3892                                                         I.getType());
3893   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3894 }
3895 
3896 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3897   // What to do depends on the size of the integer and the size of the pointer.
3898   // We can either truncate, zero extend, or no-op, accordingly.
3899   SDValue N = getValue(I.getOperand(0));
3900   auto &TLI = DAG.getTargetLoweringInfo();
3901   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3902                                                         I.getType());
3903   EVT PtrMemVT =
3904       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3905   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3906   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3907   setValue(&I, N);
3908 }
3909 
3910 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3911   // What to do depends on the size of the integer and the size of the pointer.
3912   // We can either truncate, zero extend, or no-op, accordingly.
3913   SDValue N = getValue(I.getOperand(0));
3914   auto &TLI = DAG.getTargetLoweringInfo();
3915   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3916   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3917   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3918   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3919   setValue(&I, N);
3920 }
3921 
3922 void SelectionDAGBuilder::visitBitCast(const User &I) {
3923   SDValue N = getValue(I.getOperand(0));
3924   SDLoc dl = getCurSDLoc();
3925   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3926                                                         I.getType());
3927 
3928   // BitCast assures us that source and destination are the same size so this is
3929   // either a BITCAST or a no-op.
3930   if (DestVT != N.getValueType())
3931     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3932                              DestVT, N)); // convert types.
3933   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3934   // might fold any kind of constant expression to an integer constant and that
3935   // is not what we are looking for. Only recognize a bitcast of a genuine
3936   // constant integer as an opaque constant.
3937   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3938     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3939                                  /*isOpaque*/true));
3940   else
3941     setValue(&I, N);            // noop cast.
3942 }
3943 
3944 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3945   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3946   const Value *SV = I.getOperand(0);
3947   SDValue N = getValue(SV);
3948   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3949 
3950   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3951   unsigned DestAS = I.getType()->getPointerAddressSpace();
3952 
3953   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3954     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3955 
3956   setValue(&I, N);
3957 }
3958 
3959 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3960   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3961   SDValue InVec = getValue(I.getOperand(0));
3962   SDValue InVal = getValue(I.getOperand(1));
3963   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3964                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3965   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3966                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3967                            InVec, InVal, InIdx));
3968 }
3969 
3970 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3972   SDValue InVec = getValue(I.getOperand(0));
3973   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3974                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3975   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3976                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3977                            InVec, InIdx));
3978 }
3979 
3980 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3981   SDValue Src1 = getValue(I.getOperand(0));
3982   SDValue Src2 = getValue(I.getOperand(1));
3983   ArrayRef<int> Mask;
3984   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3985     Mask = SVI->getShuffleMask();
3986   else
3987     Mask = cast<ConstantExpr>(I).getShuffleMask();
3988   SDLoc DL = getCurSDLoc();
3989   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3990   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3991   EVT SrcVT = Src1.getValueType();
3992 
3993   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
3994       VT.isScalableVector()) {
3995     // Canonical splat form of first element of first input vector.
3996     SDValue FirstElt =
3997         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
3998                     DAG.getVectorIdxConstant(0, DL));
3999     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4000     return;
4001   }
4002 
4003   // For now, we only handle splats for scalable vectors.
4004   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4005   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4006   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4007 
4008   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4009   unsigned MaskNumElts = Mask.size();
4010 
4011   if (SrcNumElts == MaskNumElts) {
4012     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4013     return;
4014   }
4015 
4016   // Normalize the shuffle vector since mask and vector length don't match.
4017   if (SrcNumElts < MaskNumElts) {
4018     // Mask is longer than the source vectors. We can use concatenate vector to
4019     // make the mask and vectors lengths match.
4020 
4021     if (MaskNumElts % SrcNumElts == 0) {
4022       // Mask length is a multiple of the source vector length.
4023       // Check if the shuffle is some kind of concatenation of the input
4024       // vectors.
4025       unsigned NumConcat = MaskNumElts / SrcNumElts;
4026       bool IsConcat = true;
4027       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4028       for (unsigned i = 0; i != MaskNumElts; ++i) {
4029         int Idx = Mask[i];
4030         if (Idx < 0)
4031           continue;
4032         // Ensure the indices in each SrcVT sized piece are sequential and that
4033         // the same source is used for the whole piece.
4034         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4035             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4036              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4037           IsConcat = false;
4038           break;
4039         }
4040         // Remember which source this index came from.
4041         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4042       }
4043 
4044       // The shuffle is concatenating multiple vectors together. Just emit
4045       // a CONCAT_VECTORS operation.
4046       if (IsConcat) {
4047         SmallVector<SDValue, 8> ConcatOps;
4048         for (auto Src : ConcatSrcs) {
4049           if (Src < 0)
4050             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4051           else if (Src == 0)
4052             ConcatOps.push_back(Src1);
4053           else
4054             ConcatOps.push_back(Src2);
4055         }
4056         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4057         return;
4058       }
4059     }
4060 
4061     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4062     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4063     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4064                                     PaddedMaskNumElts);
4065 
4066     // Pad both vectors with undefs to make them the same length as the mask.
4067     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4068 
4069     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4070     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4071     MOps1[0] = Src1;
4072     MOps2[0] = Src2;
4073 
4074     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4075     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4076 
4077     // Readjust mask for new input vector length.
4078     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4079     for (unsigned i = 0; i != MaskNumElts; ++i) {
4080       int Idx = Mask[i];
4081       if (Idx >= (int)SrcNumElts)
4082         Idx -= SrcNumElts - PaddedMaskNumElts;
4083       MappedOps[i] = Idx;
4084     }
4085 
4086     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4087 
4088     // If the concatenated vector was padded, extract a subvector with the
4089     // correct number of elements.
4090     if (MaskNumElts != PaddedMaskNumElts)
4091       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4092                            DAG.getVectorIdxConstant(0, DL));
4093 
4094     setValue(&I, Result);
4095     return;
4096   }
4097 
4098   if (SrcNumElts > MaskNumElts) {
4099     // Analyze the access pattern of the vector to see if we can extract
4100     // two subvectors and do the shuffle.
4101     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4102     bool CanExtract = true;
4103     for (int Idx : Mask) {
4104       unsigned Input = 0;
4105       if (Idx < 0)
4106         continue;
4107 
4108       if (Idx >= (int)SrcNumElts) {
4109         Input = 1;
4110         Idx -= SrcNumElts;
4111       }
4112 
4113       // If all the indices come from the same MaskNumElts sized portion of
4114       // the sources we can use extract. Also make sure the extract wouldn't
4115       // extract past the end of the source.
4116       int NewStartIdx = alignDown(Idx, MaskNumElts);
4117       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4118           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4119         CanExtract = false;
4120       // Make sure we always update StartIdx as we use it to track if all
4121       // elements are undef.
4122       StartIdx[Input] = NewStartIdx;
4123     }
4124 
4125     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4126       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4127       return;
4128     }
4129     if (CanExtract) {
4130       // Extract appropriate subvector and generate a vector shuffle
4131       for (unsigned Input = 0; Input < 2; ++Input) {
4132         SDValue &Src = Input == 0 ? Src1 : Src2;
4133         if (StartIdx[Input] < 0)
4134           Src = DAG.getUNDEF(VT);
4135         else {
4136           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4137                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4138         }
4139       }
4140 
4141       // Calculate new mask.
4142       SmallVector<int, 8> MappedOps(Mask);
4143       for (int &Idx : MappedOps) {
4144         if (Idx >= (int)SrcNumElts)
4145           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4146         else if (Idx >= 0)
4147           Idx -= StartIdx[0];
4148       }
4149 
4150       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4151       return;
4152     }
4153   }
4154 
4155   // We can't use either concat vectors or extract subvectors so fall back to
4156   // replacing the shuffle with extract and build vector.
4157   // to insert and build vector.
4158   EVT EltVT = VT.getVectorElementType();
4159   SmallVector<SDValue,8> Ops;
4160   for (int Idx : Mask) {
4161     SDValue Res;
4162 
4163     if (Idx < 0) {
4164       Res = DAG.getUNDEF(EltVT);
4165     } else {
4166       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4167       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4168 
4169       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4170                         DAG.getVectorIdxConstant(Idx, DL));
4171     }
4172 
4173     Ops.push_back(Res);
4174   }
4175 
4176   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4177 }
4178 
4179 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4180   ArrayRef<unsigned> Indices = I.getIndices();
4181   const Value *Op0 = I.getOperand(0);
4182   const Value *Op1 = I.getOperand(1);
4183   Type *AggTy = I.getType();
4184   Type *ValTy = Op1->getType();
4185   bool IntoUndef = isa<UndefValue>(Op0);
4186   bool FromUndef = isa<UndefValue>(Op1);
4187 
4188   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4189 
4190   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4191   SmallVector<EVT, 4> AggValueVTs;
4192   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4193   SmallVector<EVT, 4> ValValueVTs;
4194   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4195 
4196   unsigned NumAggValues = AggValueVTs.size();
4197   unsigned NumValValues = ValValueVTs.size();
4198   SmallVector<SDValue, 4> Values(NumAggValues);
4199 
4200   // Ignore an insertvalue that produces an empty object
4201   if (!NumAggValues) {
4202     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4203     return;
4204   }
4205 
4206   SDValue Agg = getValue(Op0);
4207   unsigned i = 0;
4208   // Copy the beginning value(s) from the original aggregate.
4209   for (; i != LinearIndex; ++i)
4210     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4211                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4212   // Copy values from the inserted value(s).
4213   if (NumValValues) {
4214     SDValue Val = getValue(Op1);
4215     for (; i != LinearIndex + NumValValues; ++i)
4216       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4217                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4218   }
4219   // Copy remaining value(s) from the original aggregate.
4220   for (; i != NumAggValues; ++i)
4221     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4222                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4223 
4224   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4225                            DAG.getVTList(AggValueVTs), Values));
4226 }
4227 
4228 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4229   ArrayRef<unsigned> Indices = I.getIndices();
4230   const Value *Op0 = I.getOperand(0);
4231   Type *AggTy = Op0->getType();
4232   Type *ValTy = I.getType();
4233   bool OutOfUndef = isa<UndefValue>(Op0);
4234 
4235   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4236 
4237   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4238   SmallVector<EVT, 4> ValValueVTs;
4239   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4240 
4241   unsigned NumValValues = ValValueVTs.size();
4242 
4243   // Ignore a extractvalue that produces an empty object
4244   if (!NumValValues) {
4245     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4246     return;
4247   }
4248 
4249   SmallVector<SDValue, 4> Values(NumValValues);
4250 
4251   SDValue Agg = getValue(Op0);
4252   // Copy out the selected value(s).
4253   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4254     Values[i - LinearIndex] =
4255       OutOfUndef ?
4256         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4257         SDValue(Agg.getNode(), Agg.getResNo() + i);
4258 
4259   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4260                            DAG.getVTList(ValValueVTs), Values));
4261 }
4262 
4263 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4264   Value *Op0 = I.getOperand(0);
4265   // Note that the pointer operand may be a vector of pointers. Take the scalar
4266   // element which holds a pointer.
4267   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4268   SDValue N = getValue(Op0);
4269   SDLoc dl = getCurSDLoc();
4270   auto &TLI = DAG.getTargetLoweringInfo();
4271 
4272   // Normalize Vector GEP - all scalar operands should be converted to the
4273   // splat vector.
4274   bool IsVectorGEP = I.getType()->isVectorTy();
4275   ElementCount VectorElementCount =
4276       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4277                   : ElementCount::getFixed(0);
4278 
4279   if (IsVectorGEP && !N.getValueType().isVector()) {
4280     LLVMContext &Context = *DAG.getContext();
4281     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4282     N = DAG.getSplat(VT, dl, N);
4283   }
4284 
4285   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4286        GTI != E; ++GTI) {
4287     const Value *Idx = GTI.getOperand();
4288     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4289       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4290       if (Field) {
4291         // N = N + Offset
4292         uint64_t Offset =
4293             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4294 
4295         // In an inbounds GEP with an offset that is nonnegative even when
4296         // interpreted as signed, assume there is no unsigned overflow.
4297         SDNodeFlags Flags;
4298         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4299           Flags.setNoUnsignedWrap(true);
4300 
4301         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4302                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4303       }
4304     } else {
4305       // IdxSize is the width of the arithmetic according to IR semantics.
4306       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4307       // (and fix up the result later).
4308       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4309       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4310       TypeSize ElementSize =
4311           GTI.getSequentialElementStride(DAG.getDataLayout());
4312       // We intentionally mask away the high bits here; ElementSize may not
4313       // fit in IdxTy.
4314       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4315       bool ElementScalable = ElementSize.isScalable();
4316 
4317       // If this is a scalar constant or a splat vector of constants,
4318       // handle it quickly.
4319       const auto *C = dyn_cast<Constant>(Idx);
4320       if (C && isa<VectorType>(C->getType()))
4321         C = C->getSplatValue();
4322 
4323       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4324       if (CI && CI->isZero())
4325         continue;
4326       if (CI && !ElementScalable) {
4327         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4328         LLVMContext &Context = *DAG.getContext();
4329         SDValue OffsVal;
4330         if (IsVectorGEP)
4331           OffsVal = DAG.getConstant(
4332               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4333         else
4334           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4335 
4336         // In an inbounds GEP with an offset that is nonnegative even when
4337         // interpreted as signed, assume there is no unsigned overflow.
4338         SDNodeFlags Flags;
4339         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4340           Flags.setNoUnsignedWrap(true);
4341 
4342         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4343 
4344         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4345         continue;
4346       }
4347 
4348       // N = N + Idx * ElementMul;
4349       SDValue IdxN = getValue(Idx);
4350 
4351       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4352         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4353                                   VectorElementCount);
4354         IdxN = DAG.getSplat(VT, dl, IdxN);
4355       }
4356 
4357       // If the index is smaller or larger than intptr_t, truncate or extend
4358       // it.
4359       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4360 
4361       if (ElementScalable) {
4362         EVT VScaleTy = N.getValueType().getScalarType();
4363         SDValue VScale = DAG.getNode(
4364             ISD::VSCALE, dl, VScaleTy,
4365             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4366         if (IsVectorGEP)
4367           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4368         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4369       } else {
4370         // If this is a multiply by a power of two, turn it into a shl
4371         // immediately.  This is a very common case.
4372         if (ElementMul != 1) {
4373           if (ElementMul.isPowerOf2()) {
4374             unsigned Amt = ElementMul.logBase2();
4375             IdxN = DAG.getNode(ISD::SHL, dl,
4376                                N.getValueType(), IdxN,
4377                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4378           } else {
4379             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4380                                             IdxN.getValueType());
4381             IdxN = DAG.getNode(ISD::MUL, dl,
4382                                N.getValueType(), IdxN, Scale);
4383           }
4384         }
4385       }
4386 
4387       N = DAG.getNode(ISD::ADD, dl,
4388                       N.getValueType(), N, IdxN);
4389     }
4390   }
4391 
4392   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4393   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4394   if (IsVectorGEP) {
4395     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4396     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4397   }
4398 
4399   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4400     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4401 
4402   setValue(&I, N);
4403 }
4404 
4405 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4406   // If this is a fixed sized alloca in the entry block of the function,
4407   // allocate it statically on the stack.
4408   if (FuncInfo.StaticAllocaMap.count(&I))
4409     return;   // getValue will auto-populate this.
4410 
4411   SDLoc dl = getCurSDLoc();
4412   Type *Ty = I.getAllocatedType();
4413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4414   auto &DL = DAG.getDataLayout();
4415   TypeSize TySize = DL.getTypeAllocSize(Ty);
4416   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4417 
4418   SDValue AllocSize = getValue(I.getArraySize());
4419 
4420   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4421   if (AllocSize.getValueType() != IntPtr)
4422     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4423 
4424   if (TySize.isScalable())
4425     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4426                             DAG.getVScale(dl, IntPtr,
4427                                           APInt(IntPtr.getScalarSizeInBits(),
4428                                                 TySize.getKnownMinValue())));
4429   else {
4430     SDValue TySizeValue =
4431         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4432     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4433                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4434   }
4435 
4436   // Handle alignment.  If the requested alignment is less than or equal to
4437   // the stack alignment, ignore it.  If the size is greater than or equal to
4438   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4439   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4440   if (*Alignment <= StackAlign)
4441     Alignment = std::nullopt;
4442 
4443   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4444   // Round the size of the allocation up to the stack alignment size
4445   // by add SA-1 to the size. This doesn't overflow because we're computing
4446   // an address inside an alloca.
4447   SDNodeFlags Flags;
4448   Flags.setNoUnsignedWrap(true);
4449   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4450                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4451 
4452   // Mask out the low bits for alignment purposes.
4453   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4454                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4455 
4456   SDValue Ops[] = {
4457       getRoot(), AllocSize,
4458       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4459   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4460   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4461   setValue(&I, DSA);
4462   DAG.setRoot(DSA.getValue(1));
4463 
4464   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4465 }
4466 
4467 static const MDNode *getRangeMetadata(const Instruction &I) {
4468   // If !noundef is not present, then !range violation results in a poison
4469   // value rather than immediate undefined behavior. In theory, transferring
4470   // these annotations to SDAG is fine, but in practice there are key SDAG
4471   // transforms that are known not to be poison-safe, such as folding logical
4472   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4473   // also present.
4474   if (!I.hasMetadata(LLVMContext::MD_noundef))
4475     return nullptr;
4476   return I.getMetadata(LLVMContext::MD_range);
4477 }
4478 
4479 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4480   if (I.isAtomic())
4481     return visitAtomicLoad(I);
4482 
4483   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4484   const Value *SV = I.getOperand(0);
4485   if (TLI.supportSwiftError()) {
4486     // Swifterror values can come from either a function parameter with
4487     // swifterror attribute or an alloca with swifterror attribute.
4488     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4489       if (Arg->hasSwiftErrorAttr())
4490         return visitLoadFromSwiftError(I);
4491     }
4492 
4493     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4494       if (Alloca->isSwiftError())
4495         return visitLoadFromSwiftError(I);
4496     }
4497   }
4498 
4499   SDValue Ptr = getValue(SV);
4500 
4501   Type *Ty = I.getType();
4502   SmallVector<EVT, 4> ValueVTs, MemVTs;
4503   SmallVector<TypeSize, 4> Offsets;
4504   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4505   unsigned NumValues = ValueVTs.size();
4506   if (NumValues == 0)
4507     return;
4508 
4509   Align Alignment = I.getAlign();
4510   AAMDNodes AAInfo = I.getAAMetadata();
4511   const MDNode *Ranges = getRangeMetadata(I);
4512   bool isVolatile = I.isVolatile();
4513   MachineMemOperand::Flags MMOFlags =
4514       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4515 
4516   SDValue Root;
4517   bool ConstantMemory = false;
4518   if (isVolatile)
4519     // Serialize volatile loads with other side effects.
4520     Root = getRoot();
4521   else if (NumValues > MaxParallelChains)
4522     Root = getMemoryRoot();
4523   else if (AA &&
4524            AA->pointsToConstantMemory(MemoryLocation(
4525                SV,
4526                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4527                AAInfo))) {
4528     // Do not serialize (non-volatile) loads of constant memory with anything.
4529     Root = DAG.getEntryNode();
4530     ConstantMemory = true;
4531     MMOFlags |= MachineMemOperand::MOInvariant;
4532   } else {
4533     // Do not serialize non-volatile loads against each other.
4534     Root = DAG.getRoot();
4535   }
4536 
4537   SDLoc dl = getCurSDLoc();
4538 
4539   if (isVolatile)
4540     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4541 
4542   SmallVector<SDValue, 4> Values(NumValues);
4543   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4544 
4545   unsigned ChainI = 0;
4546   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4547     // Serializing loads here may result in excessive register pressure, and
4548     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4549     // could recover a bit by hoisting nodes upward in the chain by recognizing
4550     // they are side-effect free or do not alias. The optimizer should really
4551     // avoid this case by converting large object/array copies to llvm.memcpy
4552     // (MaxParallelChains should always remain as failsafe).
4553     if (ChainI == MaxParallelChains) {
4554       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4555       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4556                                   ArrayRef(Chains.data(), ChainI));
4557       Root = Chain;
4558       ChainI = 0;
4559     }
4560 
4561     // TODO: MachinePointerInfo only supports a fixed length offset.
4562     MachinePointerInfo PtrInfo =
4563         !Offsets[i].isScalable() || Offsets[i].isZero()
4564             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4565             : MachinePointerInfo();
4566 
4567     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4568     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4569                             MMOFlags, AAInfo, Ranges);
4570     Chains[ChainI] = L.getValue(1);
4571 
4572     if (MemVTs[i] != ValueVTs[i])
4573       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4574 
4575     Values[i] = L;
4576   }
4577 
4578   if (!ConstantMemory) {
4579     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4580                                 ArrayRef(Chains.data(), ChainI));
4581     if (isVolatile)
4582       DAG.setRoot(Chain);
4583     else
4584       PendingLoads.push_back(Chain);
4585   }
4586 
4587   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4588                            DAG.getVTList(ValueVTs), Values));
4589 }
4590 
4591 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4592   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4593          "call visitStoreToSwiftError when backend supports swifterror");
4594 
4595   SmallVector<EVT, 4> ValueVTs;
4596   SmallVector<uint64_t, 4> Offsets;
4597   const Value *SrcV = I.getOperand(0);
4598   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4599                   SrcV->getType(), ValueVTs, &Offsets, 0);
4600   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4601          "expect a single EVT for swifterror");
4602 
4603   SDValue Src = getValue(SrcV);
4604   // Create a virtual register, then update the virtual register.
4605   Register VReg =
4606       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4607   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4608   // Chain can be getRoot or getControlRoot.
4609   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4610                                       SDValue(Src.getNode(), Src.getResNo()));
4611   DAG.setRoot(CopyNode);
4612 }
4613 
4614 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4615   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4616          "call visitLoadFromSwiftError when backend supports swifterror");
4617 
4618   assert(!I.isVolatile() &&
4619          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4620          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4621          "Support volatile, non temporal, invariant for load_from_swift_error");
4622 
4623   const Value *SV = I.getOperand(0);
4624   Type *Ty = I.getType();
4625   assert(
4626       (!AA ||
4627        !AA->pointsToConstantMemory(MemoryLocation(
4628            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4629            I.getAAMetadata()))) &&
4630       "load_from_swift_error should not be constant memory");
4631 
4632   SmallVector<EVT, 4> ValueVTs;
4633   SmallVector<uint64_t, 4> Offsets;
4634   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4635                   ValueVTs, &Offsets, 0);
4636   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4637          "expect a single EVT for swifterror");
4638 
4639   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4640   SDValue L = DAG.getCopyFromReg(
4641       getRoot(), getCurSDLoc(),
4642       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4643 
4644   setValue(&I, L);
4645 }
4646 
4647 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4648   if (I.isAtomic())
4649     return visitAtomicStore(I);
4650 
4651   const Value *SrcV = I.getOperand(0);
4652   const Value *PtrV = I.getOperand(1);
4653 
4654   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4655   if (TLI.supportSwiftError()) {
4656     // Swifterror values can come from either a function parameter with
4657     // swifterror attribute or an alloca with swifterror attribute.
4658     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4659       if (Arg->hasSwiftErrorAttr())
4660         return visitStoreToSwiftError(I);
4661     }
4662 
4663     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4664       if (Alloca->isSwiftError())
4665         return visitStoreToSwiftError(I);
4666     }
4667   }
4668 
4669   SmallVector<EVT, 4> ValueVTs, MemVTs;
4670   SmallVector<TypeSize, 4> Offsets;
4671   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4672                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4673   unsigned NumValues = ValueVTs.size();
4674   if (NumValues == 0)
4675     return;
4676 
4677   // Get the lowered operands. Note that we do this after
4678   // checking if NumResults is zero, because with zero results
4679   // the operands won't have values in the map.
4680   SDValue Src = getValue(SrcV);
4681   SDValue Ptr = getValue(PtrV);
4682 
4683   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4684   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4685   SDLoc dl = getCurSDLoc();
4686   Align Alignment = I.getAlign();
4687   AAMDNodes AAInfo = I.getAAMetadata();
4688 
4689   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4690 
4691   unsigned ChainI = 0;
4692   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4693     // See visitLoad comments.
4694     if (ChainI == MaxParallelChains) {
4695       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4696                                   ArrayRef(Chains.data(), ChainI));
4697       Root = Chain;
4698       ChainI = 0;
4699     }
4700 
4701     // TODO: MachinePointerInfo only supports a fixed length offset.
4702     MachinePointerInfo PtrInfo =
4703         !Offsets[i].isScalable() || Offsets[i].isZero()
4704             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4705             : MachinePointerInfo();
4706 
4707     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4708     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4709     if (MemVTs[i] != ValueVTs[i])
4710       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4711     SDValue St =
4712         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4713     Chains[ChainI] = St;
4714   }
4715 
4716   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4717                                   ArrayRef(Chains.data(), ChainI));
4718   setValue(&I, StoreNode);
4719   DAG.setRoot(StoreNode);
4720 }
4721 
4722 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4723                                            bool IsCompressing) {
4724   SDLoc sdl = getCurSDLoc();
4725 
4726   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4727                                Align &Alignment) {
4728     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4729     Src0 = I.getArgOperand(0);
4730     Ptr = I.getArgOperand(1);
4731     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4732     Mask = I.getArgOperand(3);
4733   };
4734   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4735                                     Align &Alignment) {
4736     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4737     Src0 = I.getArgOperand(0);
4738     Ptr = I.getArgOperand(1);
4739     Mask = I.getArgOperand(2);
4740     Alignment = I.getParamAlign(1).valueOrOne();
4741   };
4742 
4743   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4744   Align Alignment;
4745   if (IsCompressing)
4746     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4747   else
4748     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4749 
4750   SDValue Ptr = getValue(PtrOperand);
4751   SDValue Src0 = getValue(Src0Operand);
4752   SDValue Mask = getValue(MaskOperand);
4753   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4754 
4755   EVT VT = Src0.getValueType();
4756 
4757   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4758       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
4759       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4760   SDValue StoreNode =
4761       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4762                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4763   DAG.setRoot(StoreNode);
4764   setValue(&I, StoreNode);
4765 }
4766 
4767 // Get a uniform base for the Gather/Scatter intrinsic.
4768 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4769 // We try to represent it as a base pointer + vector of indices.
4770 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4771 // The first operand of the GEP may be a single pointer or a vector of pointers
4772 // Example:
4773 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4774 //  or
4775 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4776 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4777 //
4778 // When the first GEP operand is a single pointer - it is the uniform base we
4779 // are looking for. If first operand of the GEP is a splat vector - we
4780 // extract the splat value and use it as a uniform base.
4781 // In all other cases the function returns 'false'.
4782 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4783                            ISD::MemIndexType &IndexType, SDValue &Scale,
4784                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4785                            uint64_t ElemSize) {
4786   SelectionDAG& DAG = SDB->DAG;
4787   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4788   const DataLayout &DL = DAG.getDataLayout();
4789 
4790   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4791 
4792   // Handle splat constant pointer.
4793   if (auto *C = dyn_cast<Constant>(Ptr)) {
4794     C = C->getSplatValue();
4795     if (!C)
4796       return false;
4797 
4798     Base = SDB->getValue(C);
4799 
4800     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4801     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4802     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4803     IndexType = ISD::SIGNED_SCALED;
4804     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4805     return true;
4806   }
4807 
4808   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4809   if (!GEP || GEP->getParent() != CurBB)
4810     return false;
4811 
4812   if (GEP->getNumOperands() != 2)
4813     return false;
4814 
4815   const Value *BasePtr = GEP->getPointerOperand();
4816   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4817 
4818   // Make sure the base is scalar and the index is a vector.
4819   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4820     return false;
4821 
4822   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4823   if (ScaleVal.isScalable())
4824     return false;
4825 
4826   // Target may not support the required addressing mode.
4827   if (ScaleVal != 1 &&
4828       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4829     return false;
4830 
4831   Base = SDB->getValue(BasePtr);
4832   Index = SDB->getValue(IndexVal);
4833   IndexType = ISD::SIGNED_SCALED;
4834 
4835   Scale =
4836       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4837   return true;
4838 }
4839 
4840 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4841   SDLoc sdl = getCurSDLoc();
4842 
4843   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4844   const Value *Ptr = I.getArgOperand(1);
4845   SDValue Src0 = getValue(I.getArgOperand(0));
4846   SDValue Mask = getValue(I.getArgOperand(3));
4847   EVT VT = Src0.getValueType();
4848   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4849                         ->getMaybeAlignValue()
4850                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4851   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4852 
4853   SDValue Base;
4854   SDValue Index;
4855   ISD::MemIndexType IndexType;
4856   SDValue Scale;
4857   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4858                                     I.getParent(), VT.getScalarStoreSize());
4859 
4860   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4861   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4862       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4863       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4864   if (!UniformBase) {
4865     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4866     Index = getValue(Ptr);
4867     IndexType = ISD::SIGNED_SCALED;
4868     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4869   }
4870 
4871   EVT IdxVT = Index.getValueType();
4872   EVT EltTy = IdxVT.getVectorElementType();
4873   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4874     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4875     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4876   }
4877 
4878   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4879   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4880                                          Ops, MMO, IndexType, false);
4881   DAG.setRoot(Scatter);
4882   setValue(&I, Scatter);
4883 }
4884 
4885 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4886   SDLoc sdl = getCurSDLoc();
4887 
4888   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4889                               Align &Alignment) {
4890     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4891     Ptr = I.getArgOperand(0);
4892     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4893     Mask = I.getArgOperand(2);
4894     Src0 = I.getArgOperand(3);
4895   };
4896   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4897                                  Align &Alignment) {
4898     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4899     Ptr = I.getArgOperand(0);
4900     Alignment = I.getParamAlign(0).valueOrOne();
4901     Mask = I.getArgOperand(1);
4902     Src0 = I.getArgOperand(2);
4903   };
4904 
4905   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4906   Align Alignment;
4907   if (IsExpanding)
4908     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4909   else
4910     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4911 
4912   SDValue Ptr = getValue(PtrOperand);
4913   SDValue Src0 = getValue(Src0Operand);
4914   SDValue Mask = getValue(MaskOperand);
4915   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4916 
4917   EVT VT = Src0.getValueType();
4918   AAMDNodes AAInfo = I.getAAMetadata();
4919   const MDNode *Ranges = getRangeMetadata(I);
4920 
4921   // Do not serialize masked loads of constant memory with anything.
4922   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4923   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4924 
4925   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4926 
4927   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4928       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
4929       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4930 
4931   SDValue Load =
4932       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4933                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4934   if (AddToChain)
4935     PendingLoads.push_back(Load.getValue(1));
4936   setValue(&I, Load);
4937 }
4938 
4939 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4940   SDLoc sdl = getCurSDLoc();
4941 
4942   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4943   const Value *Ptr = I.getArgOperand(0);
4944   SDValue Src0 = getValue(I.getArgOperand(3));
4945   SDValue Mask = getValue(I.getArgOperand(2));
4946 
4947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4948   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4949   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4950                         ->getMaybeAlignValue()
4951                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4952 
4953   const MDNode *Ranges = getRangeMetadata(I);
4954 
4955   SDValue Root = DAG.getRoot();
4956   SDValue Base;
4957   SDValue Index;
4958   ISD::MemIndexType IndexType;
4959   SDValue Scale;
4960   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4961                                     I.getParent(), VT.getScalarStoreSize());
4962   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4963   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4964       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4965       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
4966       Ranges);
4967 
4968   if (!UniformBase) {
4969     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4970     Index = getValue(Ptr);
4971     IndexType = ISD::SIGNED_SCALED;
4972     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4973   }
4974 
4975   EVT IdxVT = Index.getValueType();
4976   EVT EltTy = IdxVT.getVectorElementType();
4977   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4978     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4979     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4980   }
4981 
4982   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
4983   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
4984                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
4985 
4986   PendingLoads.push_back(Gather.getValue(1));
4987   setValue(&I, Gather);
4988 }
4989 
4990 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
4991   SDLoc dl = getCurSDLoc();
4992   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
4993   AtomicOrdering FailureOrdering = I.getFailureOrdering();
4994   SyncScope::ID SSID = I.getSyncScopeID();
4995 
4996   SDValue InChain = getRoot();
4997 
4998   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
4999   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5000 
5001   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5002   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5003 
5004   MachineFunction &MF = DAG.getMachineFunction();
5005   MachineMemOperand *MMO = MF.getMachineMemOperand(
5006       MachinePointerInfo(I.getPointerOperand()), Flags,
5007       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5008       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5009 
5010   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5011                                    dl, MemVT, VTs, InChain,
5012                                    getValue(I.getPointerOperand()),
5013                                    getValue(I.getCompareOperand()),
5014                                    getValue(I.getNewValOperand()), MMO);
5015 
5016   SDValue OutChain = L.getValue(2);
5017 
5018   setValue(&I, L);
5019   DAG.setRoot(OutChain);
5020 }
5021 
5022 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5023   SDLoc dl = getCurSDLoc();
5024   ISD::NodeType NT;
5025   switch (I.getOperation()) {
5026   default: llvm_unreachable("Unknown atomicrmw operation");
5027   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5028   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5029   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5030   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5031   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5032   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5033   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5034   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5035   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5036   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5037   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5038   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5039   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5040   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5041   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5042   case AtomicRMWInst::UIncWrap:
5043     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5044     break;
5045   case AtomicRMWInst::UDecWrap:
5046     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5047     break;
5048   }
5049   AtomicOrdering Ordering = I.getOrdering();
5050   SyncScope::ID SSID = I.getSyncScopeID();
5051 
5052   SDValue InChain = getRoot();
5053 
5054   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5055   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5056   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5057 
5058   MachineFunction &MF = DAG.getMachineFunction();
5059   MachineMemOperand *MMO = MF.getMachineMemOperand(
5060       MachinePointerInfo(I.getPointerOperand()), Flags,
5061       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5062       AAMDNodes(), nullptr, SSID, Ordering);
5063 
5064   SDValue L =
5065     DAG.getAtomic(NT, dl, MemVT, InChain,
5066                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5067                   MMO);
5068 
5069   SDValue OutChain = L.getValue(1);
5070 
5071   setValue(&I, L);
5072   DAG.setRoot(OutChain);
5073 }
5074 
5075 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5076   SDLoc dl = getCurSDLoc();
5077   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5078   SDValue Ops[3];
5079   Ops[0] = getRoot();
5080   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5081                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5082   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5083                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5084   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5085   setValue(&I, N);
5086   DAG.setRoot(N);
5087 }
5088 
5089 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5090   SDLoc dl = getCurSDLoc();
5091   AtomicOrdering Order = I.getOrdering();
5092   SyncScope::ID SSID = I.getSyncScopeID();
5093 
5094   SDValue InChain = getRoot();
5095 
5096   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5097   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5098   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5099 
5100   if (!TLI.supportsUnalignedAtomics() &&
5101       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5102     report_fatal_error("Cannot generate unaligned atomic load");
5103 
5104   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5105 
5106   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5107       MachinePointerInfo(I.getPointerOperand()), Flags,
5108       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5109       nullptr, SSID, Order);
5110 
5111   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5112 
5113   SDValue Ptr = getValue(I.getPointerOperand());
5114   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5115                             Ptr, MMO);
5116 
5117   SDValue OutChain = L.getValue(1);
5118   if (MemVT != VT)
5119     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5120 
5121   setValue(&I, L);
5122   DAG.setRoot(OutChain);
5123 }
5124 
5125 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5126   SDLoc dl = getCurSDLoc();
5127 
5128   AtomicOrdering Ordering = I.getOrdering();
5129   SyncScope::ID SSID = I.getSyncScopeID();
5130 
5131   SDValue InChain = getRoot();
5132 
5133   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5134   EVT MemVT =
5135       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5136 
5137   if (!TLI.supportsUnalignedAtomics() &&
5138       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5139     report_fatal_error("Cannot generate unaligned atomic store");
5140 
5141   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5142 
5143   MachineFunction &MF = DAG.getMachineFunction();
5144   MachineMemOperand *MMO = MF.getMachineMemOperand(
5145       MachinePointerInfo(I.getPointerOperand()), Flags,
5146       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5147       nullptr, SSID, Ordering);
5148 
5149   SDValue Val = getValue(I.getValueOperand());
5150   if (Val.getValueType() != MemVT)
5151     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5152   SDValue Ptr = getValue(I.getPointerOperand());
5153 
5154   SDValue OutChain =
5155       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5156 
5157   setValue(&I, OutChain);
5158   DAG.setRoot(OutChain);
5159 }
5160 
5161 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5162 /// node.
5163 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5164                                                unsigned Intrinsic) {
5165   // Ignore the callsite's attributes. A specific call site may be marked with
5166   // readnone, but the lowering code will expect the chain based on the
5167   // definition.
5168   const Function *F = I.getCalledFunction();
5169   bool HasChain = !F->doesNotAccessMemory();
5170   bool OnlyLoad = HasChain && F->onlyReadsMemory();
5171 
5172   // Build the operand list.
5173   SmallVector<SDValue, 8> Ops;
5174   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5175     if (OnlyLoad) {
5176       // We don't need to serialize loads against other loads.
5177       Ops.push_back(DAG.getRoot());
5178     } else {
5179       Ops.push_back(getRoot());
5180     }
5181   }
5182 
5183   // Info is set by getTgtMemIntrinsic
5184   TargetLowering::IntrinsicInfo Info;
5185   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5186   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5187                                                DAG.getMachineFunction(),
5188                                                Intrinsic);
5189 
5190   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5191   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5192       Info.opc == ISD::INTRINSIC_W_CHAIN)
5193     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5194                                         TLI.getPointerTy(DAG.getDataLayout())));
5195 
5196   // Add all operands of the call to the operand list.
5197   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5198     const Value *Arg = I.getArgOperand(i);
5199     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5200       Ops.push_back(getValue(Arg));
5201       continue;
5202     }
5203 
5204     // Use TargetConstant instead of a regular constant for immarg.
5205     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5206     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5207       assert(CI->getBitWidth() <= 64 &&
5208              "large intrinsic immediates not handled");
5209       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5210     } else {
5211       Ops.push_back(
5212           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5213     }
5214   }
5215 
5216   SmallVector<EVT, 4> ValueVTs;
5217   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5218 
5219   if (HasChain)
5220     ValueVTs.push_back(MVT::Other);
5221 
5222   SDVTList VTs = DAG.getVTList(ValueVTs);
5223 
5224   // Propagate fast-math-flags from IR to node(s).
5225   SDNodeFlags Flags;
5226   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5227     Flags.copyFMF(*FPMO);
5228   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5229 
5230   // Create the node.
5231   SDValue Result;
5232 
5233   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5234     auto *Token = Bundle->Inputs[0].get();
5235     SDValue ConvControlToken = getValue(Token);
5236     assert(Ops.back().getValueType() != MVT::Glue &&
5237            "Did not expected another glue node here.");
5238     ConvControlToken =
5239         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5240     Ops.push_back(ConvControlToken);
5241   }
5242 
5243   // In some cases, custom collection of operands from CallInst I may be needed.
5244   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5245   if (IsTgtIntrinsic) {
5246     // This is target intrinsic that touches memory
5247     //
5248     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5249     //       didn't yield anything useful.
5250     MachinePointerInfo MPI;
5251     if (Info.ptrVal)
5252       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5253     else if (Info.fallbackAddressSpace)
5254       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5255     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5256                                      Info.memVT, MPI, Info.align, Info.flags,
5257                                      Info.size, I.getAAMetadata());
5258   } else if (!HasChain) {
5259     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5260   } else if (!I.getType()->isVoidTy()) {
5261     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5262   } else {
5263     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5264   }
5265 
5266   if (HasChain) {
5267     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5268     if (OnlyLoad)
5269       PendingLoads.push_back(Chain);
5270     else
5271       DAG.setRoot(Chain);
5272   }
5273 
5274   if (!I.getType()->isVoidTy()) {
5275     if (!isa<VectorType>(I.getType()))
5276       Result = lowerRangeToAssertZExt(DAG, I, Result);
5277 
5278     MaybeAlign Alignment = I.getRetAlign();
5279 
5280     // Insert `assertalign` node if there's an alignment.
5281     if (InsertAssertAlign && Alignment) {
5282       Result =
5283           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5284     }
5285 
5286     setValue(&I, Result);
5287   }
5288 }
5289 
5290 /// GetSignificand - Get the significand and build it into a floating-point
5291 /// number with exponent of 1:
5292 ///
5293 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5294 ///
5295 /// where Op is the hexadecimal representation of floating point value.
5296 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5297   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5298                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5299   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5300                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5301   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5302 }
5303 
5304 /// GetExponent - Get the exponent:
5305 ///
5306 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5307 ///
5308 /// where Op is the hexadecimal representation of floating point value.
5309 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5310                            const TargetLowering &TLI, const SDLoc &dl) {
5311   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5312                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5313   SDValue t1 = DAG.getNode(
5314       ISD::SRL, dl, MVT::i32, t0,
5315       DAG.getConstant(23, dl,
5316                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5317   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5318                            DAG.getConstant(127, dl, MVT::i32));
5319   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5320 }
5321 
5322 /// getF32Constant - Get 32-bit floating point constant.
5323 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5324                               const SDLoc &dl) {
5325   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5326                            MVT::f32);
5327 }
5328 
5329 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5330                                        SelectionDAG &DAG) {
5331   // TODO: What fast-math-flags should be set on the floating-point nodes?
5332 
5333   //   IntegerPartOfX = ((int32_t)(t0);
5334   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5335 
5336   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5337   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5338   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5339 
5340   //   IntegerPartOfX <<= 23;
5341   IntegerPartOfX =
5342       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5343                   DAG.getConstant(23, dl,
5344                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5345                                       MVT::i32, DAG.getDataLayout())));
5346 
5347   SDValue TwoToFractionalPartOfX;
5348   if (LimitFloatPrecision <= 6) {
5349     // For floating-point precision of 6:
5350     //
5351     //   TwoToFractionalPartOfX =
5352     //     0.997535578f +
5353     //       (0.735607626f + 0.252464424f * x) * x;
5354     //
5355     // error 0.0144103317, which is 6 bits
5356     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5357                              getF32Constant(DAG, 0x3e814304, dl));
5358     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5359                              getF32Constant(DAG, 0x3f3c50c8, dl));
5360     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5361     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5362                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5363   } else if (LimitFloatPrecision <= 12) {
5364     // For floating-point precision of 12:
5365     //
5366     //   TwoToFractionalPartOfX =
5367     //     0.999892986f +
5368     //       (0.696457318f +
5369     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5370     //
5371     // error 0.000107046256, which is 13 to 14 bits
5372     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5373                              getF32Constant(DAG, 0x3da235e3, dl));
5374     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5375                              getF32Constant(DAG, 0x3e65b8f3, dl));
5376     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5377     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5378                              getF32Constant(DAG, 0x3f324b07, dl));
5379     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5380     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5381                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5382   } else { // LimitFloatPrecision <= 18
5383     // For floating-point precision of 18:
5384     //
5385     //   TwoToFractionalPartOfX =
5386     //     0.999999982f +
5387     //       (0.693148872f +
5388     //         (0.240227044f +
5389     //           (0.554906021e-1f +
5390     //             (0.961591928e-2f +
5391     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5392     // error 2.47208000*10^(-7), which is better than 18 bits
5393     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5394                              getF32Constant(DAG, 0x3924b03e, dl));
5395     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5396                              getF32Constant(DAG, 0x3ab24b87, dl));
5397     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5398     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5399                              getF32Constant(DAG, 0x3c1d8c17, dl));
5400     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5401     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5402                              getF32Constant(DAG, 0x3d634a1d, dl));
5403     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5404     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5405                              getF32Constant(DAG, 0x3e75fe14, dl));
5406     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5407     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5408                               getF32Constant(DAG, 0x3f317234, dl));
5409     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5410     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5411                                          getF32Constant(DAG, 0x3f800000, dl));
5412   }
5413 
5414   // Add the exponent into the result in integer domain.
5415   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5416   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5417                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5418 }
5419 
5420 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5421 /// limited-precision mode.
5422 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5423                          const TargetLowering &TLI, SDNodeFlags Flags) {
5424   if (Op.getValueType() == MVT::f32 &&
5425       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5426 
5427     // Put the exponent in the right bit position for later addition to the
5428     // final result:
5429     //
5430     // t0 = Op * log2(e)
5431 
5432     // TODO: What fast-math-flags should be set here?
5433     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5434                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5435     return getLimitedPrecisionExp2(t0, dl, DAG);
5436   }
5437 
5438   // No special expansion.
5439   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5440 }
5441 
5442 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5443 /// limited-precision mode.
5444 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5445                          const TargetLowering &TLI, SDNodeFlags Flags) {
5446   // TODO: What fast-math-flags should be set on the floating-point nodes?
5447 
5448   if (Op.getValueType() == MVT::f32 &&
5449       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5450     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5451 
5452     // Scale the exponent by log(2).
5453     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5454     SDValue LogOfExponent =
5455         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5456                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5457 
5458     // Get the significand and build it into a floating-point number with
5459     // exponent of 1.
5460     SDValue X = GetSignificand(DAG, Op1, dl);
5461 
5462     SDValue LogOfMantissa;
5463     if (LimitFloatPrecision <= 6) {
5464       // For floating-point precision of 6:
5465       //
5466       //   LogofMantissa =
5467       //     -1.1609546f +
5468       //       (1.4034025f - 0.23903021f * x) * x;
5469       //
5470       // error 0.0034276066, which is better than 8 bits
5471       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5472                                getF32Constant(DAG, 0xbe74c456, dl));
5473       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5474                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5475       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5476       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5477                                   getF32Constant(DAG, 0x3f949a29, dl));
5478     } else if (LimitFloatPrecision <= 12) {
5479       // For floating-point precision of 12:
5480       //
5481       //   LogOfMantissa =
5482       //     -1.7417939f +
5483       //       (2.8212026f +
5484       //         (-1.4699568f +
5485       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5486       //
5487       // error 0.000061011436, which is 14 bits
5488       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5489                                getF32Constant(DAG, 0xbd67b6d6, dl));
5490       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5491                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5492       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5493       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5494                                getF32Constant(DAG, 0x3fbc278b, dl));
5495       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5496       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5497                                getF32Constant(DAG, 0x40348e95, dl));
5498       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5499       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5500                                   getF32Constant(DAG, 0x3fdef31a, dl));
5501     } else { // LimitFloatPrecision <= 18
5502       // For floating-point precision of 18:
5503       //
5504       //   LogOfMantissa =
5505       //     -2.1072184f +
5506       //       (4.2372794f +
5507       //         (-3.7029485f +
5508       //           (2.2781945f +
5509       //             (-0.87823314f +
5510       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5511       //
5512       // error 0.0000023660568, which is better than 18 bits
5513       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5514                                getF32Constant(DAG, 0xbc91e5ac, dl));
5515       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5516                                getF32Constant(DAG, 0x3e4350aa, dl));
5517       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5518       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5519                                getF32Constant(DAG, 0x3f60d3e3, dl));
5520       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5521       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5522                                getF32Constant(DAG, 0x4011cdf0, dl));
5523       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5524       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5525                                getF32Constant(DAG, 0x406cfd1c, dl));
5526       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5527       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5528                                getF32Constant(DAG, 0x408797cb, dl));
5529       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5530       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5531                                   getF32Constant(DAG, 0x4006dcab, dl));
5532     }
5533 
5534     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5535   }
5536 
5537   // No special expansion.
5538   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5539 }
5540 
5541 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5542 /// limited-precision mode.
5543 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5544                           const TargetLowering &TLI, SDNodeFlags Flags) {
5545   // TODO: What fast-math-flags should be set on the floating-point nodes?
5546 
5547   if (Op.getValueType() == MVT::f32 &&
5548       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5549     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5550 
5551     // Get the exponent.
5552     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5553 
5554     // Get the significand and build it into a floating-point number with
5555     // exponent of 1.
5556     SDValue X = GetSignificand(DAG, Op1, dl);
5557 
5558     // Different possible minimax approximations of significand in
5559     // floating-point for various degrees of accuracy over [1,2].
5560     SDValue Log2ofMantissa;
5561     if (LimitFloatPrecision <= 6) {
5562       // For floating-point precision of 6:
5563       //
5564       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5565       //
5566       // error 0.0049451742, which is more than 7 bits
5567       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5568                                getF32Constant(DAG, 0xbeb08fe0, dl));
5569       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5570                                getF32Constant(DAG, 0x40019463, dl));
5571       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5572       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5573                                    getF32Constant(DAG, 0x3fd6633d, dl));
5574     } else if (LimitFloatPrecision <= 12) {
5575       // For floating-point precision of 12:
5576       //
5577       //   Log2ofMantissa =
5578       //     -2.51285454f +
5579       //       (4.07009056f +
5580       //         (-2.12067489f +
5581       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5582       //
5583       // error 0.0000876136000, which is better than 13 bits
5584       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5585                                getF32Constant(DAG, 0xbda7262e, dl));
5586       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5587                                getF32Constant(DAG, 0x3f25280b, dl));
5588       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5589       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5590                                getF32Constant(DAG, 0x4007b923, dl));
5591       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5592       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5593                                getF32Constant(DAG, 0x40823e2f, dl));
5594       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5595       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5596                                    getF32Constant(DAG, 0x4020d29c, dl));
5597     } else { // LimitFloatPrecision <= 18
5598       // For floating-point precision of 18:
5599       //
5600       //   Log2ofMantissa =
5601       //     -3.0400495f +
5602       //       (6.1129976f +
5603       //         (-5.3420409f +
5604       //           (3.2865683f +
5605       //             (-1.2669343f +
5606       //               (0.27515199f -
5607       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5608       //
5609       // error 0.0000018516, which is better than 18 bits
5610       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5611                                getF32Constant(DAG, 0xbcd2769e, dl));
5612       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5613                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5614       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5615       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5616                                getF32Constant(DAG, 0x3fa22ae7, dl));
5617       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5618       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5619                                getF32Constant(DAG, 0x40525723, dl));
5620       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5621       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5622                                getF32Constant(DAG, 0x40aaf200, dl));
5623       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5624       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5625                                getF32Constant(DAG, 0x40c39dad, dl));
5626       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5627       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5628                                    getF32Constant(DAG, 0x4042902c, dl));
5629     }
5630 
5631     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5632   }
5633 
5634   // No special expansion.
5635   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5636 }
5637 
5638 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5639 /// limited-precision mode.
5640 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5641                            const TargetLowering &TLI, SDNodeFlags Flags) {
5642   // TODO: What fast-math-flags should be set on the floating-point nodes?
5643 
5644   if (Op.getValueType() == MVT::f32 &&
5645       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5646     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5647 
5648     // Scale the exponent by log10(2) [0.30102999f].
5649     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5650     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5651                                         getF32Constant(DAG, 0x3e9a209a, dl));
5652 
5653     // Get the significand and build it into a floating-point number with
5654     // exponent of 1.
5655     SDValue X = GetSignificand(DAG, Op1, dl);
5656 
5657     SDValue Log10ofMantissa;
5658     if (LimitFloatPrecision <= 6) {
5659       // For floating-point precision of 6:
5660       //
5661       //   Log10ofMantissa =
5662       //     -0.50419619f +
5663       //       (0.60948995f - 0.10380950f * x) * x;
5664       //
5665       // error 0.0014886165, which is 6 bits
5666       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5667                                getF32Constant(DAG, 0xbdd49a13, dl));
5668       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5669                                getF32Constant(DAG, 0x3f1c0789, dl));
5670       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5671       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5672                                     getF32Constant(DAG, 0x3f011300, dl));
5673     } else if (LimitFloatPrecision <= 12) {
5674       // For floating-point precision of 12:
5675       //
5676       //   Log10ofMantissa =
5677       //     -0.64831180f +
5678       //       (0.91751397f +
5679       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5680       //
5681       // error 0.00019228036, which is better than 12 bits
5682       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5683                                getF32Constant(DAG, 0x3d431f31, dl));
5684       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5685                                getF32Constant(DAG, 0x3ea21fb2, dl));
5686       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5687       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5688                                getF32Constant(DAG, 0x3f6ae232, dl));
5689       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5690       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5691                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5692     } else { // LimitFloatPrecision <= 18
5693       // For floating-point precision of 18:
5694       //
5695       //   Log10ofMantissa =
5696       //     -0.84299375f +
5697       //       (1.5327582f +
5698       //         (-1.0688956f +
5699       //           (0.49102474f +
5700       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5701       //
5702       // error 0.0000037995730, which is better than 18 bits
5703       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5704                                getF32Constant(DAG, 0x3c5d51ce, dl));
5705       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5706                                getF32Constant(DAG, 0x3e00685a, dl));
5707       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5708       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5709                                getF32Constant(DAG, 0x3efb6798, dl));
5710       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5711       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5712                                getF32Constant(DAG, 0x3f88d192, dl));
5713       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5714       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5715                                getF32Constant(DAG, 0x3fc4316c, dl));
5716       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5717       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5718                                     getF32Constant(DAG, 0x3f57ce70, dl));
5719     }
5720 
5721     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5722   }
5723 
5724   // No special expansion.
5725   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5726 }
5727 
5728 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5729 /// limited-precision mode.
5730 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5731                           const TargetLowering &TLI, SDNodeFlags Flags) {
5732   if (Op.getValueType() == MVT::f32 &&
5733       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5734     return getLimitedPrecisionExp2(Op, dl, DAG);
5735 
5736   // No special expansion.
5737   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5738 }
5739 
5740 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5741 /// limited-precision mode with x == 10.0f.
5742 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5743                          SelectionDAG &DAG, const TargetLowering &TLI,
5744                          SDNodeFlags Flags) {
5745   bool IsExp10 = false;
5746   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5747       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5748     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5749       APFloat Ten(10.0f);
5750       IsExp10 = LHSC->isExactlyValue(Ten);
5751     }
5752   }
5753 
5754   // TODO: What fast-math-flags should be set on the FMUL node?
5755   if (IsExp10) {
5756     // Put the exponent in the right bit position for later addition to the
5757     // final result:
5758     //
5759     //   #define LOG2OF10 3.3219281f
5760     //   t0 = Op * LOG2OF10;
5761     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5762                              getF32Constant(DAG, 0x40549a78, dl));
5763     return getLimitedPrecisionExp2(t0, dl, DAG);
5764   }
5765 
5766   // No special expansion.
5767   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5768 }
5769 
5770 /// ExpandPowI - Expand a llvm.powi intrinsic.
5771 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5772                           SelectionDAG &DAG) {
5773   // If RHS is a constant, we can expand this out to a multiplication tree if
5774   // it's beneficial on the target, otherwise we end up lowering to a call to
5775   // __powidf2 (for example).
5776   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5777     unsigned Val = RHSC->getSExtValue();
5778 
5779     // powi(x, 0) -> 1.0
5780     if (Val == 0)
5781       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5782 
5783     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5784             Val, DAG.shouldOptForSize())) {
5785       // Get the exponent as a positive value.
5786       if ((int)Val < 0)
5787         Val = -Val;
5788       // We use the simple binary decomposition method to generate the multiply
5789       // sequence.  There are more optimal ways to do this (for example,
5790       // powi(x,15) generates one more multiply than it should), but this has
5791       // the benefit of being both really simple and much better than a libcall.
5792       SDValue Res; // Logically starts equal to 1.0
5793       SDValue CurSquare = LHS;
5794       // TODO: Intrinsics should have fast-math-flags that propagate to these
5795       // nodes.
5796       while (Val) {
5797         if (Val & 1) {
5798           if (Res.getNode())
5799             Res =
5800                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5801           else
5802             Res = CurSquare; // 1.0*CurSquare.
5803         }
5804 
5805         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5806                                 CurSquare, CurSquare);
5807         Val >>= 1;
5808       }
5809 
5810       // If the original was negative, invert the result, producing 1/(x*x*x).
5811       if (RHSC->getSExtValue() < 0)
5812         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5813                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5814       return Res;
5815     }
5816   }
5817 
5818   // Otherwise, expand to a libcall.
5819   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5820 }
5821 
5822 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5823                             SDValue LHS, SDValue RHS, SDValue Scale,
5824                             SelectionDAG &DAG, const TargetLowering &TLI) {
5825   EVT VT = LHS.getValueType();
5826   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5827   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5828   LLVMContext &Ctx = *DAG.getContext();
5829 
5830   // If the type is legal but the operation isn't, this node might survive all
5831   // the way to operation legalization. If we end up there and we do not have
5832   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5833   // node.
5834 
5835   // Coax the legalizer into expanding the node during type legalization instead
5836   // by bumping the size by one bit. This will force it to Promote, enabling the
5837   // early expansion and avoiding the need to expand later.
5838 
5839   // We don't have to do this if Scale is 0; that can always be expanded, unless
5840   // it's a saturating signed operation. Those can experience true integer
5841   // division overflow, a case which we must avoid.
5842 
5843   // FIXME: We wouldn't have to do this (or any of the early
5844   // expansion/promotion) if it was possible to expand a libcall of an
5845   // illegal type during operation legalization. But it's not, so things
5846   // get a bit hacky.
5847   unsigned ScaleInt = Scale->getAsZExtVal();
5848   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5849       (TLI.isTypeLegal(VT) ||
5850        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5851     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5852         Opcode, VT, ScaleInt);
5853     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5854       EVT PromVT;
5855       if (VT.isScalarInteger())
5856         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5857       else if (VT.isVector()) {
5858         PromVT = VT.getVectorElementType();
5859         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5860         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5861       } else
5862         llvm_unreachable("Wrong VT for DIVFIX?");
5863       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5864       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5865       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5866       // For saturating operations, we need to shift up the LHS to get the
5867       // proper saturation width, and then shift down again afterwards.
5868       if (Saturating)
5869         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5870                           DAG.getConstant(1, DL, ShiftTy));
5871       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5872       if (Saturating)
5873         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5874                           DAG.getConstant(1, DL, ShiftTy));
5875       return DAG.getZExtOrTrunc(Res, DL, VT);
5876     }
5877   }
5878 
5879   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5880 }
5881 
5882 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5883 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5884 static void
5885 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5886                      const SDValue &N) {
5887   switch (N.getOpcode()) {
5888   case ISD::CopyFromReg: {
5889     SDValue Op = N.getOperand(1);
5890     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5891                       Op.getValueType().getSizeInBits());
5892     return;
5893   }
5894   case ISD::BITCAST:
5895   case ISD::AssertZext:
5896   case ISD::AssertSext:
5897   case ISD::TRUNCATE:
5898     getUnderlyingArgRegs(Regs, N.getOperand(0));
5899     return;
5900   case ISD::BUILD_PAIR:
5901   case ISD::BUILD_VECTOR:
5902   case ISD::CONCAT_VECTORS:
5903     for (SDValue Op : N->op_values())
5904       getUnderlyingArgRegs(Regs, Op);
5905     return;
5906   default:
5907     return;
5908   }
5909 }
5910 
5911 /// If the DbgValueInst is a dbg_value of a function argument, create the
5912 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5913 /// instruction selection, they will be inserted to the entry BB.
5914 /// We don't currently support this for variadic dbg_values, as they shouldn't
5915 /// appear for function arguments or in the prologue.
5916 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5917     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5918     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5919   const Argument *Arg = dyn_cast<Argument>(V);
5920   if (!Arg)
5921     return false;
5922 
5923   MachineFunction &MF = DAG.getMachineFunction();
5924   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5925 
5926   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5927   // we've been asked to pursue.
5928   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5929                               bool Indirect) {
5930     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5931       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5932       // pointing at the VReg, which will be patched up later.
5933       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5934       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5935           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5936           /* isKill */ false, /* isDead */ false,
5937           /* isUndef */ false, /* isEarlyClobber */ false,
5938           /* SubReg */ 0, /* isDebug */ true)});
5939 
5940       auto *NewDIExpr = FragExpr;
5941       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5942       // the DIExpression.
5943       if (Indirect)
5944         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5945       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5946       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5947       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5948     } else {
5949       // Create a completely standard DBG_VALUE.
5950       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5951       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5952     }
5953   };
5954 
5955   if (Kind == FuncArgumentDbgValueKind::Value) {
5956     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5957     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5958     // the entry block.
5959     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5960     if (!IsInEntryBlock)
5961       return false;
5962 
5963     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5964     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5965     // variable that also is a param.
5966     //
5967     // Although, if we are at the top of the entry block already, we can still
5968     // emit using ArgDbgValue. This might catch some situations when the
5969     // dbg.value refers to an argument that isn't used in the entry block, so
5970     // any CopyToReg node would be optimized out and the only way to express
5971     // this DBG_VALUE is by using the physical reg (or FI) as done in this
5972     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
5973     // we should only emit as ArgDbgValue if the Variable is an argument to the
5974     // current function, and the dbg.value intrinsic is found in the entry
5975     // block.
5976     bool VariableIsFunctionInputArg = Variable->isParameter() &&
5977         !DL->getInlinedAt();
5978     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
5979     if (!IsInPrologue && !VariableIsFunctionInputArg)
5980       return false;
5981 
5982     // Here we assume that a function argument on IR level only can be used to
5983     // describe one input parameter on source level. If we for example have
5984     // source code like this
5985     //
5986     //    struct A { long x, y; };
5987     //    void foo(struct A a, long b) {
5988     //      ...
5989     //      b = a.x;
5990     //      ...
5991     //    }
5992     //
5993     // and IR like this
5994     //
5995     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
5996     //  entry:
5997     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
5998     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
5999     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6000     //    ...
6001     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6002     //    ...
6003     //
6004     // then the last dbg.value is describing a parameter "b" using a value that
6005     // is an argument. But since we already has used %a1 to describe a parameter
6006     // we should not handle that last dbg.value here (that would result in an
6007     // incorrect hoisting of the DBG_VALUE to the function entry).
6008     // Notice that we allow one dbg.value per IR level argument, to accommodate
6009     // for the situation with fragments above.
6010     // If there is no node for the value being handled, we return true to skip
6011     // the normal generation of debug info, as it would kill existing debug
6012     // info for the parameter in case of duplicates.
6013     if (VariableIsFunctionInputArg) {
6014       unsigned ArgNo = Arg->getArgNo();
6015       if (ArgNo >= FuncInfo.DescribedArgs.size())
6016         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6017       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6018         return !NodeMap[V].getNode();
6019       FuncInfo.DescribedArgs.set(ArgNo);
6020     }
6021   }
6022 
6023   bool IsIndirect = false;
6024   std::optional<MachineOperand> Op;
6025   // Some arguments' frame index is recorded during argument lowering.
6026   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6027   if (FI != std::numeric_limits<int>::max())
6028     Op = MachineOperand::CreateFI(FI);
6029 
6030   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
6031   if (!Op && N.getNode()) {
6032     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6033     Register Reg;
6034     if (ArgRegsAndSizes.size() == 1)
6035       Reg = ArgRegsAndSizes.front().first;
6036 
6037     if (Reg && Reg.isVirtual()) {
6038       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6039       Register PR = RegInfo.getLiveInPhysReg(Reg);
6040       if (PR)
6041         Reg = PR;
6042     }
6043     if (Reg) {
6044       Op = MachineOperand::CreateReg(Reg, false);
6045       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6046     }
6047   }
6048 
6049   if (!Op && N.getNode()) {
6050     // Check if frame index is available.
6051     SDValue LCandidate = peekThroughBitcasts(N);
6052     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6053       if (FrameIndexSDNode *FINode =
6054           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6055         Op = MachineOperand::CreateFI(FINode->getIndex());
6056   }
6057 
6058   if (!Op) {
6059     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6060     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
6061                                          SplitRegs) {
6062       unsigned Offset = 0;
6063       for (const auto &RegAndSize : SplitRegs) {
6064         // If the expression is already a fragment, the current register
6065         // offset+size might extend beyond the fragment. In this case, only
6066         // the register bits that are inside the fragment are relevant.
6067         int RegFragmentSizeInBits = RegAndSize.second;
6068         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6069           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6070           // The register is entirely outside the expression fragment,
6071           // so is irrelevant for debug info.
6072           if (Offset >= ExprFragmentSizeInBits)
6073             break;
6074           // The register is partially outside the expression fragment, only
6075           // the low bits within the fragment are relevant for debug info.
6076           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6077             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6078           }
6079         }
6080 
6081         auto FragmentExpr = DIExpression::createFragmentExpression(
6082             Expr, Offset, RegFragmentSizeInBits);
6083         Offset += RegAndSize.second;
6084         // If a valid fragment expression cannot be created, the variable's
6085         // correct value cannot be determined and so it is set as Undef.
6086         if (!FragmentExpr) {
6087           SDDbgValue *SDV = DAG.getConstantDbgValue(
6088               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6089           DAG.AddDbgValue(SDV, false);
6090           continue;
6091         }
6092         MachineInstr *NewMI =
6093             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6094                              Kind != FuncArgumentDbgValueKind::Value);
6095         FuncInfo.ArgDbgValues.push_back(NewMI);
6096       }
6097     };
6098 
6099     // Check if ValueMap has reg number.
6100     DenseMap<const Value *, Register>::const_iterator
6101       VMI = FuncInfo.ValueMap.find(V);
6102     if (VMI != FuncInfo.ValueMap.end()) {
6103       const auto &TLI = DAG.getTargetLoweringInfo();
6104       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6105                        V->getType(), std::nullopt);
6106       if (RFV.occupiesMultipleRegs()) {
6107         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6108         return true;
6109       }
6110 
6111       Op = MachineOperand::CreateReg(VMI->second, false);
6112       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6113     } else if (ArgRegsAndSizes.size() > 1) {
6114       // This was split due to the calling convention, and no virtual register
6115       // mapping exists for the value.
6116       splitMultiRegDbgValue(ArgRegsAndSizes);
6117       return true;
6118     }
6119   }
6120 
6121   if (!Op)
6122     return false;
6123 
6124   assert(Variable->isValidLocationForIntrinsic(DL) &&
6125          "Expected inlined-at fields to agree");
6126   MachineInstr *NewMI = nullptr;
6127 
6128   if (Op->isReg())
6129     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6130   else
6131     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6132                     Variable, Expr);
6133 
6134   // Otherwise, use ArgDbgValues.
6135   FuncInfo.ArgDbgValues.push_back(NewMI);
6136   return true;
6137 }
6138 
6139 /// Return the appropriate SDDbgValue based on N.
6140 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6141                                              DILocalVariable *Variable,
6142                                              DIExpression *Expr,
6143                                              const DebugLoc &dl,
6144                                              unsigned DbgSDNodeOrder) {
6145   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6146     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6147     // stack slot locations.
6148     //
6149     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6150     // debug values here after optimization:
6151     //
6152     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6153     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6154     //
6155     // Both describe the direct values of their associated variables.
6156     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6157                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6158   }
6159   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6160                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6161 }
6162 
6163 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6164   switch (Intrinsic) {
6165   case Intrinsic::smul_fix:
6166     return ISD::SMULFIX;
6167   case Intrinsic::umul_fix:
6168     return ISD::UMULFIX;
6169   case Intrinsic::smul_fix_sat:
6170     return ISD::SMULFIXSAT;
6171   case Intrinsic::umul_fix_sat:
6172     return ISD::UMULFIXSAT;
6173   case Intrinsic::sdiv_fix:
6174     return ISD::SDIVFIX;
6175   case Intrinsic::udiv_fix:
6176     return ISD::UDIVFIX;
6177   case Intrinsic::sdiv_fix_sat:
6178     return ISD::SDIVFIXSAT;
6179   case Intrinsic::udiv_fix_sat:
6180     return ISD::UDIVFIXSAT;
6181   default:
6182     llvm_unreachable("Unhandled fixed point intrinsic");
6183   }
6184 }
6185 
6186 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6187                                            const char *FunctionName) {
6188   assert(FunctionName && "FunctionName must not be nullptr");
6189   SDValue Callee = DAG.getExternalSymbol(
6190       FunctionName,
6191       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6192   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6193 }
6194 
6195 /// Given a @llvm.call.preallocated.setup, return the corresponding
6196 /// preallocated call.
6197 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6198   assert(cast<CallBase>(PreallocatedSetup)
6199                  ->getCalledFunction()
6200                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6201          "expected call_preallocated_setup Value");
6202   for (const auto *U : PreallocatedSetup->users()) {
6203     auto *UseCall = cast<CallBase>(U);
6204     const Function *Fn = UseCall->getCalledFunction();
6205     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6206       return UseCall;
6207     }
6208   }
6209   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6210 }
6211 
6212 /// If DI is a debug value with an EntryValue expression, lower it using the
6213 /// corresponding physical register of the associated Argument value
6214 /// (guaranteed to exist by the verifier).
6215 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6216     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6217     DIExpression *Expr, DebugLoc DbgLoc) {
6218   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6219     return false;
6220 
6221   // These properties are guaranteed by the verifier.
6222   const Argument *Arg = cast<Argument>(Values[0]);
6223   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6224 
6225   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6226   if (ArgIt == FuncInfo.ValueMap.end()) {
6227     LLVM_DEBUG(
6228         dbgs() << "Dropping dbg.value: expression is entry_value but "
6229                   "couldn't find an associated register for the Argument\n");
6230     return true;
6231   }
6232   Register ArgVReg = ArgIt->getSecond();
6233 
6234   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6235     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6236       SDDbgValue *SDV = DAG.getVRegDbgValue(
6237           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6238       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6239       return true;
6240     }
6241   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6242                        "couldn't find a physical register\n");
6243   return true;
6244 }
6245 
6246 /// Lower the call to the specified intrinsic function.
6247 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6248                                                   unsigned Intrinsic) {
6249   SDLoc sdl = getCurSDLoc();
6250   switch (Intrinsic) {
6251   case Intrinsic::experimental_convergence_anchor:
6252     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6253     break;
6254   case Intrinsic::experimental_convergence_entry:
6255     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6256     break;
6257   case Intrinsic::experimental_convergence_loop: {
6258     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6259     auto *Token = Bundle->Inputs[0].get();
6260     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6261                              getValue(Token)));
6262     break;
6263   }
6264   }
6265 }
6266 
6267 /// Lower the call to the specified intrinsic function.
6268 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6269                                              unsigned Intrinsic) {
6270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6271   SDLoc sdl = getCurSDLoc();
6272   DebugLoc dl = getCurDebugLoc();
6273   SDValue Res;
6274 
6275   SDNodeFlags Flags;
6276   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6277     Flags.copyFMF(*FPOp);
6278 
6279   switch (Intrinsic) {
6280   default:
6281     // By default, turn this into a target intrinsic node.
6282     visitTargetIntrinsic(I, Intrinsic);
6283     return;
6284   case Intrinsic::vscale: {
6285     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6286     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6287     return;
6288   }
6289   case Intrinsic::vastart:  visitVAStart(I); return;
6290   case Intrinsic::vaend:    visitVAEnd(I); return;
6291   case Intrinsic::vacopy:   visitVACopy(I); return;
6292   case Intrinsic::returnaddress:
6293     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6294                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6295                              getValue(I.getArgOperand(0))));
6296     return;
6297   case Intrinsic::addressofreturnaddress:
6298     setValue(&I,
6299              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6300                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6301     return;
6302   case Intrinsic::sponentry:
6303     setValue(&I,
6304              DAG.getNode(ISD::SPONENTRY, sdl,
6305                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6306     return;
6307   case Intrinsic::frameaddress:
6308     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6309                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6310                              getValue(I.getArgOperand(0))));
6311     return;
6312   case Intrinsic::read_volatile_register:
6313   case Intrinsic::read_register: {
6314     Value *Reg = I.getArgOperand(0);
6315     SDValue Chain = getRoot();
6316     SDValue RegName =
6317         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6318     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6319     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6320       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6321     setValue(&I, Res);
6322     DAG.setRoot(Res.getValue(1));
6323     return;
6324   }
6325   case Intrinsic::write_register: {
6326     Value *Reg = I.getArgOperand(0);
6327     Value *RegValue = I.getArgOperand(1);
6328     SDValue Chain = getRoot();
6329     SDValue RegName =
6330         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6331     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6332                             RegName, getValue(RegValue)));
6333     return;
6334   }
6335   case Intrinsic::memcpy: {
6336     const auto &MCI = cast<MemCpyInst>(I);
6337     SDValue Op1 = getValue(I.getArgOperand(0));
6338     SDValue Op2 = getValue(I.getArgOperand(1));
6339     SDValue Op3 = getValue(I.getArgOperand(2));
6340     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6341     Align DstAlign = MCI.getDestAlign().valueOrOne();
6342     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6343     Align Alignment = std::min(DstAlign, SrcAlign);
6344     bool isVol = MCI.isVolatile();
6345     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6346     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6347     // node.
6348     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6349     SDValue MC = DAG.getMemcpy(
6350         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6351         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6352         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6353     updateDAGForMaybeTailCall(MC);
6354     return;
6355   }
6356   case Intrinsic::memcpy_inline: {
6357     const auto &MCI = cast<MemCpyInlineInst>(I);
6358     SDValue Dst = getValue(I.getArgOperand(0));
6359     SDValue Src = getValue(I.getArgOperand(1));
6360     SDValue Size = getValue(I.getArgOperand(2));
6361     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6362     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6363     Align DstAlign = MCI.getDestAlign().valueOrOne();
6364     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6365     Align Alignment = std::min(DstAlign, SrcAlign);
6366     bool isVol = MCI.isVolatile();
6367     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6368     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6369     // node.
6370     SDValue MC = DAG.getMemcpy(
6371         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6372         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6373         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6374     updateDAGForMaybeTailCall(MC);
6375     return;
6376   }
6377   case Intrinsic::memset: {
6378     const auto &MSI = cast<MemSetInst>(I);
6379     SDValue Op1 = getValue(I.getArgOperand(0));
6380     SDValue Op2 = getValue(I.getArgOperand(1));
6381     SDValue Op3 = getValue(I.getArgOperand(2));
6382     // @llvm.memset defines 0 and 1 to both mean no alignment.
6383     Align Alignment = MSI.getDestAlign().valueOrOne();
6384     bool isVol = MSI.isVolatile();
6385     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6386     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6387     SDValue MS = DAG.getMemset(
6388         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6389         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6390     updateDAGForMaybeTailCall(MS);
6391     return;
6392   }
6393   case Intrinsic::memset_inline: {
6394     const auto &MSII = cast<MemSetInlineInst>(I);
6395     SDValue Dst = getValue(I.getArgOperand(0));
6396     SDValue Value = getValue(I.getArgOperand(1));
6397     SDValue Size = getValue(I.getArgOperand(2));
6398     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6399     // @llvm.memset defines 0 and 1 to both mean no alignment.
6400     Align DstAlign = MSII.getDestAlign().valueOrOne();
6401     bool isVol = MSII.isVolatile();
6402     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6403     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6404     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6405                                /* AlwaysInline */ true, isTC,
6406                                MachinePointerInfo(I.getArgOperand(0)),
6407                                I.getAAMetadata());
6408     updateDAGForMaybeTailCall(MC);
6409     return;
6410   }
6411   case Intrinsic::memmove: {
6412     const auto &MMI = cast<MemMoveInst>(I);
6413     SDValue Op1 = getValue(I.getArgOperand(0));
6414     SDValue Op2 = getValue(I.getArgOperand(1));
6415     SDValue Op3 = getValue(I.getArgOperand(2));
6416     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6417     Align DstAlign = MMI.getDestAlign().valueOrOne();
6418     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6419     Align Alignment = std::min(DstAlign, SrcAlign);
6420     bool isVol = MMI.isVolatile();
6421     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6422     // FIXME: Support passing different dest/src alignments to the memmove DAG
6423     // node.
6424     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6425     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6426                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6427                                 MachinePointerInfo(I.getArgOperand(1)),
6428                                 I.getAAMetadata(), AA);
6429     updateDAGForMaybeTailCall(MM);
6430     return;
6431   }
6432   case Intrinsic::memcpy_element_unordered_atomic: {
6433     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6434     SDValue Dst = getValue(MI.getRawDest());
6435     SDValue Src = getValue(MI.getRawSource());
6436     SDValue Length = getValue(MI.getLength());
6437 
6438     Type *LengthTy = MI.getLength()->getType();
6439     unsigned ElemSz = MI.getElementSizeInBytes();
6440     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6441     SDValue MC =
6442         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6443                             isTC, MachinePointerInfo(MI.getRawDest()),
6444                             MachinePointerInfo(MI.getRawSource()));
6445     updateDAGForMaybeTailCall(MC);
6446     return;
6447   }
6448   case Intrinsic::memmove_element_unordered_atomic: {
6449     auto &MI = cast<AtomicMemMoveInst>(I);
6450     SDValue Dst = getValue(MI.getRawDest());
6451     SDValue Src = getValue(MI.getRawSource());
6452     SDValue Length = getValue(MI.getLength());
6453 
6454     Type *LengthTy = MI.getLength()->getType();
6455     unsigned ElemSz = MI.getElementSizeInBytes();
6456     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6457     SDValue MC =
6458         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6459                              isTC, MachinePointerInfo(MI.getRawDest()),
6460                              MachinePointerInfo(MI.getRawSource()));
6461     updateDAGForMaybeTailCall(MC);
6462     return;
6463   }
6464   case Intrinsic::memset_element_unordered_atomic: {
6465     auto &MI = cast<AtomicMemSetInst>(I);
6466     SDValue Dst = getValue(MI.getRawDest());
6467     SDValue Val = getValue(MI.getValue());
6468     SDValue Length = getValue(MI.getLength());
6469 
6470     Type *LengthTy = MI.getLength()->getType();
6471     unsigned ElemSz = MI.getElementSizeInBytes();
6472     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6473     SDValue MC =
6474         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6475                             isTC, MachinePointerInfo(MI.getRawDest()));
6476     updateDAGForMaybeTailCall(MC);
6477     return;
6478   }
6479   case Intrinsic::call_preallocated_setup: {
6480     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6481     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6482     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6483                               getRoot(), SrcValue);
6484     setValue(&I, Res);
6485     DAG.setRoot(Res);
6486     return;
6487   }
6488   case Intrinsic::call_preallocated_arg: {
6489     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6490     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6491     SDValue Ops[3];
6492     Ops[0] = getRoot();
6493     Ops[1] = SrcValue;
6494     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6495                                    MVT::i32); // arg index
6496     SDValue Res = DAG.getNode(
6497         ISD::PREALLOCATED_ARG, sdl,
6498         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6499     setValue(&I, Res);
6500     DAG.setRoot(Res.getValue(1));
6501     return;
6502   }
6503   case Intrinsic::dbg_declare: {
6504     const auto &DI = cast<DbgDeclareInst>(I);
6505     // Debug intrinsics are handled separately in assignment tracking mode.
6506     // Some intrinsics are handled right after Argument lowering.
6507     if (AssignmentTrackingEnabled ||
6508         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6509       return;
6510     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6511     DILocalVariable *Variable = DI.getVariable();
6512     DIExpression *Expression = DI.getExpression();
6513     dropDanglingDebugInfo(Variable, Expression);
6514     // Assume dbg.declare can not currently use DIArgList, i.e.
6515     // it is non-variadic.
6516     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6517     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6518                        DI.getDebugLoc());
6519     return;
6520   }
6521   case Intrinsic::dbg_label: {
6522     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6523     DILabel *Label = DI.getLabel();
6524     assert(Label && "Missing label");
6525 
6526     SDDbgLabel *SDV;
6527     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6528     DAG.AddDbgLabel(SDV);
6529     return;
6530   }
6531   case Intrinsic::dbg_assign: {
6532     // Debug intrinsics are handled seperately in assignment tracking mode.
6533     if (AssignmentTrackingEnabled)
6534       return;
6535     // If assignment tracking hasn't been enabled then fall through and treat
6536     // the dbg.assign as a dbg.value.
6537     [[fallthrough]];
6538   }
6539   case Intrinsic::dbg_value: {
6540     // Debug intrinsics are handled seperately in assignment tracking mode.
6541     if (AssignmentTrackingEnabled)
6542       return;
6543     const DbgValueInst &DI = cast<DbgValueInst>(I);
6544     assert(DI.getVariable() && "Missing variable");
6545 
6546     DILocalVariable *Variable = DI.getVariable();
6547     DIExpression *Expression = DI.getExpression();
6548     dropDanglingDebugInfo(Variable, Expression);
6549 
6550     if (DI.isKillLocation()) {
6551       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6552       return;
6553     }
6554 
6555     SmallVector<Value *, 4> Values(DI.getValues());
6556     if (Values.empty())
6557       return;
6558 
6559     bool IsVariadic = DI.hasArgList();
6560     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6561                           SDNodeOrder, IsVariadic))
6562       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6563                            DI.getDebugLoc(), SDNodeOrder);
6564     return;
6565   }
6566 
6567   case Intrinsic::eh_typeid_for: {
6568     // Find the type id for the given typeinfo.
6569     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6570     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6571     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6572     setValue(&I, Res);
6573     return;
6574   }
6575 
6576   case Intrinsic::eh_return_i32:
6577   case Intrinsic::eh_return_i64:
6578     DAG.getMachineFunction().setCallsEHReturn(true);
6579     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6580                             MVT::Other,
6581                             getControlRoot(),
6582                             getValue(I.getArgOperand(0)),
6583                             getValue(I.getArgOperand(1))));
6584     return;
6585   case Intrinsic::eh_unwind_init:
6586     DAG.getMachineFunction().setCallsUnwindInit(true);
6587     return;
6588   case Intrinsic::eh_dwarf_cfa:
6589     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6590                              TLI.getPointerTy(DAG.getDataLayout()),
6591                              getValue(I.getArgOperand(0))));
6592     return;
6593   case Intrinsic::eh_sjlj_callsite: {
6594     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6595     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6596     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6597 
6598     MMI.setCurrentCallSite(CI->getZExtValue());
6599     return;
6600   }
6601   case Intrinsic::eh_sjlj_functioncontext: {
6602     // Get and store the index of the function context.
6603     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6604     AllocaInst *FnCtx =
6605       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6606     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6607     MFI.setFunctionContextIndex(FI);
6608     return;
6609   }
6610   case Intrinsic::eh_sjlj_setjmp: {
6611     SDValue Ops[2];
6612     Ops[0] = getRoot();
6613     Ops[1] = getValue(I.getArgOperand(0));
6614     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6615                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6616     setValue(&I, Op.getValue(0));
6617     DAG.setRoot(Op.getValue(1));
6618     return;
6619   }
6620   case Intrinsic::eh_sjlj_longjmp:
6621     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6622                             getRoot(), getValue(I.getArgOperand(0))));
6623     return;
6624   case Intrinsic::eh_sjlj_setup_dispatch:
6625     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6626                             getRoot()));
6627     return;
6628   case Intrinsic::masked_gather:
6629     visitMaskedGather(I);
6630     return;
6631   case Intrinsic::masked_load:
6632     visitMaskedLoad(I);
6633     return;
6634   case Intrinsic::masked_scatter:
6635     visitMaskedScatter(I);
6636     return;
6637   case Intrinsic::masked_store:
6638     visitMaskedStore(I);
6639     return;
6640   case Intrinsic::masked_expandload:
6641     visitMaskedLoad(I, true /* IsExpanding */);
6642     return;
6643   case Intrinsic::masked_compressstore:
6644     visitMaskedStore(I, true /* IsCompressing */);
6645     return;
6646   case Intrinsic::powi:
6647     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6648                             getValue(I.getArgOperand(1)), DAG));
6649     return;
6650   case Intrinsic::log:
6651     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6652     return;
6653   case Intrinsic::log2:
6654     setValue(&I,
6655              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6656     return;
6657   case Intrinsic::log10:
6658     setValue(&I,
6659              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6660     return;
6661   case Intrinsic::exp:
6662     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6663     return;
6664   case Intrinsic::exp2:
6665     setValue(&I,
6666              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6667     return;
6668   case Intrinsic::pow:
6669     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6670                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6671     return;
6672   case Intrinsic::sqrt:
6673   case Intrinsic::fabs:
6674   case Intrinsic::sin:
6675   case Intrinsic::cos:
6676   case Intrinsic::exp10:
6677   case Intrinsic::floor:
6678   case Intrinsic::ceil:
6679   case Intrinsic::trunc:
6680   case Intrinsic::rint:
6681   case Intrinsic::nearbyint:
6682   case Intrinsic::round:
6683   case Intrinsic::roundeven:
6684   case Intrinsic::canonicalize: {
6685     unsigned Opcode;
6686     switch (Intrinsic) {
6687     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6688     case Intrinsic::sqrt:      Opcode = ISD::FSQRT;      break;
6689     case Intrinsic::fabs:      Opcode = ISD::FABS;       break;
6690     case Intrinsic::sin:       Opcode = ISD::FSIN;       break;
6691     case Intrinsic::cos:       Opcode = ISD::FCOS;       break;
6692     case Intrinsic::exp10:     Opcode = ISD::FEXP10;     break;
6693     case Intrinsic::floor:     Opcode = ISD::FFLOOR;     break;
6694     case Intrinsic::ceil:      Opcode = ISD::FCEIL;      break;
6695     case Intrinsic::trunc:     Opcode = ISD::FTRUNC;     break;
6696     case Intrinsic::rint:      Opcode = ISD::FRINT;      break;
6697     case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
6698     case Intrinsic::round:     Opcode = ISD::FROUND;     break;
6699     case Intrinsic::roundeven: Opcode = ISD::FROUNDEVEN; break;
6700     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6701     }
6702 
6703     setValue(&I, DAG.getNode(Opcode, sdl,
6704                              getValue(I.getArgOperand(0)).getValueType(),
6705                              getValue(I.getArgOperand(0)), Flags));
6706     return;
6707   }
6708   case Intrinsic::lround:
6709   case Intrinsic::llround:
6710   case Intrinsic::lrint:
6711   case Intrinsic::llrint: {
6712     unsigned Opcode;
6713     switch (Intrinsic) {
6714     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6715     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6716     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6717     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6718     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6719     }
6720 
6721     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6722     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6723                              getValue(I.getArgOperand(0))));
6724     return;
6725   }
6726   case Intrinsic::minnum:
6727     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6728                              getValue(I.getArgOperand(0)).getValueType(),
6729                              getValue(I.getArgOperand(0)),
6730                              getValue(I.getArgOperand(1)), Flags));
6731     return;
6732   case Intrinsic::maxnum:
6733     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6734                              getValue(I.getArgOperand(0)).getValueType(),
6735                              getValue(I.getArgOperand(0)),
6736                              getValue(I.getArgOperand(1)), Flags));
6737     return;
6738   case Intrinsic::minimum:
6739     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6740                              getValue(I.getArgOperand(0)).getValueType(),
6741                              getValue(I.getArgOperand(0)),
6742                              getValue(I.getArgOperand(1)), Flags));
6743     return;
6744   case Intrinsic::maximum:
6745     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6746                              getValue(I.getArgOperand(0)).getValueType(),
6747                              getValue(I.getArgOperand(0)),
6748                              getValue(I.getArgOperand(1)), Flags));
6749     return;
6750   case Intrinsic::copysign:
6751     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6752                              getValue(I.getArgOperand(0)).getValueType(),
6753                              getValue(I.getArgOperand(0)),
6754                              getValue(I.getArgOperand(1)), Flags));
6755     return;
6756   case Intrinsic::ldexp:
6757     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6758                              getValue(I.getArgOperand(0)).getValueType(),
6759                              getValue(I.getArgOperand(0)),
6760                              getValue(I.getArgOperand(1)), Flags));
6761     return;
6762   case Intrinsic::frexp: {
6763     SmallVector<EVT, 2> ValueVTs;
6764     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6765     SDVTList VTs = DAG.getVTList(ValueVTs);
6766     setValue(&I,
6767              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6768     return;
6769   }
6770   case Intrinsic::arithmetic_fence: {
6771     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6772                              getValue(I.getArgOperand(0)).getValueType(),
6773                              getValue(I.getArgOperand(0)), Flags));
6774     return;
6775   }
6776   case Intrinsic::fma:
6777     setValue(&I, DAG.getNode(
6778                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6779                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6780                      getValue(I.getArgOperand(2)), Flags));
6781     return;
6782 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6783   case Intrinsic::INTRINSIC:
6784 #include "llvm/IR/ConstrainedOps.def"
6785     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6786     return;
6787 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6788 #include "llvm/IR/VPIntrinsics.def"
6789     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6790     return;
6791   case Intrinsic::fptrunc_round: {
6792     // Get the last argument, the metadata and convert it to an integer in the
6793     // call
6794     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6795     std::optional<RoundingMode> RoundMode =
6796         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6797 
6798     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6799 
6800     // Propagate fast-math-flags from IR to node(s).
6801     SDNodeFlags Flags;
6802     Flags.copyFMF(*cast<FPMathOperator>(&I));
6803     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6804 
6805     SDValue Result;
6806     Result = DAG.getNode(
6807         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6808         DAG.getTargetConstant((int)*RoundMode, sdl,
6809                               TLI.getPointerTy(DAG.getDataLayout())));
6810     setValue(&I, Result);
6811 
6812     return;
6813   }
6814   case Intrinsic::fmuladd: {
6815     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6816     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6817         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6818       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6819                                getValue(I.getArgOperand(0)).getValueType(),
6820                                getValue(I.getArgOperand(0)),
6821                                getValue(I.getArgOperand(1)),
6822                                getValue(I.getArgOperand(2)), Flags));
6823     } else {
6824       // TODO: Intrinsic calls should have fast-math-flags.
6825       SDValue Mul = DAG.getNode(
6826           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6827           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6828       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6829                                 getValue(I.getArgOperand(0)).getValueType(),
6830                                 Mul, getValue(I.getArgOperand(2)), Flags);
6831       setValue(&I, Add);
6832     }
6833     return;
6834   }
6835   case Intrinsic::convert_to_fp16:
6836     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6837                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6838                                          getValue(I.getArgOperand(0)),
6839                                          DAG.getTargetConstant(0, sdl,
6840                                                                MVT::i32))));
6841     return;
6842   case Intrinsic::convert_from_fp16:
6843     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6844                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6845                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6846                                          getValue(I.getArgOperand(0)))));
6847     return;
6848   case Intrinsic::fptosi_sat: {
6849     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6850     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6851                              getValue(I.getArgOperand(0)),
6852                              DAG.getValueType(VT.getScalarType())));
6853     return;
6854   }
6855   case Intrinsic::fptoui_sat: {
6856     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6857     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6858                              getValue(I.getArgOperand(0)),
6859                              DAG.getValueType(VT.getScalarType())));
6860     return;
6861   }
6862   case Intrinsic::set_rounding:
6863     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6864                       {getRoot(), getValue(I.getArgOperand(0))});
6865     setValue(&I, Res);
6866     DAG.setRoot(Res.getValue(0));
6867     return;
6868   case Intrinsic::is_fpclass: {
6869     const DataLayout DLayout = DAG.getDataLayout();
6870     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6871     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6872     FPClassTest Test = static_cast<FPClassTest>(
6873         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6874     MachineFunction &MF = DAG.getMachineFunction();
6875     const Function &F = MF.getFunction();
6876     SDValue Op = getValue(I.getArgOperand(0));
6877     SDNodeFlags Flags;
6878     Flags.setNoFPExcept(
6879         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6880     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6881     // expansion can use illegal types. Making expansion early allows
6882     // legalizing these types prior to selection.
6883     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6884       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6885       setValue(&I, Result);
6886       return;
6887     }
6888 
6889     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6890     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6891     setValue(&I, V);
6892     return;
6893   }
6894   case Intrinsic::get_fpenv: {
6895     const DataLayout DLayout = DAG.getDataLayout();
6896     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
6897     Align TempAlign = DAG.getEVTAlign(EnvVT);
6898     SDValue Chain = getRoot();
6899     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
6900     // and temporary storage in stack.
6901     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
6902       Res = DAG.getNode(
6903           ISD::GET_FPENV, sdl,
6904           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6905                         MVT::Other),
6906           Chain);
6907     } else {
6908       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6909       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6910       auto MPI =
6911           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6912       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6913           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
6914           TempAlign);
6915       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6916       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
6917     }
6918     setValue(&I, Res);
6919     DAG.setRoot(Res.getValue(1));
6920     return;
6921   }
6922   case Intrinsic::set_fpenv: {
6923     const DataLayout DLayout = DAG.getDataLayout();
6924     SDValue Env = getValue(I.getArgOperand(0));
6925     EVT EnvVT = Env.getValueType();
6926     Align TempAlign = DAG.getEVTAlign(EnvVT);
6927     SDValue Chain = getRoot();
6928     // If SET_FPENV is custom or legal, use it. Otherwise use loading
6929     // environment from memory.
6930     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
6931       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
6932     } else {
6933       // Allocate space in stack, copy environment bits into it and use this
6934       // memory in SET_FPENV_MEM.
6935       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
6936       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
6937       auto MPI =
6938           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
6939       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
6940                            MachineMemOperand::MOStore);
6941       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6942           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
6943           TempAlign);
6944       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
6945     }
6946     DAG.setRoot(Chain);
6947     return;
6948   }
6949   case Intrinsic::reset_fpenv:
6950     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
6951     return;
6952   case Intrinsic::get_fpmode:
6953     Res = DAG.getNode(
6954         ISD::GET_FPMODE, sdl,
6955         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
6956                       MVT::Other),
6957         DAG.getRoot());
6958     setValue(&I, Res);
6959     DAG.setRoot(Res.getValue(1));
6960     return;
6961   case Intrinsic::set_fpmode:
6962     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
6963                       getValue(I.getArgOperand(0)));
6964     DAG.setRoot(Res);
6965     return;
6966   case Intrinsic::reset_fpmode: {
6967     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
6968     DAG.setRoot(Res);
6969     return;
6970   }
6971   case Intrinsic::pcmarker: {
6972     SDValue Tmp = getValue(I.getArgOperand(0));
6973     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
6974     return;
6975   }
6976   case Intrinsic::readcyclecounter: {
6977     SDValue Op = getRoot();
6978     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
6979                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6980     setValue(&I, Res);
6981     DAG.setRoot(Res.getValue(1));
6982     return;
6983   }
6984   case Intrinsic::readsteadycounter: {
6985     SDValue Op = getRoot();
6986     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
6987                       DAG.getVTList(MVT::i64, MVT::Other), Op);
6988     setValue(&I, Res);
6989     DAG.setRoot(Res.getValue(1));
6990     return;
6991   }
6992   case Intrinsic::bitreverse:
6993     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
6994                              getValue(I.getArgOperand(0)).getValueType(),
6995                              getValue(I.getArgOperand(0))));
6996     return;
6997   case Intrinsic::bswap:
6998     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
6999                              getValue(I.getArgOperand(0)).getValueType(),
7000                              getValue(I.getArgOperand(0))));
7001     return;
7002   case Intrinsic::cttz: {
7003     SDValue Arg = getValue(I.getArgOperand(0));
7004     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7005     EVT Ty = Arg.getValueType();
7006     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7007                              sdl, Ty, Arg));
7008     return;
7009   }
7010   case Intrinsic::ctlz: {
7011     SDValue Arg = getValue(I.getArgOperand(0));
7012     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7013     EVT Ty = Arg.getValueType();
7014     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7015                              sdl, Ty, Arg));
7016     return;
7017   }
7018   case Intrinsic::ctpop: {
7019     SDValue Arg = getValue(I.getArgOperand(0));
7020     EVT Ty = Arg.getValueType();
7021     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7022     return;
7023   }
7024   case Intrinsic::fshl:
7025   case Intrinsic::fshr: {
7026     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7027     SDValue X = getValue(I.getArgOperand(0));
7028     SDValue Y = getValue(I.getArgOperand(1));
7029     SDValue Z = getValue(I.getArgOperand(2));
7030     EVT VT = X.getValueType();
7031 
7032     if (X == Y) {
7033       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7034       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7035     } else {
7036       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7037       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7038     }
7039     return;
7040   }
7041   case Intrinsic::sadd_sat: {
7042     SDValue Op1 = getValue(I.getArgOperand(0));
7043     SDValue Op2 = getValue(I.getArgOperand(1));
7044     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7045     return;
7046   }
7047   case Intrinsic::uadd_sat: {
7048     SDValue Op1 = getValue(I.getArgOperand(0));
7049     SDValue Op2 = getValue(I.getArgOperand(1));
7050     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7051     return;
7052   }
7053   case Intrinsic::ssub_sat: {
7054     SDValue Op1 = getValue(I.getArgOperand(0));
7055     SDValue Op2 = getValue(I.getArgOperand(1));
7056     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7057     return;
7058   }
7059   case Intrinsic::usub_sat: {
7060     SDValue Op1 = getValue(I.getArgOperand(0));
7061     SDValue Op2 = getValue(I.getArgOperand(1));
7062     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7063     return;
7064   }
7065   case Intrinsic::sshl_sat: {
7066     SDValue Op1 = getValue(I.getArgOperand(0));
7067     SDValue Op2 = getValue(I.getArgOperand(1));
7068     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7069     return;
7070   }
7071   case Intrinsic::ushl_sat: {
7072     SDValue Op1 = getValue(I.getArgOperand(0));
7073     SDValue Op2 = getValue(I.getArgOperand(1));
7074     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7075     return;
7076   }
7077   case Intrinsic::smul_fix:
7078   case Intrinsic::umul_fix:
7079   case Intrinsic::smul_fix_sat:
7080   case Intrinsic::umul_fix_sat: {
7081     SDValue Op1 = getValue(I.getArgOperand(0));
7082     SDValue Op2 = getValue(I.getArgOperand(1));
7083     SDValue Op3 = getValue(I.getArgOperand(2));
7084     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7085                              Op1.getValueType(), Op1, Op2, Op3));
7086     return;
7087   }
7088   case Intrinsic::sdiv_fix:
7089   case Intrinsic::udiv_fix:
7090   case Intrinsic::sdiv_fix_sat:
7091   case Intrinsic::udiv_fix_sat: {
7092     SDValue Op1 = getValue(I.getArgOperand(0));
7093     SDValue Op2 = getValue(I.getArgOperand(1));
7094     SDValue Op3 = getValue(I.getArgOperand(2));
7095     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7096                               Op1, Op2, Op3, DAG, TLI));
7097     return;
7098   }
7099   case Intrinsic::smax: {
7100     SDValue Op1 = getValue(I.getArgOperand(0));
7101     SDValue Op2 = getValue(I.getArgOperand(1));
7102     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7103     return;
7104   }
7105   case Intrinsic::smin: {
7106     SDValue Op1 = getValue(I.getArgOperand(0));
7107     SDValue Op2 = getValue(I.getArgOperand(1));
7108     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7109     return;
7110   }
7111   case Intrinsic::umax: {
7112     SDValue Op1 = getValue(I.getArgOperand(0));
7113     SDValue Op2 = getValue(I.getArgOperand(1));
7114     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7115     return;
7116   }
7117   case Intrinsic::umin: {
7118     SDValue Op1 = getValue(I.getArgOperand(0));
7119     SDValue Op2 = getValue(I.getArgOperand(1));
7120     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7121     return;
7122   }
7123   case Intrinsic::abs: {
7124     // TODO: Preserve "int min is poison" arg in SDAG?
7125     SDValue Op1 = getValue(I.getArgOperand(0));
7126     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7127     return;
7128   }
7129   case Intrinsic::stacksave: {
7130     SDValue Op = getRoot();
7131     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7132     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7133     setValue(&I, Res);
7134     DAG.setRoot(Res.getValue(1));
7135     return;
7136   }
7137   case Intrinsic::stackrestore:
7138     Res = getValue(I.getArgOperand(0));
7139     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7140     return;
7141   case Intrinsic::get_dynamic_area_offset: {
7142     SDValue Op = getRoot();
7143     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7144     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7145     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7146     // target.
7147     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7148       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7149                          " intrinsic!");
7150     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7151                       Op);
7152     DAG.setRoot(Op);
7153     setValue(&I, Res);
7154     return;
7155   }
7156   case Intrinsic::stackguard: {
7157     MachineFunction &MF = DAG.getMachineFunction();
7158     const Module &M = *MF.getFunction().getParent();
7159     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7160     SDValue Chain = getRoot();
7161     if (TLI.useLoadStackGuardNode()) {
7162       Res = getLoadStackGuard(DAG, sdl, Chain);
7163       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7164     } else {
7165       const Value *Global = TLI.getSDagStackGuard(M);
7166       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7167       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7168                         MachinePointerInfo(Global, 0), Align,
7169                         MachineMemOperand::MOVolatile);
7170     }
7171     if (TLI.useStackGuardXorFP())
7172       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7173     DAG.setRoot(Chain);
7174     setValue(&I, Res);
7175     return;
7176   }
7177   case Intrinsic::stackprotector: {
7178     // Emit code into the DAG to store the stack guard onto the stack.
7179     MachineFunction &MF = DAG.getMachineFunction();
7180     MachineFrameInfo &MFI = MF.getFrameInfo();
7181     SDValue Src, Chain = getRoot();
7182 
7183     if (TLI.useLoadStackGuardNode())
7184       Src = getLoadStackGuard(DAG, sdl, Chain);
7185     else
7186       Src = getValue(I.getArgOperand(0));   // The guard's value.
7187 
7188     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7189 
7190     int FI = FuncInfo.StaticAllocaMap[Slot];
7191     MFI.setStackProtectorIndex(FI);
7192     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7193 
7194     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7195 
7196     // Store the stack protector onto the stack.
7197     Res = DAG.getStore(
7198         Chain, sdl, Src, FIN,
7199         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7200         MaybeAlign(), MachineMemOperand::MOVolatile);
7201     setValue(&I, Res);
7202     DAG.setRoot(Res);
7203     return;
7204   }
7205   case Intrinsic::objectsize:
7206     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7207 
7208   case Intrinsic::is_constant:
7209     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7210 
7211   case Intrinsic::annotation:
7212   case Intrinsic::ptr_annotation:
7213   case Intrinsic::launder_invariant_group:
7214   case Intrinsic::strip_invariant_group:
7215     // Drop the intrinsic, but forward the value
7216     setValue(&I, getValue(I.getOperand(0)));
7217     return;
7218 
7219   case Intrinsic::assume:
7220   case Intrinsic::experimental_noalias_scope_decl:
7221   case Intrinsic::var_annotation:
7222   case Intrinsic::sideeffect:
7223     // Discard annotate attributes, noalias scope declarations, assumptions, and
7224     // artificial side-effects.
7225     return;
7226 
7227   case Intrinsic::codeview_annotation: {
7228     // Emit a label associated with this metadata.
7229     MachineFunction &MF = DAG.getMachineFunction();
7230     MCSymbol *Label =
7231         MF.getMMI().getContext().createTempSymbol("annotation", true);
7232     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7233     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7234     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7235     DAG.setRoot(Res);
7236     return;
7237   }
7238 
7239   case Intrinsic::init_trampoline: {
7240     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7241 
7242     SDValue Ops[6];
7243     Ops[0] = getRoot();
7244     Ops[1] = getValue(I.getArgOperand(0));
7245     Ops[2] = getValue(I.getArgOperand(1));
7246     Ops[3] = getValue(I.getArgOperand(2));
7247     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7248     Ops[5] = DAG.getSrcValue(F);
7249 
7250     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7251 
7252     DAG.setRoot(Res);
7253     return;
7254   }
7255   case Intrinsic::adjust_trampoline:
7256     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7257                              TLI.getPointerTy(DAG.getDataLayout()),
7258                              getValue(I.getArgOperand(0))));
7259     return;
7260   case Intrinsic::gcroot: {
7261     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7262            "only valid in functions with gc specified, enforced by Verifier");
7263     assert(GFI && "implied by previous");
7264     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7265     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7266 
7267     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7268     GFI->addStackRoot(FI->getIndex(), TypeMap);
7269     return;
7270   }
7271   case Intrinsic::gcread:
7272   case Intrinsic::gcwrite:
7273     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7274   case Intrinsic::get_rounding:
7275     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7276     setValue(&I, Res);
7277     DAG.setRoot(Res.getValue(1));
7278     return;
7279 
7280   case Intrinsic::expect:
7281     // Just replace __builtin_expect(exp, c) with EXP.
7282     setValue(&I, getValue(I.getArgOperand(0)));
7283     return;
7284 
7285   case Intrinsic::ubsantrap:
7286   case Intrinsic::debugtrap:
7287   case Intrinsic::trap: {
7288     StringRef TrapFuncName =
7289         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7290     if (TrapFuncName.empty()) {
7291       switch (Intrinsic) {
7292       case Intrinsic::trap:
7293         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7294         break;
7295       case Intrinsic::debugtrap:
7296         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7297         break;
7298       case Intrinsic::ubsantrap:
7299         DAG.setRoot(DAG.getNode(
7300             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7301             DAG.getTargetConstant(
7302                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7303                 MVT::i32)));
7304         break;
7305       default: llvm_unreachable("unknown trap intrinsic");
7306       }
7307       return;
7308     }
7309     TargetLowering::ArgListTy Args;
7310     if (Intrinsic == Intrinsic::ubsantrap) {
7311       Args.push_back(TargetLoweringBase::ArgListEntry());
7312       Args[0].Val = I.getArgOperand(0);
7313       Args[0].Node = getValue(Args[0].Val);
7314       Args[0].Ty = Args[0].Val->getType();
7315     }
7316 
7317     TargetLowering::CallLoweringInfo CLI(DAG);
7318     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7319         CallingConv::C, I.getType(),
7320         DAG.getExternalSymbol(TrapFuncName.data(),
7321                               TLI.getPointerTy(DAG.getDataLayout())),
7322         std::move(Args));
7323 
7324     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7325     DAG.setRoot(Result.second);
7326     return;
7327   }
7328 
7329   case Intrinsic::allow_runtime_check:
7330   case Intrinsic::allow_ubsan_check:
7331     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7332     return;
7333 
7334   case Intrinsic::uadd_with_overflow:
7335   case Intrinsic::sadd_with_overflow:
7336   case Intrinsic::usub_with_overflow:
7337   case Intrinsic::ssub_with_overflow:
7338   case Intrinsic::umul_with_overflow:
7339   case Intrinsic::smul_with_overflow: {
7340     ISD::NodeType Op;
7341     switch (Intrinsic) {
7342     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7343     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7344     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7345     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7346     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7347     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7348     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7349     }
7350     SDValue Op1 = getValue(I.getArgOperand(0));
7351     SDValue Op2 = getValue(I.getArgOperand(1));
7352 
7353     EVT ResultVT = Op1.getValueType();
7354     EVT OverflowVT = MVT::i1;
7355     if (ResultVT.isVector())
7356       OverflowVT = EVT::getVectorVT(
7357           *Context, OverflowVT, ResultVT.getVectorElementCount());
7358 
7359     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7360     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7361     return;
7362   }
7363   case Intrinsic::prefetch: {
7364     SDValue Ops[5];
7365     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7366     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7367     Ops[0] = DAG.getRoot();
7368     Ops[1] = getValue(I.getArgOperand(0));
7369     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7370                                    MVT::i32);
7371     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7372                                    MVT::i32);
7373     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7374                                    MVT::i32);
7375     SDValue Result = DAG.getMemIntrinsicNode(
7376         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7377         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7378         /* align */ std::nullopt, Flags);
7379 
7380     // Chain the prefetch in parallel with any pending loads, to stay out of
7381     // the way of later optimizations.
7382     PendingLoads.push_back(Result);
7383     Result = getRoot();
7384     DAG.setRoot(Result);
7385     return;
7386   }
7387   case Intrinsic::lifetime_start:
7388   case Intrinsic::lifetime_end: {
7389     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7390     // Stack coloring is not enabled in O0, discard region information.
7391     if (TM.getOptLevel() == CodeGenOptLevel::None)
7392       return;
7393 
7394     const int64_t ObjectSize =
7395         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7396     Value *const ObjectPtr = I.getArgOperand(1);
7397     SmallVector<const Value *, 4> Allocas;
7398     getUnderlyingObjects(ObjectPtr, Allocas);
7399 
7400     for (const Value *Alloca : Allocas) {
7401       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7402 
7403       // Could not find an Alloca.
7404       if (!LifetimeObject)
7405         continue;
7406 
7407       // First check that the Alloca is static, otherwise it won't have a
7408       // valid frame index.
7409       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7410       if (SI == FuncInfo.StaticAllocaMap.end())
7411         return;
7412 
7413       const int FrameIndex = SI->second;
7414       int64_t Offset;
7415       if (GetPointerBaseWithConstantOffset(
7416               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7417         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7418       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7419                                 Offset);
7420       DAG.setRoot(Res);
7421     }
7422     return;
7423   }
7424   case Intrinsic::pseudoprobe: {
7425     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7426     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7427     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7428     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7429     DAG.setRoot(Res);
7430     return;
7431   }
7432   case Intrinsic::invariant_start:
7433     // Discard region information.
7434     setValue(&I,
7435              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7436     return;
7437   case Intrinsic::invariant_end:
7438     // Discard region information.
7439     return;
7440   case Intrinsic::clear_cache:
7441     /// FunctionName may be null.
7442     if (const char *FunctionName = TLI.getClearCacheBuiltinName())
7443       lowerCallToExternalSymbol(I, FunctionName);
7444     return;
7445   case Intrinsic::donothing:
7446   case Intrinsic::seh_try_begin:
7447   case Intrinsic::seh_scope_begin:
7448   case Intrinsic::seh_try_end:
7449   case Intrinsic::seh_scope_end:
7450     // ignore
7451     return;
7452   case Intrinsic::experimental_stackmap:
7453     visitStackmap(I);
7454     return;
7455   case Intrinsic::experimental_patchpoint_void:
7456   case Intrinsic::experimental_patchpoint:
7457     visitPatchpoint(I);
7458     return;
7459   case Intrinsic::experimental_gc_statepoint:
7460     LowerStatepoint(cast<GCStatepointInst>(I));
7461     return;
7462   case Intrinsic::experimental_gc_result:
7463     visitGCResult(cast<GCResultInst>(I));
7464     return;
7465   case Intrinsic::experimental_gc_relocate:
7466     visitGCRelocate(cast<GCRelocateInst>(I));
7467     return;
7468   case Intrinsic::instrprof_cover:
7469     llvm_unreachable("instrprof failed to lower a cover");
7470   case Intrinsic::instrprof_increment:
7471     llvm_unreachable("instrprof failed to lower an increment");
7472   case Intrinsic::instrprof_timestamp:
7473     llvm_unreachable("instrprof failed to lower a timestamp");
7474   case Intrinsic::instrprof_value_profile:
7475     llvm_unreachable("instrprof failed to lower a value profiling call");
7476   case Intrinsic::instrprof_mcdc_parameters:
7477     llvm_unreachable("instrprof failed to lower mcdc parameters");
7478   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7479     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7480   case Intrinsic::instrprof_mcdc_condbitmap_update:
7481     llvm_unreachable("instrprof failed to lower an mcdc condbitmap update");
7482   case Intrinsic::localescape: {
7483     MachineFunction &MF = DAG.getMachineFunction();
7484     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7485 
7486     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7487     // is the same on all targets.
7488     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7489       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7490       if (isa<ConstantPointerNull>(Arg))
7491         continue; // Skip null pointers. They represent a hole in index space.
7492       AllocaInst *Slot = cast<AllocaInst>(Arg);
7493       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7494              "can only escape static allocas");
7495       int FI = FuncInfo.StaticAllocaMap[Slot];
7496       MCSymbol *FrameAllocSym =
7497           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7498               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7499       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7500               TII->get(TargetOpcode::LOCAL_ESCAPE))
7501           .addSym(FrameAllocSym)
7502           .addFrameIndex(FI);
7503     }
7504 
7505     return;
7506   }
7507 
7508   case Intrinsic::localrecover: {
7509     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7510     MachineFunction &MF = DAG.getMachineFunction();
7511 
7512     // Get the symbol that defines the frame offset.
7513     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7514     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7515     unsigned IdxVal =
7516         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7517     MCSymbol *FrameAllocSym =
7518         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7519             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7520 
7521     Value *FP = I.getArgOperand(1);
7522     SDValue FPVal = getValue(FP);
7523     EVT PtrVT = FPVal.getValueType();
7524 
7525     // Create a MCSymbol for the label to avoid any target lowering
7526     // that would make this PC relative.
7527     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7528     SDValue OffsetVal =
7529         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7530 
7531     // Add the offset to the FP.
7532     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7533     setValue(&I, Add);
7534 
7535     return;
7536   }
7537 
7538   case Intrinsic::eh_exceptionpointer:
7539   case Intrinsic::eh_exceptioncode: {
7540     // Get the exception pointer vreg, copy from it, and resize it to fit.
7541     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7542     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7543     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7544     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7545     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7546     if (Intrinsic == Intrinsic::eh_exceptioncode)
7547       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7548     setValue(&I, N);
7549     return;
7550   }
7551   case Intrinsic::xray_customevent: {
7552     // Here we want to make sure that the intrinsic behaves as if it has a
7553     // specific calling convention.
7554     const auto &Triple = DAG.getTarget().getTargetTriple();
7555     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7556       return;
7557 
7558     SmallVector<SDValue, 8> Ops;
7559 
7560     // We want to say that we always want the arguments in registers.
7561     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7562     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7563     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7564     SDValue Chain = getRoot();
7565     Ops.push_back(LogEntryVal);
7566     Ops.push_back(StrSizeVal);
7567     Ops.push_back(Chain);
7568 
7569     // We need to enforce the calling convention for the callsite, so that
7570     // argument ordering is enforced correctly, and that register allocation can
7571     // see that some registers may be assumed clobbered and have to preserve
7572     // them across calls to the intrinsic.
7573     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7574                                            sdl, NodeTys, Ops);
7575     SDValue patchableNode = SDValue(MN, 0);
7576     DAG.setRoot(patchableNode);
7577     setValue(&I, patchableNode);
7578     return;
7579   }
7580   case Intrinsic::xray_typedevent: {
7581     // Here we want to make sure that the intrinsic behaves as if it has a
7582     // specific calling convention.
7583     const auto &Triple = DAG.getTarget().getTargetTriple();
7584     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7585       return;
7586 
7587     SmallVector<SDValue, 8> Ops;
7588 
7589     // We want to say that we always want the arguments in registers.
7590     // It's unclear to me how manipulating the selection DAG here forces callers
7591     // to provide arguments in registers instead of on the stack.
7592     SDValue LogTypeId = getValue(I.getArgOperand(0));
7593     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7594     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7595     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7596     SDValue Chain = getRoot();
7597     Ops.push_back(LogTypeId);
7598     Ops.push_back(LogEntryVal);
7599     Ops.push_back(StrSizeVal);
7600     Ops.push_back(Chain);
7601 
7602     // We need to enforce the calling convention for the callsite, so that
7603     // argument ordering is enforced correctly, and that register allocation can
7604     // see that some registers may be assumed clobbered and have to preserve
7605     // them across calls to the intrinsic.
7606     MachineSDNode *MN = DAG.getMachineNode(
7607         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7608     SDValue patchableNode = SDValue(MN, 0);
7609     DAG.setRoot(patchableNode);
7610     setValue(&I, patchableNode);
7611     return;
7612   }
7613   case Intrinsic::experimental_deoptimize:
7614     LowerDeoptimizeCall(&I);
7615     return;
7616   case Intrinsic::experimental_stepvector:
7617     visitStepVector(I);
7618     return;
7619   case Intrinsic::vector_reduce_fadd:
7620   case Intrinsic::vector_reduce_fmul:
7621   case Intrinsic::vector_reduce_add:
7622   case Intrinsic::vector_reduce_mul:
7623   case Intrinsic::vector_reduce_and:
7624   case Intrinsic::vector_reduce_or:
7625   case Intrinsic::vector_reduce_xor:
7626   case Intrinsic::vector_reduce_smax:
7627   case Intrinsic::vector_reduce_smin:
7628   case Intrinsic::vector_reduce_umax:
7629   case Intrinsic::vector_reduce_umin:
7630   case Intrinsic::vector_reduce_fmax:
7631   case Intrinsic::vector_reduce_fmin:
7632   case Intrinsic::vector_reduce_fmaximum:
7633   case Intrinsic::vector_reduce_fminimum:
7634     visitVectorReduce(I, Intrinsic);
7635     return;
7636 
7637   case Intrinsic::icall_branch_funnel: {
7638     SmallVector<SDValue, 16> Ops;
7639     Ops.push_back(getValue(I.getArgOperand(0)));
7640 
7641     int64_t Offset;
7642     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7643         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7644     if (!Base)
7645       report_fatal_error(
7646           "llvm.icall.branch.funnel operand must be a GlobalValue");
7647     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7648 
7649     struct BranchFunnelTarget {
7650       int64_t Offset;
7651       SDValue Target;
7652     };
7653     SmallVector<BranchFunnelTarget, 8> Targets;
7654 
7655     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7656       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7657           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7658       if (ElemBase != Base)
7659         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7660                            "to the same GlobalValue");
7661 
7662       SDValue Val = getValue(I.getArgOperand(Op + 1));
7663       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7664       if (!GA)
7665         report_fatal_error(
7666             "llvm.icall.branch.funnel operand must be a GlobalValue");
7667       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7668                                      GA->getGlobal(), sdl, Val.getValueType(),
7669                                      GA->getOffset())});
7670     }
7671     llvm::sort(Targets,
7672                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7673                  return T1.Offset < T2.Offset;
7674                });
7675 
7676     for (auto &T : Targets) {
7677       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7678       Ops.push_back(T.Target);
7679     }
7680 
7681     Ops.push_back(DAG.getRoot()); // Chain
7682     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7683                                  MVT::Other, Ops),
7684               0);
7685     DAG.setRoot(N);
7686     setValue(&I, N);
7687     HasTailCall = true;
7688     return;
7689   }
7690 
7691   case Intrinsic::wasm_landingpad_index:
7692     // Information this intrinsic contained has been transferred to
7693     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7694     // delete it now.
7695     return;
7696 
7697   case Intrinsic::aarch64_settag:
7698   case Intrinsic::aarch64_settag_zero: {
7699     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7700     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7701     SDValue Val = TSI.EmitTargetCodeForSetTag(
7702         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7703         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7704         ZeroMemory);
7705     DAG.setRoot(Val);
7706     setValue(&I, Val);
7707     return;
7708   }
7709   case Intrinsic::amdgcn_cs_chain: {
7710     assert(I.arg_size() == 5 && "Additional args not supported yet");
7711     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7712            "Non-zero flags not supported yet");
7713 
7714     // At this point we don't care if it's amdgpu_cs_chain or
7715     // amdgpu_cs_chain_preserve.
7716     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7717 
7718     Type *RetTy = I.getType();
7719     assert(RetTy->isVoidTy() && "Should not return");
7720 
7721     SDValue Callee = getValue(I.getOperand(0));
7722 
7723     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7724     // We'll also tack the value of the EXEC mask at the end.
7725     TargetLowering::ArgListTy Args;
7726     Args.reserve(3);
7727 
7728     for (unsigned Idx : {2, 3, 1}) {
7729       TargetLowering::ArgListEntry Arg;
7730       Arg.Node = getValue(I.getOperand(Idx));
7731       Arg.Ty = I.getOperand(Idx)->getType();
7732       Arg.setAttributes(&I, Idx);
7733       Args.push_back(Arg);
7734     }
7735 
7736     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7737     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7738     Args[2].IsInReg = true; // EXEC should be inreg
7739 
7740     TargetLowering::CallLoweringInfo CLI(DAG);
7741     CLI.setDebugLoc(getCurSDLoc())
7742         .setChain(getRoot())
7743         .setCallee(CC, RetTy, Callee, std::move(Args))
7744         .setNoReturn(true)
7745         .setTailCall(true)
7746         .setConvergent(I.isConvergent());
7747     CLI.CB = &I;
7748     std::pair<SDValue, SDValue> Result =
7749         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7750     (void)Result;
7751     assert(!Result.first.getNode() && !Result.second.getNode() &&
7752            "Should've lowered as tail call");
7753 
7754     HasTailCall = true;
7755     return;
7756   }
7757   case Intrinsic::ptrmask: {
7758     SDValue Ptr = getValue(I.getOperand(0));
7759     SDValue Mask = getValue(I.getOperand(1));
7760 
7761     EVT PtrVT = Ptr.getValueType();
7762     assert(PtrVT == Mask.getValueType() &&
7763            "Pointers with different index type are not supported by SDAG");
7764     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7765     return;
7766   }
7767   case Intrinsic::threadlocal_address: {
7768     setValue(&I, getValue(I.getOperand(0)));
7769     return;
7770   }
7771   case Intrinsic::get_active_lane_mask: {
7772     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7773     SDValue Index = getValue(I.getOperand(0));
7774     EVT ElementVT = Index.getValueType();
7775 
7776     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7777       visitTargetIntrinsic(I, Intrinsic);
7778       return;
7779     }
7780 
7781     SDValue TripCount = getValue(I.getOperand(1));
7782     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7783                                  CCVT.getVectorElementCount());
7784 
7785     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7786     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7787     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7788     SDValue VectorInduction = DAG.getNode(
7789         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7790     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7791                                  VectorTripCount, ISD::CondCode::SETULT);
7792     setValue(&I, SetCC);
7793     return;
7794   }
7795   case Intrinsic::experimental_get_vector_length: {
7796     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7797            "Expected positive VF");
7798     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7799     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7800 
7801     SDValue Count = getValue(I.getOperand(0));
7802     EVT CountVT = Count.getValueType();
7803 
7804     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7805       visitTargetIntrinsic(I, Intrinsic);
7806       return;
7807     }
7808 
7809     // Expand to a umin between the trip count and the maximum elements the type
7810     // can hold.
7811     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7812 
7813     // Extend the trip count to at least the result VT.
7814     if (CountVT.bitsLT(VT)) {
7815       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7816       CountVT = VT;
7817     }
7818 
7819     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7820                                          ElementCount::get(VF, IsScalable));
7821 
7822     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7823     // Clip to the result type if needed.
7824     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7825 
7826     setValue(&I, Trunc);
7827     return;
7828   }
7829   case Intrinsic::experimental_cttz_elts: {
7830     auto DL = getCurSDLoc();
7831     SDValue Op = getValue(I.getOperand(0));
7832     EVT OpVT = Op.getValueType();
7833 
7834     if (!TLI.shouldExpandCttzElements(OpVT)) {
7835       visitTargetIntrinsic(I, Intrinsic);
7836       return;
7837     }
7838 
7839     if (OpVT.getScalarType() != MVT::i1) {
7840       // Compare the input vector elements to zero & use to count trailing zeros
7841       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
7842       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
7843                               OpVT.getVectorElementCount());
7844       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
7845     }
7846 
7847     // Find the smallest "sensible" element type to use for the expansion.
7848     ConstantRange CR(
7849         APInt(64, OpVT.getVectorElementCount().getKnownMinValue()));
7850     if (OpVT.isScalableVT())
7851       CR = CR.umul_sat(getVScaleRange(I.getCaller(), 64));
7852 
7853     // If the zero-is-poison flag is set, we can assume the upper limit
7854     // of the result is VF-1.
7855     if (!cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero())
7856       CR = CR.subtract(APInt(64, 1));
7857 
7858     unsigned EltWidth = I.getType()->getScalarSizeInBits();
7859     EltWidth = std::min(EltWidth, (unsigned)CR.getActiveBits());
7860     EltWidth = std::max(llvm::bit_ceil(EltWidth), (unsigned)8);
7861 
7862     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
7863 
7864     // Create the new vector type & get the vector length
7865     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
7866                                  OpVT.getVectorElementCount());
7867 
7868     SDValue VL =
7869         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
7870 
7871     SDValue StepVec = DAG.getStepVector(DL, NewVT);
7872     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
7873     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
7874     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
7875     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
7876     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
7877     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
7878 
7879     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7880     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
7881 
7882     setValue(&I, Ret);
7883     return;
7884   }
7885   case Intrinsic::vector_insert: {
7886     SDValue Vec = getValue(I.getOperand(0));
7887     SDValue SubVec = getValue(I.getOperand(1));
7888     SDValue Index = getValue(I.getOperand(2));
7889 
7890     // The intrinsic's index type is i64, but the SDNode requires an index type
7891     // suitable for the target. Convert the index as required.
7892     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7893     if (Index.getValueType() != VectorIdxTy)
7894       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
7895 
7896     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7897     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
7898                              Index));
7899     return;
7900   }
7901   case Intrinsic::vector_extract: {
7902     SDValue Vec = getValue(I.getOperand(0));
7903     SDValue Index = getValue(I.getOperand(1));
7904     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7905 
7906     // The intrinsic's index type is i64, but the SDNode requires an index type
7907     // suitable for the target. Convert the index as required.
7908     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7909     if (Index.getValueType() != VectorIdxTy)
7910       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
7911 
7912     setValue(&I,
7913              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
7914     return;
7915   }
7916   case Intrinsic::experimental_vector_reverse:
7917     visitVectorReverse(I);
7918     return;
7919   case Intrinsic::experimental_vector_splice:
7920     visitVectorSplice(I);
7921     return;
7922   case Intrinsic::callbr_landingpad:
7923     visitCallBrLandingPad(I);
7924     return;
7925   case Intrinsic::experimental_vector_interleave2:
7926     visitVectorInterleave(I);
7927     return;
7928   case Intrinsic::experimental_vector_deinterleave2:
7929     visitVectorDeinterleave(I);
7930     return;
7931   case Intrinsic::experimental_convergence_anchor:
7932   case Intrinsic::experimental_convergence_entry:
7933   case Intrinsic::experimental_convergence_loop:
7934     visitConvergenceControl(I, Intrinsic);
7935   }
7936 }
7937 
7938 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
7939     const ConstrainedFPIntrinsic &FPI) {
7940   SDLoc sdl = getCurSDLoc();
7941 
7942   // We do not need to serialize constrained FP intrinsics against
7943   // each other or against (nonvolatile) loads, so they can be
7944   // chained like loads.
7945   SDValue Chain = DAG.getRoot();
7946   SmallVector<SDValue, 4> Opers;
7947   Opers.push_back(Chain);
7948   if (FPI.isUnaryOp()) {
7949     Opers.push_back(getValue(FPI.getArgOperand(0)));
7950   } else if (FPI.isTernaryOp()) {
7951     Opers.push_back(getValue(FPI.getArgOperand(0)));
7952     Opers.push_back(getValue(FPI.getArgOperand(1)));
7953     Opers.push_back(getValue(FPI.getArgOperand(2)));
7954   } else {
7955     Opers.push_back(getValue(FPI.getArgOperand(0)));
7956     Opers.push_back(getValue(FPI.getArgOperand(1)));
7957   }
7958 
7959   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
7960     assert(Result.getNode()->getNumValues() == 2);
7961 
7962     // Push node to the appropriate list so that future instructions can be
7963     // chained up correctly.
7964     SDValue OutChain = Result.getValue(1);
7965     switch (EB) {
7966     case fp::ExceptionBehavior::ebIgnore:
7967       // The only reason why ebIgnore nodes still need to be chained is that
7968       // they might depend on the current rounding mode, and therefore must
7969       // not be moved across instruction that may change that mode.
7970       [[fallthrough]];
7971     case fp::ExceptionBehavior::ebMayTrap:
7972       // These must not be moved across calls or instructions that may change
7973       // floating-point exception masks.
7974       PendingConstrainedFP.push_back(OutChain);
7975       break;
7976     case fp::ExceptionBehavior::ebStrict:
7977       // These must not be moved across calls or instructions that may change
7978       // floating-point exception masks or read floating-point exception flags.
7979       // In addition, they cannot be optimized out even if unused.
7980       PendingConstrainedFPStrict.push_back(OutChain);
7981       break;
7982     }
7983   };
7984 
7985   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7986   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
7987   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
7988   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
7989 
7990   SDNodeFlags Flags;
7991   if (EB == fp::ExceptionBehavior::ebIgnore)
7992     Flags.setNoFPExcept(true);
7993 
7994   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
7995     Flags.copyFMF(*FPOp);
7996 
7997   unsigned Opcode;
7998   switch (FPI.getIntrinsicID()) {
7999   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8000 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8001   case Intrinsic::INTRINSIC:                                                   \
8002     Opcode = ISD::STRICT_##DAGN;                                               \
8003     break;
8004 #include "llvm/IR/ConstrainedOps.def"
8005   case Intrinsic::experimental_constrained_fmuladd: {
8006     Opcode = ISD::STRICT_FMA;
8007     // Break fmuladd into fmul and fadd.
8008     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8009         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8010       Opers.pop_back();
8011       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8012       pushOutChain(Mul, EB);
8013       Opcode = ISD::STRICT_FADD;
8014       Opers.clear();
8015       Opers.push_back(Mul.getValue(1));
8016       Opers.push_back(Mul.getValue(0));
8017       Opers.push_back(getValue(FPI.getArgOperand(2)));
8018     }
8019     break;
8020   }
8021   }
8022 
8023   // A few strict DAG nodes carry additional operands that are not
8024   // set up by the default code above.
8025   switch (Opcode) {
8026   default: break;
8027   case ISD::STRICT_FP_ROUND:
8028     Opers.push_back(
8029         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8030     break;
8031   case ISD::STRICT_FSETCC:
8032   case ISD::STRICT_FSETCCS: {
8033     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8034     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8035     if (TM.Options.NoNaNsFPMath)
8036       Condition = getFCmpCodeWithoutNaN(Condition);
8037     Opers.push_back(DAG.getCondCode(Condition));
8038     break;
8039   }
8040   }
8041 
8042   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8043   pushOutChain(Result, EB);
8044 
8045   SDValue FPResult = Result.getValue(0);
8046   setValue(&FPI, FPResult);
8047 }
8048 
8049 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8050   std::optional<unsigned> ResOPC;
8051   switch (VPIntrin.getIntrinsicID()) {
8052   case Intrinsic::vp_ctlz: {
8053     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8054     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8055     break;
8056   }
8057   case Intrinsic::vp_cttz: {
8058     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8059     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8060     break;
8061   }
8062 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8063   case Intrinsic::VPID:                                                        \
8064     ResOPC = ISD::VPSD;                                                        \
8065     break;
8066 #include "llvm/IR/VPIntrinsics.def"
8067   }
8068 
8069   if (!ResOPC)
8070     llvm_unreachable(
8071         "Inconsistency: no SDNode available for this VPIntrinsic!");
8072 
8073   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8074       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8075     if (VPIntrin.getFastMathFlags().allowReassoc())
8076       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8077                                                 : ISD::VP_REDUCE_FMUL;
8078   }
8079 
8080   return *ResOPC;
8081 }
8082 
8083 void SelectionDAGBuilder::visitVPLoad(
8084     const VPIntrinsic &VPIntrin, EVT VT,
8085     const SmallVectorImpl<SDValue> &OpValues) {
8086   SDLoc DL = getCurSDLoc();
8087   Value *PtrOperand = VPIntrin.getArgOperand(0);
8088   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8089   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8090   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8091   SDValue LD;
8092   // Do not serialize variable-length loads of constant memory with
8093   // anything.
8094   if (!Alignment)
8095     Alignment = DAG.getEVTAlign(VT);
8096   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8097   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8098   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8099   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8100       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8101       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8102   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8103                      MMO, false /*IsExpanding */);
8104   if (AddToChain)
8105     PendingLoads.push_back(LD.getValue(1));
8106   setValue(&VPIntrin, LD);
8107 }
8108 
8109 void SelectionDAGBuilder::visitVPGather(
8110     const VPIntrinsic &VPIntrin, EVT VT,
8111     const SmallVectorImpl<SDValue> &OpValues) {
8112   SDLoc DL = getCurSDLoc();
8113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8114   Value *PtrOperand = VPIntrin.getArgOperand(0);
8115   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8116   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8117   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8118   SDValue LD;
8119   if (!Alignment)
8120     Alignment = DAG.getEVTAlign(VT.getScalarType());
8121   unsigned AS =
8122     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8123   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8124       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8125       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8126   SDValue Base, Index, Scale;
8127   ISD::MemIndexType IndexType;
8128   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8129                                     this, VPIntrin.getParent(),
8130                                     VT.getScalarStoreSize());
8131   if (!UniformBase) {
8132     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8133     Index = getValue(PtrOperand);
8134     IndexType = ISD::SIGNED_SCALED;
8135     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8136   }
8137   EVT IdxVT = Index.getValueType();
8138   EVT EltTy = IdxVT.getVectorElementType();
8139   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8140     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8141     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8142   }
8143   LD = DAG.getGatherVP(
8144       DAG.getVTList(VT, MVT::Other), VT, DL,
8145       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8146       IndexType);
8147   PendingLoads.push_back(LD.getValue(1));
8148   setValue(&VPIntrin, LD);
8149 }
8150 
8151 void SelectionDAGBuilder::visitVPStore(
8152     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8153   SDLoc DL = getCurSDLoc();
8154   Value *PtrOperand = VPIntrin.getArgOperand(1);
8155   EVT VT = OpValues[0].getValueType();
8156   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8157   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8158   SDValue ST;
8159   if (!Alignment)
8160     Alignment = DAG.getEVTAlign(VT);
8161   SDValue Ptr = OpValues[1];
8162   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8163   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8164       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8165       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8166   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8167                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8168                       /* IsTruncating */ false, /*IsCompressing*/ false);
8169   DAG.setRoot(ST);
8170   setValue(&VPIntrin, ST);
8171 }
8172 
8173 void SelectionDAGBuilder::visitVPScatter(
8174     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8175   SDLoc DL = getCurSDLoc();
8176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8177   Value *PtrOperand = VPIntrin.getArgOperand(1);
8178   EVT VT = OpValues[0].getValueType();
8179   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8180   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8181   SDValue ST;
8182   if (!Alignment)
8183     Alignment = DAG.getEVTAlign(VT.getScalarType());
8184   unsigned AS =
8185       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8186   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8187       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8188       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8189   SDValue Base, Index, Scale;
8190   ISD::MemIndexType IndexType;
8191   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8192                                     this, VPIntrin.getParent(),
8193                                     VT.getScalarStoreSize());
8194   if (!UniformBase) {
8195     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8196     Index = getValue(PtrOperand);
8197     IndexType = ISD::SIGNED_SCALED;
8198     Scale =
8199       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8200   }
8201   EVT IdxVT = Index.getValueType();
8202   EVT EltTy = IdxVT.getVectorElementType();
8203   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8204     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8205     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8206   }
8207   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8208                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8209                          OpValues[2], OpValues[3]},
8210                         MMO, IndexType);
8211   DAG.setRoot(ST);
8212   setValue(&VPIntrin, ST);
8213 }
8214 
8215 void SelectionDAGBuilder::visitVPStridedLoad(
8216     const VPIntrinsic &VPIntrin, EVT VT,
8217     const SmallVectorImpl<SDValue> &OpValues) {
8218   SDLoc DL = getCurSDLoc();
8219   Value *PtrOperand = VPIntrin.getArgOperand(0);
8220   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8221   if (!Alignment)
8222     Alignment = DAG.getEVTAlign(VT.getScalarType());
8223   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8224   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8225   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8226   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8227   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8228   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8229   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8230       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8231       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8232 
8233   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8234                                     OpValues[2], OpValues[3], MMO,
8235                                     false /*IsExpanding*/);
8236 
8237   if (AddToChain)
8238     PendingLoads.push_back(LD.getValue(1));
8239   setValue(&VPIntrin, LD);
8240 }
8241 
8242 void SelectionDAGBuilder::visitVPStridedStore(
8243     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8244   SDLoc DL = getCurSDLoc();
8245   Value *PtrOperand = VPIntrin.getArgOperand(1);
8246   EVT VT = OpValues[0].getValueType();
8247   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8248   if (!Alignment)
8249     Alignment = DAG.getEVTAlign(VT.getScalarType());
8250   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8251   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8252   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8253       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8254       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8255 
8256   SDValue ST = DAG.getStridedStoreVP(
8257       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8258       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8259       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8260       /*IsCompressing*/ false);
8261 
8262   DAG.setRoot(ST);
8263   setValue(&VPIntrin, ST);
8264 }
8265 
8266 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8267   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8268   SDLoc DL = getCurSDLoc();
8269 
8270   ISD::CondCode Condition;
8271   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8272   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8273   if (IsFP) {
8274     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8275     // flags, but calls that don't return floating-point types can't be
8276     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8277     Condition = getFCmpCondCode(CondCode);
8278     if (TM.Options.NoNaNsFPMath)
8279       Condition = getFCmpCodeWithoutNaN(Condition);
8280   } else {
8281     Condition = getICmpCondCode(CondCode);
8282   }
8283 
8284   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8285   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8286   // #2 is the condition code
8287   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8288   SDValue EVL = getValue(VPIntrin.getOperand(4));
8289   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8290   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8291          "Unexpected target EVL type");
8292   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8293 
8294   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8295                                                         VPIntrin.getType());
8296   setValue(&VPIntrin,
8297            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8298 }
8299 
8300 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8301     const VPIntrinsic &VPIntrin) {
8302   SDLoc DL = getCurSDLoc();
8303   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8304 
8305   auto IID = VPIntrin.getIntrinsicID();
8306 
8307   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8308     return visitVPCmp(*CmpI);
8309 
8310   SmallVector<EVT, 4> ValueVTs;
8311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8312   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8313   SDVTList VTs = DAG.getVTList(ValueVTs);
8314 
8315   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8316 
8317   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8318   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8319          "Unexpected target EVL type");
8320 
8321   // Request operands.
8322   SmallVector<SDValue, 7> OpValues;
8323   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8324     auto Op = getValue(VPIntrin.getArgOperand(I));
8325     if (I == EVLParamPos)
8326       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8327     OpValues.push_back(Op);
8328   }
8329 
8330   switch (Opcode) {
8331   default: {
8332     SDNodeFlags SDFlags;
8333     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8334       SDFlags.copyFMF(*FPMO);
8335     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8336     setValue(&VPIntrin, Result);
8337     break;
8338   }
8339   case ISD::VP_LOAD:
8340     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8341     break;
8342   case ISD::VP_GATHER:
8343     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8344     break;
8345   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8346     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8347     break;
8348   case ISD::VP_STORE:
8349     visitVPStore(VPIntrin, OpValues);
8350     break;
8351   case ISD::VP_SCATTER:
8352     visitVPScatter(VPIntrin, OpValues);
8353     break;
8354   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8355     visitVPStridedStore(VPIntrin, OpValues);
8356     break;
8357   case ISD::VP_FMULADD: {
8358     assert(OpValues.size() == 5 && "Unexpected number of operands");
8359     SDNodeFlags SDFlags;
8360     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8361       SDFlags.copyFMF(*FPMO);
8362     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8363         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8364       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8365     } else {
8366       SDValue Mul = DAG.getNode(
8367           ISD::VP_FMUL, DL, VTs,
8368           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8369       SDValue Add =
8370           DAG.getNode(ISD::VP_FADD, DL, VTs,
8371                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8372       setValue(&VPIntrin, Add);
8373     }
8374     break;
8375   }
8376   case ISD::VP_IS_FPCLASS: {
8377     const DataLayout DLayout = DAG.getDataLayout();
8378     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8379     auto Constant = OpValues[1]->getAsZExtVal();
8380     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8381     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8382                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8383     setValue(&VPIntrin, V);
8384     return;
8385   }
8386   case ISD::VP_INTTOPTR: {
8387     SDValue N = OpValues[0];
8388     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8389     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8390     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8391                                OpValues[2]);
8392     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8393                              OpValues[2]);
8394     setValue(&VPIntrin, N);
8395     break;
8396   }
8397   case ISD::VP_PTRTOINT: {
8398     SDValue N = OpValues[0];
8399     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8400                                                           VPIntrin.getType());
8401     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8402                                        VPIntrin.getOperand(0)->getType());
8403     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8404                                OpValues[2]);
8405     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8406                              OpValues[2]);
8407     setValue(&VPIntrin, N);
8408     break;
8409   }
8410   case ISD::VP_ABS:
8411   case ISD::VP_CTLZ:
8412   case ISD::VP_CTLZ_ZERO_UNDEF:
8413   case ISD::VP_CTTZ:
8414   case ISD::VP_CTTZ_ZERO_UNDEF: {
8415     SDValue Result =
8416         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8417     setValue(&VPIntrin, Result);
8418     break;
8419   }
8420   }
8421 }
8422 
8423 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8424                                           const BasicBlock *EHPadBB,
8425                                           MCSymbol *&BeginLabel) {
8426   MachineFunction &MF = DAG.getMachineFunction();
8427   MachineModuleInfo &MMI = MF.getMMI();
8428 
8429   // Insert a label before the invoke call to mark the try range.  This can be
8430   // used to detect deletion of the invoke via the MachineModuleInfo.
8431   BeginLabel = MMI.getContext().createTempSymbol();
8432 
8433   // For SjLj, keep track of which landing pads go with which invokes
8434   // so as to maintain the ordering of pads in the LSDA.
8435   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8436   if (CallSiteIndex) {
8437     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8438     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8439 
8440     // Now that the call site is handled, stop tracking it.
8441     MMI.setCurrentCallSite(0);
8442   }
8443 
8444   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8445 }
8446 
8447 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8448                                         const BasicBlock *EHPadBB,
8449                                         MCSymbol *BeginLabel) {
8450   assert(BeginLabel && "BeginLabel should've been set");
8451 
8452   MachineFunction &MF = DAG.getMachineFunction();
8453   MachineModuleInfo &MMI = MF.getMMI();
8454 
8455   // Insert a label at the end of the invoke call to mark the try range.  This
8456   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8457   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8458   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8459 
8460   // Inform MachineModuleInfo of range.
8461   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8462   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8463   // actually use outlined funclets and their LSDA info style.
8464   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8465     assert(II && "II should've been set");
8466     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8467     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8468   } else if (!isScopedEHPersonality(Pers)) {
8469     assert(EHPadBB);
8470     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8471   }
8472 
8473   return Chain;
8474 }
8475 
8476 std::pair<SDValue, SDValue>
8477 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8478                                     const BasicBlock *EHPadBB) {
8479   MCSymbol *BeginLabel = nullptr;
8480 
8481   if (EHPadBB) {
8482     // Both PendingLoads and PendingExports must be flushed here;
8483     // this call might not return.
8484     (void)getRoot();
8485     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8486     CLI.setChain(getRoot());
8487   }
8488 
8489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8490   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8491 
8492   assert((CLI.IsTailCall || Result.second.getNode()) &&
8493          "Non-null chain expected with non-tail call!");
8494   assert((Result.second.getNode() || !Result.first.getNode()) &&
8495          "Null value expected with tail call!");
8496 
8497   if (!Result.second.getNode()) {
8498     // As a special case, a null chain means that a tail call has been emitted
8499     // and the DAG root is already updated.
8500     HasTailCall = true;
8501 
8502     // Since there's no actual continuation from this block, nothing can be
8503     // relying on us setting vregs for them.
8504     PendingExports.clear();
8505   } else {
8506     DAG.setRoot(Result.second);
8507   }
8508 
8509   if (EHPadBB) {
8510     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8511                            BeginLabel));
8512   }
8513 
8514   return Result;
8515 }
8516 
8517 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8518                                       bool isTailCall,
8519                                       bool isMustTailCall,
8520                                       const BasicBlock *EHPadBB) {
8521   auto &DL = DAG.getDataLayout();
8522   FunctionType *FTy = CB.getFunctionType();
8523   Type *RetTy = CB.getType();
8524 
8525   TargetLowering::ArgListTy Args;
8526   Args.reserve(CB.arg_size());
8527 
8528   const Value *SwiftErrorVal = nullptr;
8529   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8530 
8531   if (isTailCall) {
8532     // Avoid emitting tail calls in functions with the disable-tail-calls
8533     // attribute.
8534     auto *Caller = CB.getParent()->getParent();
8535     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8536         "true" && !isMustTailCall)
8537       isTailCall = false;
8538 
8539     // We can't tail call inside a function with a swifterror argument. Lowering
8540     // does not support this yet. It would have to move into the swifterror
8541     // register before the call.
8542     if (TLI.supportSwiftError() &&
8543         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8544       isTailCall = false;
8545   }
8546 
8547   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8548     TargetLowering::ArgListEntry Entry;
8549     const Value *V = *I;
8550 
8551     // Skip empty types
8552     if (V->getType()->isEmptyTy())
8553       continue;
8554 
8555     SDValue ArgNode = getValue(V);
8556     Entry.Node = ArgNode; Entry.Ty = V->getType();
8557 
8558     Entry.setAttributes(&CB, I - CB.arg_begin());
8559 
8560     // Use swifterror virtual register as input to the call.
8561     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8562       SwiftErrorVal = V;
8563       // We find the virtual register for the actual swifterror argument.
8564       // Instead of using the Value, we use the virtual register instead.
8565       Entry.Node =
8566           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8567                           EVT(TLI.getPointerTy(DL)));
8568     }
8569 
8570     Args.push_back(Entry);
8571 
8572     // If we have an explicit sret argument that is an Instruction, (i.e., it
8573     // might point to function-local memory), we can't meaningfully tail-call.
8574     if (Entry.IsSRet && isa<Instruction>(V))
8575       isTailCall = false;
8576   }
8577 
8578   // If call site has a cfguardtarget operand bundle, create and add an
8579   // additional ArgListEntry.
8580   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8581     TargetLowering::ArgListEntry Entry;
8582     Value *V = Bundle->Inputs[0];
8583     SDValue ArgNode = getValue(V);
8584     Entry.Node = ArgNode;
8585     Entry.Ty = V->getType();
8586     Entry.IsCFGuardTarget = true;
8587     Args.push_back(Entry);
8588   }
8589 
8590   // Check if target-independent constraints permit a tail call here.
8591   // Target-dependent constraints are checked within TLI->LowerCallTo.
8592   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8593     isTailCall = false;
8594 
8595   // Disable tail calls if there is an swifterror argument. Targets have not
8596   // been updated to support tail calls.
8597   if (TLI.supportSwiftError() && SwiftErrorVal)
8598     isTailCall = false;
8599 
8600   ConstantInt *CFIType = nullptr;
8601   if (CB.isIndirectCall()) {
8602     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8603       if (!TLI.supportKCFIBundles())
8604         report_fatal_error(
8605             "Target doesn't support calls with kcfi operand bundles.");
8606       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8607       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8608     }
8609   }
8610 
8611   SDValue ConvControlToken;
8612   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8613     auto *Token = Bundle->Inputs[0].get();
8614     ConvControlToken = getValue(Token);
8615   }
8616 
8617   TargetLowering::CallLoweringInfo CLI(DAG);
8618   CLI.setDebugLoc(getCurSDLoc())
8619       .setChain(getRoot())
8620       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8621       .setTailCall(isTailCall)
8622       .setConvergent(CB.isConvergent())
8623       .setIsPreallocated(
8624           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8625       .setCFIType(CFIType)
8626       .setConvergenceControlToken(ConvControlToken);
8627   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8628 
8629   if (Result.first.getNode()) {
8630     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8631     setValue(&CB, Result.first);
8632   }
8633 
8634   // The last element of CLI.InVals has the SDValue for swifterror return.
8635   // Here we copy it to a virtual register and update SwiftErrorMap for
8636   // book-keeping.
8637   if (SwiftErrorVal && TLI.supportSwiftError()) {
8638     // Get the last element of InVals.
8639     SDValue Src = CLI.InVals.back();
8640     Register VReg =
8641         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8642     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8643     DAG.setRoot(CopyNode);
8644   }
8645 }
8646 
8647 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8648                              SelectionDAGBuilder &Builder) {
8649   // Check to see if this load can be trivially constant folded, e.g. if the
8650   // input is from a string literal.
8651   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8652     // Cast pointer to the type we really want to load.
8653     Type *LoadTy =
8654         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8655     if (LoadVT.isVector())
8656       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8657 
8658     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8659                                          PointerType::getUnqual(LoadTy));
8660 
8661     if (const Constant *LoadCst =
8662             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8663                                          LoadTy, Builder.DAG.getDataLayout()))
8664       return Builder.getValue(LoadCst);
8665   }
8666 
8667   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8668   // still constant memory, the input chain can be the entry node.
8669   SDValue Root;
8670   bool ConstantMemory = false;
8671 
8672   // Do not serialize (non-volatile) loads of constant memory with anything.
8673   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8674     Root = Builder.DAG.getEntryNode();
8675     ConstantMemory = true;
8676   } else {
8677     // Do not serialize non-volatile loads against each other.
8678     Root = Builder.DAG.getRoot();
8679   }
8680 
8681   SDValue Ptr = Builder.getValue(PtrVal);
8682   SDValue LoadVal =
8683       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8684                           MachinePointerInfo(PtrVal), Align(1));
8685 
8686   if (!ConstantMemory)
8687     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8688   return LoadVal;
8689 }
8690 
8691 /// Record the value for an instruction that produces an integer result,
8692 /// converting the type where necessary.
8693 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8694                                                   SDValue Value,
8695                                                   bool IsSigned) {
8696   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8697                                                     I.getType(), true);
8698   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8699   setValue(&I, Value);
8700 }
8701 
8702 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8703 /// true and lower it. Otherwise return false, and it will be lowered like a
8704 /// normal call.
8705 /// The caller already checked that \p I calls the appropriate LibFunc with a
8706 /// correct prototype.
8707 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8708   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8709   const Value *Size = I.getArgOperand(2);
8710   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8711   if (CSize && CSize->getZExtValue() == 0) {
8712     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8713                                                           I.getType(), true);
8714     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8715     return true;
8716   }
8717 
8718   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8719   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8720       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8721       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8722   if (Res.first.getNode()) {
8723     processIntegerCallValue(I, Res.first, true);
8724     PendingLoads.push_back(Res.second);
8725     return true;
8726   }
8727 
8728   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8729   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8730   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8731     return false;
8732 
8733   // If the target has a fast compare for the given size, it will return a
8734   // preferred load type for that size. Require that the load VT is legal and
8735   // that the target supports unaligned loads of that type. Otherwise, return
8736   // INVALID.
8737   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8738     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8739     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8740     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8741       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8742       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8743       // TODO: Check alignment of src and dest ptrs.
8744       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8745       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8746       if (!TLI.isTypeLegal(LVT) ||
8747           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8748           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8749         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8750     }
8751 
8752     return LVT;
8753   };
8754 
8755   // This turns into unaligned loads. We only do this if the target natively
8756   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8757   // we'll only produce a small number of byte loads.
8758   MVT LoadVT;
8759   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8760   switch (NumBitsToCompare) {
8761   default:
8762     return false;
8763   case 16:
8764     LoadVT = MVT::i16;
8765     break;
8766   case 32:
8767     LoadVT = MVT::i32;
8768     break;
8769   case 64:
8770   case 128:
8771   case 256:
8772     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8773     break;
8774   }
8775 
8776   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8777     return false;
8778 
8779   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8780   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8781 
8782   // Bitcast to a wide integer type if the loads are vectors.
8783   if (LoadVT.isVector()) {
8784     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8785     LoadL = DAG.getBitcast(CmpVT, LoadL);
8786     LoadR = DAG.getBitcast(CmpVT, LoadR);
8787   }
8788 
8789   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8790   processIntegerCallValue(I, Cmp, false);
8791   return true;
8792 }
8793 
8794 /// See if we can lower a memchr call into an optimized form. If so, return
8795 /// true and lower it. Otherwise return false, and it will be lowered like a
8796 /// normal call.
8797 /// The caller already checked that \p I calls the appropriate LibFunc with a
8798 /// correct prototype.
8799 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8800   const Value *Src = I.getArgOperand(0);
8801   const Value *Char = I.getArgOperand(1);
8802   const Value *Length = I.getArgOperand(2);
8803 
8804   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8805   std::pair<SDValue, SDValue> Res =
8806     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8807                                 getValue(Src), getValue(Char), getValue(Length),
8808                                 MachinePointerInfo(Src));
8809   if (Res.first.getNode()) {
8810     setValue(&I, Res.first);
8811     PendingLoads.push_back(Res.second);
8812     return true;
8813   }
8814 
8815   return false;
8816 }
8817 
8818 /// See if we can lower a mempcpy call into an optimized form. If so, return
8819 /// true and lower it. Otherwise return false, and it will be lowered like a
8820 /// normal call.
8821 /// The caller already checked that \p I calls the appropriate LibFunc with a
8822 /// correct prototype.
8823 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8824   SDValue Dst = getValue(I.getArgOperand(0));
8825   SDValue Src = getValue(I.getArgOperand(1));
8826   SDValue Size = getValue(I.getArgOperand(2));
8827 
8828   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8829   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8830   // DAG::getMemcpy needs Alignment to be defined.
8831   Align Alignment = std::min(DstAlign, SrcAlign);
8832 
8833   SDLoc sdl = getCurSDLoc();
8834 
8835   // In the mempcpy context we need to pass in a false value for isTailCall
8836   // because the return pointer needs to be adjusted by the size of
8837   // the copied memory.
8838   SDValue Root = getMemoryRoot();
8839   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8840                              /*isTailCall=*/false,
8841                              MachinePointerInfo(I.getArgOperand(0)),
8842                              MachinePointerInfo(I.getArgOperand(1)),
8843                              I.getAAMetadata());
8844   assert(MC.getNode() != nullptr &&
8845          "** memcpy should not be lowered as TailCall in mempcpy context **");
8846   DAG.setRoot(MC);
8847 
8848   // Check if Size needs to be truncated or extended.
8849   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8850 
8851   // Adjust return pointer to point just past the last dst byte.
8852   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8853                                     Dst, Size);
8854   setValue(&I, DstPlusSize);
8855   return true;
8856 }
8857 
8858 /// See if we can lower a strcpy call into an optimized form.  If so, return
8859 /// true and lower it, otherwise return false and it will be lowered like a
8860 /// normal call.
8861 /// The caller already checked that \p I calls the appropriate LibFunc with a
8862 /// correct prototype.
8863 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
8864   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8865 
8866   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8867   std::pair<SDValue, SDValue> Res =
8868     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
8869                                 getValue(Arg0), getValue(Arg1),
8870                                 MachinePointerInfo(Arg0),
8871                                 MachinePointerInfo(Arg1), isStpcpy);
8872   if (Res.first.getNode()) {
8873     setValue(&I, Res.first);
8874     DAG.setRoot(Res.second);
8875     return true;
8876   }
8877 
8878   return false;
8879 }
8880 
8881 /// See if we can lower a strcmp call into an optimized form.  If so, return
8882 /// true and lower it, otherwise return false and it will be lowered like a
8883 /// normal call.
8884 /// The caller already checked that \p I calls the appropriate LibFunc with a
8885 /// correct prototype.
8886 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
8887   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8888 
8889   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8890   std::pair<SDValue, SDValue> Res =
8891     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
8892                                 getValue(Arg0), getValue(Arg1),
8893                                 MachinePointerInfo(Arg0),
8894                                 MachinePointerInfo(Arg1));
8895   if (Res.first.getNode()) {
8896     processIntegerCallValue(I, Res.first, true);
8897     PendingLoads.push_back(Res.second);
8898     return true;
8899   }
8900 
8901   return false;
8902 }
8903 
8904 /// See if we can lower a strlen call into an optimized form.  If so, return
8905 /// true and lower it, otherwise return false and it will be lowered like a
8906 /// normal call.
8907 /// The caller already checked that \p I calls the appropriate LibFunc with a
8908 /// correct prototype.
8909 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
8910   const Value *Arg0 = I.getArgOperand(0);
8911 
8912   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8913   std::pair<SDValue, SDValue> Res =
8914     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
8915                                 getValue(Arg0), MachinePointerInfo(Arg0));
8916   if (Res.first.getNode()) {
8917     processIntegerCallValue(I, Res.first, false);
8918     PendingLoads.push_back(Res.second);
8919     return true;
8920   }
8921 
8922   return false;
8923 }
8924 
8925 /// See if we can lower a strnlen call into an optimized form.  If so, return
8926 /// true and lower it, otherwise return false and it will be lowered like a
8927 /// normal call.
8928 /// The caller already checked that \p I calls the appropriate LibFunc with a
8929 /// correct prototype.
8930 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
8931   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
8932 
8933   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8934   std::pair<SDValue, SDValue> Res =
8935     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
8936                                  getValue(Arg0), getValue(Arg1),
8937                                  MachinePointerInfo(Arg0));
8938   if (Res.first.getNode()) {
8939     processIntegerCallValue(I, Res.first, false);
8940     PendingLoads.push_back(Res.second);
8941     return true;
8942   }
8943 
8944   return false;
8945 }
8946 
8947 /// See if we can lower a unary floating-point operation into an SDNode with
8948 /// the specified Opcode.  If so, return true and lower it, otherwise return
8949 /// false and it will be lowered like a normal call.
8950 /// The caller already checked that \p I calls the appropriate LibFunc with a
8951 /// correct prototype.
8952 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
8953                                               unsigned Opcode) {
8954   // We already checked this call's prototype; verify it doesn't modify errno.
8955   if (!I.onlyReadsMemory())
8956     return false;
8957 
8958   SDNodeFlags Flags;
8959   Flags.copyFMF(cast<FPMathOperator>(I));
8960 
8961   SDValue Tmp = getValue(I.getArgOperand(0));
8962   setValue(&I,
8963            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
8964   return true;
8965 }
8966 
8967 /// See if we can lower a binary floating-point operation into an SDNode with
8968 /// the specified Opcode. If so, return true and lower it. Otherwise return
8969 /// false, and it will be lowered like a normal call.
8970 /// The caller already checked that \p I calls the appropriate LibFunc with a
8971 /// correct prototype.
8972 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
8973                                                unsigned Opcode) {
8974   // We already checked this call's prototype; verify it doesn't modify errno.
8975   if (!I.onlyReadsMemory())
8976     return false;
8977 
8978   SDNodeFlags Flags;
8979   Flags.copyFMF(cast<FPMathOperator>(I));
8980 
8981   SDValue Tmp0 = getValue(I.getArgOperand(0));
8982   SDValue Tmp1 = getValue(I.getArgOperand(1));
8983   EVT VT = Tmp0.getValueType();
8984   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
8985   return true;
8986 }
8987 
8988 void SelectionDAGBuilder::visitCall(const CallInst &I) {
8989   // Handle inline assembly differently.
8990   if (I.isInlineAsm()) {
8991     visitInlineAsm(I);
8992     return;
8993   }
8994 
8995   diagnoseDontCall(I);
8996 
8997   if (Function *F = I.getCalledFunction()) {
8998     if (F->isDeclaration()) {
8999       // Is this an LLVM intrinsic or a target-specific intrinsic?
9000       unsigned IID = F->getIntrinsicID();
9001       if (!IID)
9002         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9003           IID = II->getIntrinsicID(F);
9004 
9005       if (IID) {
9006         visitIntrinsicCall(I, IID);
9007         return;
9008       }
9009     }
9010 
9011     // Check for well-known libc/libm calls.  If the function is internal, it
9012     // can't be a library call.  Don't do the check if marked as nobuiltin for
9013     // some reason or the call site requires strict floating point semantics.
9014     LibFunc Func;
9015     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9016         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9017         LibInfo->hasOptimizedCodeGen(Func)) {
9018       switch (Func) {
9019       default: break;
9020       case LibFunc_bcmp:
9021         if (visitMemCmpBCmpCall(I))
9022           return;
9023         break;
9024       case LibFunc_copysign:
9025       case LibFunc_copysignf:
9026       case LibFunc_copysignl:
9027         // We already checked this call's prototype; verify it doesn't modify
9028         // errno.
9029         if (I.onlyReadsMemory()) {
9030           SDValue LHS = getValue(I.getArgOperand(0));
9031           SDValue RHS = getValue(I.getArgOperand(1));
9032           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9033                                    LHS.getValueType(), LHS, RHS));
9034           return;
9035         }
9036         break;
9037       case LibFunc_fabs:
9038       case LibFunc_fabsf:
9039       case LibFunc_fabsl:
9040         if (visitUnaryFloatCall(I, ISD::FABS))
9041           return;
9042         break;
9043       case LibFunc_fmin:
9044       case LibFunc_fminf:
9045       case LibFunc_fminl:
9046         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9047           return;
9048         break;
9049       case LibFunc_fmax:
9050       case LibFunc_fmaxf:
9051       case LibFunc_fmaxl:
9052         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9053           return;
9054         break;
9055       case LibFunc_sin:
9056       case LibFunc_sinf:
9057       case LibFunc_sinl:
9058         if (visitUnaryFloatCall(I, ISD::FSIN))
9059           return;
9060         break;
9061       case LibFunc_cos:
9062       case LibFunc_cosf:
9063       case LibFunc_cosl:
9064         if (visitUnaryFloatCall(I, ISD::FCOS))
9065           return;
9066         break;
9067       case LibFunc_sqrt:
9068       case LibFunc_sqrtf:
9069       case LibFunc_sqrtl:
9070       case LibFunc_sqrt_finite:
9071       case LibFunc_sqrtf_finite:
9072       case LibFunc_sqrtl_finite:
9073         if (visitUnaryFloatCall(I, ISD::FSQRT))
9074           return;
9075         break;
9076       case LibFunc_floor:
9077       case LibFunc_floorf:
9078       case LibFunc_floorl:
9079         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9080           return;
9081         break;
9082       case LibFunc_nearbyint:
9083       case LibFunc_nearbyintf:
9084       case LibFunc_nearbyintl:
9085         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9086           return;
9087         break;
9088       case LibFunc_ceil:
9089       case LibFunc_ceilf:
9090       case LibFunc_ceill:
9091         if (visitUnaryFloatCall(I, ISD::FCEIL))
9092           return;
9093         break;
9094       case LibFunc_rint:
9095       case LibFunc_rintf:
9096       case LibFunc_rintl:
9097         if (visitUnaryFloatCall(I, ISD::FRINT))
9098           return;
9099         break;
9100       case LibFunc_round:
9101       case LibFunc_roundf:
9102       case LibFunc_roundl:
9103         if (visitUnaryFloatCall(I, ISD::FROUND))
9104           return;
9105         break;
9106       case LibFunc_trunc:
9107       case LibFunc_truncf:
9108       case LibFunc_truncl:
9109         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9110           return;
9111         break;
9112       case LibFunc_log2:
9113       case LibFunc_log2f:
9114       case LibFunc_log2l:
9115         if (visitUnaryFloatCall(I, ISD::FLOG2))
9116           return;
9117         break;
9118       case LibFunc_exp2:
9119       case LibFunc_exp2f:
9120       case LibFunc_exp2l:
9121         if (visitUnaryFloatCall(I, ISD::FEXP2))
9122           return;
9123         break;
9124       case LibFunc_exp10:
9125       case LibFunc_exp10f:
9126       case LibFunc_exp10l:
9127         if (visitUnaryFloatCall(I, ISD::FEXP10))
9128           return;
9129         break;
9130       case LibFunc_ldexp:
9131       case LibFunc_ldexpf:
9132       case LibFunc_ldexpl:
9133         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9134           return;
9135         break;
9136       case LibFunc_memcmp:
9137         if (visitMemCmpBCmpCall(I))
9138           return;
9139         break;
9140       case LibFunc_mempcpy:
9141         if (visitMemPCpyCall(I))
9142           return;
9143         break;
9144       case LibFunc_memchr:
9145         if (visitMemChrCall(I))
9146           return;
9147         break;
9148       case LibFunc_strcpy:
9149         if (visitStrCpyCall(I, false))
9150           return;
9151         break;
9152       case LibFunc_stpcpy:
9153         if (visitStrCpyCall(I, true))
9154           return;
9155         break;
9156       case LibFunc_strcmp:
9157         if (visitStrCmpCall(I))
9158           return;
9159         break;
9160       case LibFunc_strlen:
9161         if (visitStrLenCall(I))
9162           return;
9163         break;
9164       case LibFunc_strnlen:
9165         if (visitStrNLenCall(I))
9166           return;
9167         break;
9168       }
9169     }
9170   }
9171 
9172   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9173   // have to do anything here to lower funclet bundles.
9174   // CFGuardTarget bundles are lowered in LowerCallTo.
9175   assert(!I.hasOperandBundlesOtherThan(
9176              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9177               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9178               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9179               LLVMContext::OB_convergencectrl}) &&
9180          "Cannot lower calls with arbitrary operand bundles!");
9181 
9182   SDValue Callee = getValue(I.getCalledOperand());
9183 
9184   if (I.countOperandBundlesOfType(LLVMContext::OB_deopt))
9185     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9186   else
9187     // Check if we can potentially perform a tail call. More detailed checking
9188     // is be done within LowerCallTo, after more information about the call is
9189     // known.
9190     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9191 }
9192 
9193 namespace {
9194 
9195 /// AsmOperandInfo - This contains information for each constraint that we are
9196 /// lowering.
9197 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9198 public:
9199   /// CallOperand - If this is the result output operand or a clobber
9200   /// this is null, otherwise it is the incoming operand to the CallInst.
9201   /// This gets modified as the asm is processed.
9202   SDValue CallOperand;
9203 
9204   /// AssignedRegs - If this is a register or register class operand, this
9205   /// contains the set of register corresponding to the operand.
9206   RegsForValue AssignedRegs;
9207 
9208   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9209     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9210   }
9211 
9212   /// Whether or not this operand accesses memory
9213   bool hasMemory(const TargetLowering &TLI) const {
9214     // Indirect operand accesses access memory.
9215     if (isIndirect)
9216       return true;
9217 
9218     for (const auto &Code : Codes)
9219       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9220         return true;
9221 
9222     return false;
9223   }
9224 };
9225 
9226 
9227 } // end anonymous namespace
9228 
9229 /// Make sure that the output operand \p OpInfo and its corresponding input
9230 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9231 /// out).
9232 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9233                                SDISelAsmOperandInfo &MatchingOpInfo,
9234                                SelectionDAG &DAG) {
9235   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9236     return;
9237 
9238   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9239   const auto &TLI = DAG.getTargetLoweringInfo();
9240 
9241   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9242       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9243                                        OpInfo.ConstraintVT);
9244   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9245       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9246                                        MatchingOpInfo.ConstraintVT);
9247   if ((OpInfo.ConstraintVT.isInteger() !=
9248        MatchingOpInfo.ConstraintVT.isInteger()) ||
9249       (MatchRC.second != InputRC.second)) {
9250     // FIXME: error out in a more elegant fashion
9251     report_fatal_error("Unsupported asm: input constraint"
9252                        " with a matching output constraint of"
9253                        " incompatible type!");
9254   }
9255   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9256 }
9257 
9258 /// Get a direct memory input to behave well as an indirect operand.
9259 /// This may introduce stores, hence the need for a \p Chain.
9260 /// \return The (possibly updated) chain.
9261 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9262                                         SDISelAsmOperandInfo &OpInfo,
9263                                         SelectionDAG &DAG) {
9264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9265 
9266   // If we don't have an indirect input, put it in the constpool if we can,
9267   // otherwise spill it to a stack slot.
9268   // TODO: This isn't quite right. We need to handle these according to
9269   // the addressing mode that the constraint wants. Also, this may take
9270   // an additional register for the computation and we don't want that
9271   // either.
9272 
9273   // If the operand is a float, integer, or vector constant, spill to a
9274   // constant pool entry to get its address.
9275   const Value *OpVal = OpInfo.CallOperandVal;
9276   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9277       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9278     OpInfo.CallOperand = DAG.getConstantPool(
9279         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9280     return Chain;
9281   }
9282 
9283   // Otherwise, create a stack slot and emit a store to it before the asm.
9284   Type *Ty = OpVal->getType();
9285   auto &DL = DAG.getDataLayout();
9286   uint64_t TySize = DL.getTypeAllocSize(Ty);
9287   MachineFunction &MF = DAG.getMachineFunction();
9288   int SSFI = MF.getFrameInfo().CreateStackObject(
9289       TySize, DL.getPrefTypeAlign(Ty), false);
9290   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9291   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9292                             MachinePointerInfo::getFixedStack(MF, SSFI),
9293                             TLI.getMemValueType(DL, Ty));
9294   OpInfo.CallOperand = StackSlot;
9295 
9296   return Chain;
9297 }
9298 
9299 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9300 /// specified operand.  We prefer to assign virtual registers, to allow the
9301 /// register allocator to handle the assignment process.  However, if the asm
9302 /// uses features that we can't model on machineinstrs, we have SDISel do the
9303 /// allocation.  This produces generally horrible, but correct, code.
9304 ///
9305 ///   OpInfo describes the operand
9306 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9307 static std::optional<unsigned>
9308 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9309                      SDISelAsmOperandInfo &OpInfo,
9310                      SDISelAsmOperandInfo &RefOpInfo) {
9311   LLVMContext &Context = *DAG.getContext();
9312   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9313 
9314   MachineFunction &MF = DAG.getMachineFunction();
9315   SmallVector<unsigned, 4> Regs;
9316   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9317 
9318   // No work to do for memory/address operands.
9319   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9320       OpInfo.ConstraintType == TargetLowering::C_Address)
9321     return std::nullopt;
9322 
9323   // If this is a constraint for a single physreg, or a constraint for a
9324   // register class, find it.
9325   unsigned AssignedReg;
9326   const TargetRegisterClass *RC;
9327   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9328       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9329   // RC is unset only on failure. Return immediately.
9330   if (!RC)
9331     return std::nullopt;
9332 
9333   // Get the actual register value type.  This is important, because the user
9334   // may have asked for (e.g.) the AX register in i32 type.  We need to
9335   // remember that AX is actually i16 to get the right extension.
9336   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9337 
9338   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9339     // If this is an FP operand in an integer register (or visa versa), or more
9340     // generally if the operand value disagrees with the register class we plan
9341     // to stick it in, fix the operand type.
9342     //
9343     // If this is an input value, the bitcast to the new type is done now.
9344     // Bitcast for output value is done at the end of visitInlineAsm().
9345     if ((OpInfo.Type == InlineAsm::isOutput ||
9346          OpInfo.Type == InlineAsm::isInput) &&
9347         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9348       // Try to convert to the first EVT that the reg class contains.  If the
9349       // types are identical size, use a bitcast to convert (e.g. two differing
9350       // vector types).  Note: output bitcast is done at the end of
9351       // visitInlineAsm().
9352       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9353         // Exclude indirect inputs while they are unsupported because the code
9354         // to perform the load is missing and thus OpInfo.CallOperand still
9355         // refers to the input address rather than the pointed-to value.
9356         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9357           OpInfo.CallOperand =
9358               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9359         OpInfo.ConstraintVT = RegVT;
9360         // If the operand is an FP value and we want it in integer registers,
9361         // use the corresponding integer type. This turns an f64 value into
9362         // i64, which can be passed with two i32 values on a 32-bit machine.
9363       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9364         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9365         if (OpInfo.Type == InlineAsm::isInput)
9366           OpInfo.CallOperand =
9367               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9368         OpInfo.ConstraintVT = VT;
9369       }
9370     }
9371   }
9372 
9373   // No need to allocate a matching input constraint since the constraint it's
9374   // matching to has already been allocated.
9375   if (OpInfo.isMatchingInputConstraint())
9376     return std::nullopt;
9377 
9378   EVT ValueVT = OpInfo.ConstraintVT;
9379   if (OpInfo.ConstraintVT == MVT::Other)
9380     ValueVT = RegVT;
9381 
9382   // Initialize NumRegs.
9383   unsigned NumRegs = 1;
9384   if (OpInfo.ConstraintVT != MVT::Other)
9385     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9386 
9387   // If this is a constraint for a specific physical register, like {r17},
9388   // assign it now.
9389 
9390   // If this associated to a specific register, initialize iterator to correct
9391   // place. If virtual, make sure we have enough registers
9392 
9393   // Initialize iterator if necessary
9394   TargetRegisterClass::iterator I = RC->begin();
9395   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9396 
9397   // Do not check for single registers.
9398   if (AssignedReg) {
9399     I = std::find(I, RC->end(), AssignedReg);
9400     if (I == RC->end()) {
9401       // RC does not contain the selected register, which indicates a
9402       // mismatch between the register and the required type/bitwidth.
9403       return {AssignedReg};
9404     }
9405   }
9406 
9407   for (; NumRegs; --NumRegs, ++I) {
9408     assert(I != RC->end() && "Ran out of registers to allocate!");
9409     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9410     Regs.push_back(R);
9411   }
9412 
9413   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9414   return std::nullopt;
9415 }
9416 
9417 static unsigned
9418 findMatchingInlineAsmOperand(unsigned OperandNo,
9419                              const std::vector<SDValue> &AsmNodeOperands) {
9420   // Scan until we find the definition we already emitted of this operand.
9421   unsigned CurOp = InlineAsm::Op_FirstOperand;
9422   for (; OperandNo; --OperandNo) {
9423     // Advance to the next operand.
9424     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9425     const InlineAsm::Flag F(OpFlag);
9426     assert(
9427         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9428         "Skipped past definitions?");
9429     CurOp += F.getNumOperandRegisters() + 1;
9430   }
9431   return CurOp;
9432 }
9433 
9434 namespace {
9435 
9436 class ExtraFlags {
9437   unsigned Flags = 0;
9438 
9439 public:
9440   explicit ExtraFlags(const CallBase &Call) {
9441     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9442     if (IA->hasSideEffects())
9443       Flags |= InlineAsm::Extra_HasSideEffects;
9444     if (IA->isAlignStack())
9445       Flags |= InlineAsm::Extra_IsAlignStack;
9446     if (Call.isConvergent())
9447       Flags |= InlineAsm::Extra_IsConvergent;
9448     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9449   }
9450 
9451   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9452     // Ideally, we would only check against memory constraints.  However, the
9453     // meaning of an Other constraint can be target-specific and we can't easily
9454     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9455     // for Other constraints as well.
9456     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9457         OpInfo.ConstraintType == TargetLowering::C_Other) {
9458       if (OpInfo.Type == InlineAsm::isInput)
9459         Flags |= InlineAsm::Extra_MayLoad;
9460       else if (OpInfo.Type == InlineAsm::isOutput)
9461         Flags |= InlineAsm::Extra_MayStore;
9462       else if (OpInfo.Type == InlineAsm::isClobber)
9463         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9464     }
9465   }
9466 
9467   unsigned get() const { return Flags; }
9468 };
9469 
9470 } // end anonymous namespace
9471 
9472 static bool isFunction(SDValue Op) {
9473   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9474     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9475       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9476 
9477       // In normal "call dllimport func" instruction (non-inlineasm) it force
9478       // indirect access by specifing call opcode. And usually specially print
9479       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9480       // not do in this way now. (In fact, this is similar with "Data Access"
9481       // action). So here we ignore dllimport function.
9482       if (Fn && !Fn->hasDLLImportStorageClass())
9483         return true;
9484     }
9485   }
9486   return false;
9487 }
9488 
9489 /// visitInlineAsm - Handle a call to an InlineAsm object.
9490 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9491                                          const BasicBlock *EHPadBB) {
9492   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9493 
9494   /// ConstraintOperands - Information about all of the constraints.
9495   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9496 
9497   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9498   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9499       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9500 
9501   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9502   // AsmDialect, MayLoad, MayStore).
9503   bool HasSideEffect = IA->hasSideEffects();
9504   ExtraFlags ExtraInfo(Call);
9505 
9506   for (auto &T : TargetConstraints) {
9507     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9508     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9509 
9510     if (OpInfo.CallOperandVal)
9511       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9512 
9513     if (!HasSideEffect)
9514       HasSideEffect = OpInfo.hasMemory(TLI);
9515 
9516     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9517     // FIXME: Could we compute this on OpInfo rather than T?
9518 
9519     // Compute the constraint code and ConstraintType to use.
9520     TLI.ComputeConstraintToUse(T, SDValue());
9521 
9522     if (T.ConstraintType == TargetLowering::C_Immediate &&
9523         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9524       // We've delayed emitting a diagnostic like the "n" constraint because
9525       // inlining could cause an integer showing up.
9526       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9527                                           "' expects an integer constant "
9528                                           "expression");
9529 
9530     ExtraInfo.update(T);
9531   }
9532 
9533   // We won't need to flush pending loads if this asm doesn't touch
9534   // memory and is nonvolatile.
9535   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9536 
9537   bool EmitEHLabels = isa<InvokeInst>(Call);
9538   if (EmitEHLabels) {
9539     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9540   }
9541   bool IsCallBr = isa<CallBrInst>(Call);
9542 
9543   if (IsCallBr || EmitEHLabels) {
9544     // If this is a callbr or invoke we need to flush pending exports since
9545     // inlineasm_br and invoke are terminators.
9546     // We need to do this before nodes are glued to the inlineasm_br node.
9547     Chain = getControlRoot();
9548   }
9549 
9550   MCSymbol *BeginLabel = nullptr;
9551   if (EmitEHLabels) {
9552     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9553   }
9554 
9555   int OpNo = -1;
9556   SmallVector<StringRef> AsmStrs;
9557   IA->collectAsmStrs(AsmStrs);
9558 
9559   // Second pass over the constraints: compute which constraint option to use.
9560   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9561     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9562       OpNo++;
9563 
9564     // If this is an output operand with a matching input operand, look up the
9565     // matching input. If their types mismatch, e.g. one is an integer, the
9566     // other is floating point, or their sizes are different, flag it as an
9567     // error.
9568     if (OpInfo.hasMatchingInput()) {
9569       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9570       patchMatchingInput(OpInfo, Input, DAG);
9571     }
9572 
9573     // Compute the constraint code and ConstraintType to use.
9574     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9575 
9576     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9577          OpInfo.Type == InlineAsm::isClobber) ||
9578         OpInfo.ConstraintType == TargetLowering::C_Address)
9579       continue;
9580 
9581     // In Linux PIC model, there are 4 cases about value/label addressing:
9582     //
9583     // 1: Function call or Label jmp inside the module.
9584     // 2: Data access (such as global variable, static variable) inside module.
9585     // 3: Function call or Label jmp outside the module.
9586     // 4: Data access (such as global variable) outside the module.
9587     //
9588     // Due to current llvm inline asm architecture designed to not "recognize"
9589     // the asm code, there are quite troubles for us to treat mem addressing
9590     // differently for same value/adress used in different instuctions.
9591     // For example, in pic model, call a func may in plt way or direclty
9592     // pc-related, but lea/mov a function adress may use got.
9593     //
9594     // Here we try to "recognize" function call for the case 1 and case 3 in
9595     // inline asm. And try to adjust the constraint for them.
9596     //
9597     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9598     // label, so here we don't handle jmp function label now, but we need to
9599     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9600     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9601         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9602         TM.getCodeModel() != CodeModel::Large) {
9603       OpInfo.isIndirect = false;
9604       OpInfo.ConstraintType = TargetLowering::C_Address;
9605     }
9606 
9607     // If this is a memory input, and if the operand is not indirect, do what we
9608     // need to provide an address for the memory input.
9609     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9610         !OpInfo.isIndirect) {
9611       assert((OpInfo.isMultipleAlternative ||
9612               (OpInfo.Type == InlineAsm::isInput)) &&
9613              "Can only indirectify direct input operands!");
9614 
9615       // Memory operands really want the address of the value.
9616       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9617 
9618       // There is no longer a Value* corresponding to this operand.
9619       OpInfo.CallOperandVal = nullptr;
9620 
9621       // It is now an indirect operand.
9622       OpInfo.isIndirect = true;
9623     }
9624 
9625   }
9626 
9627   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9628   std::vector<SDValue> AsmNodeOperands;
9629   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9630   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9631       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9632 
9633   // If we have a !srcloc metadata node associated with it, we want to attach
9634   // this to the ultimately generated inline asm machineinstr.  To do this, we
9635   // pass in the third operand as this (potentially null) inline asm MDNode.
9636   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9637   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9638 
9639   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9640   // bits as operand 3.
9641   AsmNodeOperands.push_back(DAG.getTargetConstant(
9642       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9643 
9644   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9645   // this, assign virtual and physical registers for inputs and otput.
9646   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9647     // Assign Registers.
9648     SDISelAsmOperandInfo &RefOpInfo =
9649         OpInfo.isMatchingInputConstraint()
9650             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9651             : OpInfo;
9652     const auto RegError =
9653         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9654     if (RegError) {
9655       const MachineFunction &MF = DAG.getMachineFunction();
9656       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9657       const char *RegName = TRI.getName(*RegError);
9658       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9659                                    "' allocated for constraint '" +
9660                                    Twine(OpInfo.ConstraintCode) +
9661                                    "' does not match required type");
9662       return;
9663     }
9664 
9665     auto DetectWriteToReservedRegister = [&]() {
9666       const MachineFunction &MF = DAG.getMachineFunction();
9667       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9668       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9669         if (Register::isPhysicalRegister(Reg) &&
9670             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9671           const char *RegName = TRI.getName(Reg);
9672           emitInlineAsmError(Call, "write to reserved register '" +
9673                                        Twine(RegName) + "'");
9674           return true;
9675         }
9676       }
9677       return false;
9678     };
9679     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9680             (OpInfo.Type == InlineAsm::isInput &&
9681              !OpInfo.isMatchingInputConstraint())) &&
9682            "Only address as input operand is allowed.");
9683 
9684     switch (OpInfo.Type) {
9685     case InlineAsm::isOutput:
9686       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9687         const InlineAsm::ConstraintCode ConstraintID =
9688             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9689         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9690                "Failed to convert memory constraint code to constraint id.");
9691 
9692         // Add information to the INLINEASM node to know about this output.
9693         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9694         OpFlags.setMemConstraint(ConstraintID);
9695         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9696                                                         MVT::i32));
9697         AsmNodeOperands.push_back(OpInfo.CallOperand);
9698       } else {
9699         // Otherwise, this outputs to a register (directly for C_Register /
9700         // C_RegisterClass, and a target-defined fashion for
9701         // C_Immediate/C_Other). Find a register that we can use.
9702         if (OpInfo.AssignedRegs.Regs.empty()) {
9703           emitInlineAsmError(
9704               Call, "couldn't allocate output register for constraint '" +
9705                         Twine(OpInfo.ConstraintCode) + "'");
9706           return;
9707         }
9708 
9709         if (DetectWriteToReservedRegister())
9710           return;
9711 
9712         // Add information to the INLINEASM node to know that this register is
9713         // set.
9714         OpInfo.AssignedRegs.AddInlineAsmOperands(
9715             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9716                                   : InlineAsm::Kind::RegDef,
9717             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9718       }
9719       break;
9720 
9721     case InlineAsm::isInput:
9722     case InlineAsm::isLabel: {
9723       SDValue InOperandVal = OpInfo.CallOperand;
9724 
9725       if (OpInfo.isMatchingInputConstraint()) {
9726         // If this is required to match an output register we have already set,
9727         // just use its register.
9728         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9729                                                   AsmNodeOperands);
9730         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
9731         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9732           if (OpInfo.isIndirect) {
9733             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9734             emitInlineAsmError(Call, "inline asm not supported yet: "
9735                                      "don't know how to handle tied "
9736                                      "indirect register inputs");
9737             return;
9738           }
9739 
9740           SmallVector<unsigned, 4> Regs;
9741           MachineFunction &MF = DAG.getMachineFunction();
9742           MachineRegisterInfo &MRI = MF.getRegInfo();
9743           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9744           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9745           Register TiedReg = R->getReg();
9746           MVT RegVT = R->getSimpleValueType(0);
9747           const TargetRegisterClass *RC =
9748               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9749               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9750                                       : TRI.getMinimalPhysRegClass(TiedReg);
9751           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9752             Regs.push_back(MRI.createVirtualRegister(RC));
9753 
9754           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9755 
9756           SDLoc dl = getCurSDLoc();
9757           // Use the produced MatchedRegs object to
9758           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9759           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9760                                            OpInfo.getMatchedOperand(), dl, DAG,
9761                                            AsmNodeOperands);
9762           break;
9763         }
9764 
9765         assert(Flag.isMemKind() && "Unknown matching constraint!");
9766         assert(Flag.getNumOperandRegisters() == 1 &&
9767                "Unexpected number of operands");
9768         // Add information to the INLINEASM node to know about this input.
9769         // See InlineAsm.h isUseOperandTiedToDef.
9770         Flag.clearMemConstraint();
9771         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9772         AsmNodeOperands.push_back(DAG.getTargetConstant(
9773             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9774         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9775         break;
9776       }
9777 
9778       // Treat indirect 'X' constraint as memory.
9779       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9780           OpInfo.isIndirect)
9781         OpInfo.ConstraintType = TargetLowering::C_Memory;
9782 
9783       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9784           OpInfo.ConstraintType == TargetLowering::C_Other) {
9785         std::vector<SDValue> Ops;
9786         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9787                                           Ops, DAG);
9788         if (Ops.empty()) {
9789           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9790             if (isa<ConstantSDNode>(InOperandVal)) {
9791               emitInlineAsmError(Call, "value out of range for constraint '" +
9792                                            Twine(OpInfo.ConstraintCode) + "'");
9793               return;
9794             }
9795 
9796           emitInlineAsmError(Call,
9797                              "invalid operand for inline asm constraint '" +
9798                                  Twine(OpInfo.ConstraintCode) + "'");
9799           return;
9800         }
9801 
9802         // Add information to the INLINEASM node to know about this input.
9803         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9804         AsmNodeOperands.push_back(DAG.getTargetConstant(
9805             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9806         llvm::append_range(AsmNodeOperands, Ops);
9807         break;
9808       }
9809 
9810       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9811         assert((OpInfo.isIndirect ||
9812                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
9813                "Operand must be indirect to be a mem!");
9814         assert(InOperandVal.getValueType() ==
9815                    TLI.getPointerTy(DAG.getDataLayout()) &&
9816                "Memory operands expect pointer values");
9817 
9818         const InlineAsm::ConstraintCode ConstraintID =
9819             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9820         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9821                "Failed to convert memory constraint code to constraint id.");
9822 
9823         // Add information to the INLINEASM node to know about this input.
9824         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9825         ResOpType.setMemConstraint(ConstraintID);
9826         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
9827                                                         getCurSDLoc(),
9828                                                         MVT::i32));
9829         AsmNodeOperands.push_back(InOperandVal);
9830         break;
9831       }
9832 
9833       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
9834         const InlineAsm::ConstraintCode ConstraintID =
9835             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9836         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9837                "Failed to convert memory constraint code to constraint id.");
9838 
9839         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
9840 
9841         SDValue AsmOp = InOperandVal;
9842         if (isFunction(InOperandVal)) {
9843           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
9844           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
9845           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
9846                                              InOperandVal.getValueType(),
9847                                              GA->getOffset());
9848         }
9849 
9850         // Add information to the INLINEASM node to know about this input.
9851         ResOpType.setMemConstraint(ConstraintID);
9852 
9853         AsmNodeOperands.push_back(
9854             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
9855 
9856         AsmNodeOperands.push_back(AsmOp);
9857         break;
9858       }
9859 
9860       assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
9861               OpInfo.ConstraintType == TargetLowering::C_Register) &&
9862              "Unknown constraint type!");
9863 
9864       // TODO: Support this.
9865       if (OpInfo.isIndirect) {
9866         emitInlineAsmError(
9867             Call, "Don't know how to handle indirect register inputs yet "
9868                   "for constraint '" +
9869                       Twine(OpInfo.ConstraintCode) + "'");
9870         return;
9871       }
9872 
9873       // Copy the input into the appropriate registers.
9874       if (OpInfo.AssignedRegs.Regs.empty()) {
9875         emitInlineAsmError(Call,
9876                            "couldn't allocate input reg for constraint '" +
9877                                Twine(OpInfo.ConstraintCode) + "'");
9878         return;
9879       }
9880 
9881       if (DetectWriteToReservedRegister())
9882         return;
9883 
9884       SDLoc dl = getCurSDLoc();
9885 
9886       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
9887                                         &Call);
9888 
9889       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
9890                                                0, dl, DAG, AsmNodeOperands);
9891       break;
9892     }
9893     case InlineAsm::isClobber:
9894       // Add the clobbered value to the operand list, so that the register
9895       // allocator is aware that the physreg got clobbered.
9896       if (!OpInfo.AssignedRegs.Regs.empty())
9897         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
9898                                                  false, 0, getCurSDLoc(), DAG,
9899                                                  AsmNodeOperands);
9900       break;
9901     }
9902   }
9903 
9904   // Finish up input operands.  Set the input chain and add the flag last.
9905   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
9906   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
9907 
9908   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
9909   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
9910                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
9911   Glue = Chain.getValue(1);
9912 
9913   // Do additional work to generate outputs.
9914 
9915   SmallVector<EVT, 1> ResultVTs;
9916   SmallVector<SDValue, 1> ResultValues;
9917   SmallVector<SDValue, 8> OutChains;
9918 
9919   llvm::Type *CallResultType = Call.getType();
9920   ArrayRef<Type *> ResultTypes;
9921   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
9922     ResultTypes = StructResult->elements();
9923   else if (!CallResultType->isVoidTy())
9924     ResultTypes = ArrayRef(CallResultType);
9925 
9926   auto CurResultType = ResultTypes.begin();
9927   auto handleRegAssign = [&](SDValue V) {
9928     assert(CurResultType != ResultTypes.end() && "Unexpected value");
9929     assert((*CurResultType)->isSized() && "Unexpected unsized type");
9930     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
9931     ++CurResultType;
9932     // If the type of the inline asm call site return value is different but has
9933     // same size as the type of the asm output bitcast it.  One example of this
9934     // is for vectors with different width / number of elements.  This can
9935     // happen for register classes that can contain multiple different value
9936     // types.  The preg or vreg allocated may not have the same VT as was
9937     // expected.
9938     //
9939     // This can also happen for a return value that disagrees with the register
9940     // class it is put in, eg. a double in a general-purpose register on a
9941     // 32-bit machine.
9942     if (ResultVT != V.getValueType() &&
9943         ResultVT.getSizeInBits() == V.getValueSizeInBits())
9944       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
9945     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
9946              V.getValueType().isInteger()) {
9947       // If a result value was tied to an input value, the computed result
9948       // may have a wider width than the expected result.  Extract the
9949       // relevant portion.
9950       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
9951     }
9952     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
9953     ResultVTs.push_back(ResultVT);
9954     ResultValues.push_back(V);
9955   };
9956 
9957   // Deal with output operands.
9958   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9959     if (OpInfo.Type == InlineAsm::isOutput) {
9960       SDValue Val;
9961       // Skip trivial output operands.
9962       if (OpInfo.AssignedRegs.Regs.empty())
9963         continue;
9964 
9965       switch (OpInfo.ConstraintType) {
9966       case TargetLowering::C_Register:
9967       case TargetLowering::C_RegisterClass:
9968         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
9969                                                   Chain, &Glue, &Call);
9970         break;
9971       case TargetLowering::C_Immediate:
9972       case TargetLowering::C_Other:
9973         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
9974                                               OpInfo, DAG);
9975         break;
9976       case TargetLowering::C_Memory:
9977         break; // Already handled.
9978       case TargetLowering::C_Address:
9979         break; // Silence warning.
9980       case TargetLowering::C_Unknown:
9981         assert(false && "Unexpected unknown constraint");
9982       }
9983 
9984       // Indirect output manifest as stores. Record output chains.
9985       if (OpInfo.isIndirect) {
9986         const Value *Ptr = OpInfo.CallOperandVal;
9987         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
9988         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
9989                                      MachinePointerInfo(Ptr));
9990         OutChains.push_back(Store);
9991       } else {
9992         // generate CopyFromRegs to associated registers.
9993         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
9994         if (Val.getOpcode() == ISD::MERGE_VALUES) {
9995           for (const SDValue &V : Val->op_values())
9996             handleRegAssign(V);
9997         } else
9998           handleRegAssign(Val);
9999       }
10000     }
10001   }
10002 
10003   // Set results.
10004   if (!ResultValues.empty()) {
10005     assert(CurResultType == ResultTypes.end() &&
10006            "Mismatch in number of ResultTypes");
10007     assert(ResultValues.size() == ResultTypes.size() &&
10008            "Mismatch in number of output operands in asm result");
10009 
10010     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10011                             DAG.getVTList(ResultVTs), ResultValues);
10012     setValue(&Call, V);
10013   }
10014 
10015   // Collect store chains.
10016   if (!OutChains.empty())
10017     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10018 
10019   if (EmitEHLabels) {
10020     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10021   }
10022 
10023   // Only Update Root if inline assembly has a memory effect.
10024   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10025       EmitEHLabels)
10026     DAG.setRoot(Chain);
10027 }
10028 
10029 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10030                                              const Twine &Message) {
10031   LLVMContext &Ctx = *DAG.getContext();
10032   Ctx.emitError(&Call, Message);
10033 
10034   // Make sure we leave the DAG in a valid state
10035   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10036   SmallVector<EVT, 1> ValueVTs;
10037   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10038 
10039   if (ValueVTs.empty())
10040     return;
10041 
10042   SmallVector<SDValue, 1> Ops;
10043   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
10044     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
10045 
10046   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10047 }
10048 
10049 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10050   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10051                           MVT::Other, getRoot(),
10052                           getValue(I.getArgOperand(0)),
10053                           DAG.getSrcValue(I.getArgOperand(0))));
10054 }
10055 
10056 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10057   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10058   const DataLayout &DL = DAG.getDataLayout();
10059   SDValue V = DAG.getVAArg(
10060       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10061       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10062       DL.getABITypeAlign(I.getType()).value());
10063   DAG.setRoot(V.getValue(1));
10064 
10065   if (I.getType()->isPointerTy())
10066     V = DAG.getPtrExtOrTrunc(
10067         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10068   setValue(&I, V);
10069 }
10070 
10071 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10072   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10073                           MVT::Other, getRoot(),
10074                           getValue(I.getArgOperand(0)),
10075                           DAG.getSrcValue(I.getArgOperand(0))));
10076 }
10077 
10078 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10079   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10080                           MVT::Other, getRoot(),
10081                           getValue(I.getArgOperand(0)),
10082                           getValue(I.getArgOperand(1)),
10083                           DAG.getSrcValue(I.getArgOperand(0)),
10084                           DAG.getSrcValue(I.getArgOperand(1))));
10085 }
10086 
10087 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10088                                                     const Instruction &I,
10089                                                     SDValue Op) {
10090   const MDNode *Range = getRangeMetadata(I);
10091   if (!Range)
10092     return Op;
10093 
10094   ConstantRange CR = getConstantRangeFromMetadata(*Range);
10095   if (CR.isFullSet() || CR.isEmptySet() || CR.isUpperWrapped())
10096     return Op;
10097 
10098   APInt Lo = CR.getUnsignedMin();
10099   if (!Lo.isMinValue())
10100     return Op;
10101 
10102   APInt Hi = CR.getUnsignedMax();
10103   unsigned Bits = std::max(Hi.getActiveBits(),
10104                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10105 
10106   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10107 
10108   SDLoc SL = getCurSDLoc();
10109 
10110   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10111                              DAG.getValueType(SmallVT));
10112   unsigned NumVals = Op.getNode()->getNumValues();
10113   if (NumVals == 1)
10114     return ZExt;
10115 
10116   SmallVector<SDValue, 4> Ops;
10117 
10118   Ops.push_back(ZExt);
10119   for (unsigned I = 1; I != NumVals; ++I)
10120     Ops.push_back(Op.getValue(I));
10121 
10122   return DAG.getMergeValues(Ops, SL);
10123 }
10124 
10125 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10126 /// the call being lowered.
10127 ///
10128 /// This is a helper for lowering intrinsics that follow a target calling
10129 /// convention or require stack pointer adjustment. Only a subset of the
10130 /// intrinsic's operands need to participate in the calling convention.
10131 void SelectionDAGBuilder::populateCallLoweringInfo(
10132     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10133     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10134     AttributeSet RetAttrs, bool IsPatchPoint) {
10135   TargetLowering::ArgListTy Args;
10136   Args.reserve(NumArgs);
10137 
10138   // Populate the argument list.
10139   // Attributes for args start at offset 1, after the return attribute.
10140   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10141        ArgI != ArgE; ++ArgI) {
10142     const Value *V = Call->getOperand(ArgI);
10143 
10144     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10145 
10146     TargetLowering::ArgListEntry Entry;
10147     Entry.Node = getValue(V);
10148     Entry.Ty = V->getType();
10149     Entry.setAttributes(Call, ArgI);
10150     Args.push_back(Entry);
10151   }
10152 
10153   CLI.setDebugLoc(getCurSDLoc())
10154       .setChain(getRoot())
10155       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10156                  RetAttrs)
10157       .setDiscardResult(Call->use_empty())
10158       .setIsPatchPoint(IsPatchPoint)
10159       .setIsPreallocated(
10160           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10161 }
10162 
10163 /// Add a stack map intrinsic call's live variable operands to a stackmap
10164 /// or patchpoint target node's operand list.
10165 ///
10166 /// Constants are converted to TargetConstants purely as an optimization to
10167 /// avoid constant materialization and register allocation.
10168 ///
10169 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10170 /// generate addess computation nodes, and so FinalizeISel can convert the
10171 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10172 /// address materialization and register allocation, but may also be required
10173 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10174 /// alloca in the entry block, then the runtime may assume that the alloca's
10175 /// StackMap location can be read immediately after compilation and that the
10176 /// location is valid at any point during execution (this is similar to the
10177 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10178 /// only available in a register, then the runtime would need to trap when
10179 /// execution reaches the StackMap in order to read the alloca's location.
10180 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10181                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10182                                 SelectionDAGBuilder &Builder) {
10183   SelectionDAG &DAG = Builder.DAG;
10184   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10185     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10186 
10187     // Things on the stack are pointer-typed, meaning that they are already
10188     // legal and can be emitted directly to target nodes.
10189     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10190       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10191     } else {
10192       // Otherwise emit a target independent node to be legalised.
10193       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10194     }
10195   }
10196 }
10197 
10198 /// Lower llvm.experimental.stackmap.
10199 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10200   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10201   //                                  [live variables...])
10202 
10203   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10204 
10205   SDValue Chain, InGlue, Callee;
10206   SmallVector<SDValue, 32> Ops;
10207 
10208   SDLoc DL = getCurSDLoc();
10209   Callee = getValue(CI.getCalledOperand());
10210 
10211   // The stackmap intrinsic only records the live variables (the arguments
10212   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10213   // intrinsic, this won't be lowered to a function call. This means we don't
10214   // have to worry about calling conventions and target specific lowering code.
10215   // Instead we perform the call lowering right here.
10216   //
10217   // chain, flag = CALLSEQ_START(chain, 0, 0)
10218   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10219   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10220   //
10221   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10222   InGlue = Chain.getValue(1);
10223 
10224   // Add the STACKMAP operands, starting with DAG house-keeping.
10225   Ops.push_back(Chain);
10226   Ops.push_back(InGlue);
10227 
10228   // Add the <id>, <numShadowBytes> operands.
10229   //
10230   // These do not require legalisation, and can be emitted directly to target
10231   // constant nodes.
10232   SDValue ID = getValue(CI.getArgOperand(0));
10233   assert(ID.getValueType() == MVT::i64);
10234   SDValue IDConst =
10235       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10236   Ops.push_back(IDConst);
10237 
10238   SDValue Shad = getValue(CI.getArgOperand(1));
10239   assert(Shad.getValueType() == MVT::i32);
10240   SDValue ShadConst =
10241       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10242   Ops.push_back(ShadConst);
10243 
10244   // Add the live variables.
10245   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10246 
10247   // Create the STACKMAP node.
10248   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10249   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10250   InGlue = Chain.getValue(1);
10251 
10252   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10253 
10254   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10255 
10256   // Set the root to the target-lowered call chain.
10257   DAG.setRoot(Chain);
10258 
10259   // Inform the Frame Information that we have a stackmap in this function.
10260   FuncInfo.MF->getFrameInfo().setHasStackMap();
10261 }
10262 
10263 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10264 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10265                                           const BasicBlock *EHPadBB) {
10266   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10267   //                                         i32 <numBytes>,
10268   //                                         i8* <target>,
10269   //                                         i32 <numArgs>,
10270   //                                         [Args...],
10271   //                                         [live variables...])
10272 
10273   CallingConv::ID CC = CB.getCallingConv();
10274   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10275   bool HasDef = !CB.getType()->isVoidTy();
10276   SDLoc dl = getCurSDLoc();
10277   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10278 
10279   // Handle immediate and symbolic callees.
10280   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10281     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10282                                    /*isTarget=*/true);
10283   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10284     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10285                                          SDLoc(SymbolicCallee),
10286                                          SymbolicCallee->getValueType(0));
10287 
10288   // Get the real number of arguments participating in the call <numArgs>
10289   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10290   unsigned NumArgs = NArgVal->getAsZExtVal();
10291 
10292   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10293   // Intrinsics include all meta-operands up to but not including CC.
10294   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10295   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10296          "Not enough arguments provided to the patchpoint intrinsic");
10297 
10298   // For AnyRegCC the arguments are lowered later on manually.
10299   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10300   Type *ReturnTy =
10301       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10302 
10303   TargetLowering::CallLoweringInfo CLI(DAG);
10304   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10305                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10306   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10307 
10308   SDNode *CallEnd = Result.second.getNode();
10309   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10310     CallEnd = CallEnd->getOperand(0).getNode();
10311 
10312   /// Get a call instruction from the call sequence chain.
10313   /// Tail calls are not allowed.
10314   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10315          "Expected a callseq node.");
10316   SDNode *Call = CallEnd->getOperand(0).getNode();
10317   bool HasGlue = Call->getGluedNode();
10318 
10319   // Replace the target specific call node with the patchable intrinsic.
10320   SmallVector<SDValue, 8> Ops;
10321 
10322   // Push the chain.
10323   Ops.push_back(*(Call->op_begin()));
10324 
10325   // Optionally, push the glue (if any).
10326   if (HasGlue)
10327     Ops.push_back(*(Call->op_end() - 1));
10328 
10329   // Push the register mask info.
10330   if (HasGlue)
10331     Ops.push_back(*(Call->op_end() - 2));
10332   else
10333     Ops.push_back(*(Call->op_end() - 1));
10334 
10335   // Add the <id> and <numBytes> constants.
10336   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10337   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10338   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10339   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10340 
10341   // Add the callee.
10342   Ops.push_back(Callee);
10343 
10344   // Adjust <numArgs> to account for any arguments that have been passed on the
10345   // stack instead.
10346   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10347   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10348   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10349   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10350 
10351   // Add the calling convention
10352   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10353 
10354   // Add the arguments we omitted previously. The register allocator should
10355   // place these in any free register.
10356   if (IsAnyRegCC)
10357     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10358       Ops.push_back(getValue(CB.getArgOperand(i)));
10359 
10360   // Push the arguments from the call instruction.
10361   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10362   Ops.append(Call->op_begin() + 2, e);
10363 
10364   // Push live variables for the stack map.
10365   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10366 
10367   SDVTList NodeTys;
10368   if (IsAnyRegCC && HasDef) {
10369     // Create the return types based on the intrinsic definition
10370     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10371     SmallVector<EVT, 3> ValueVTs;
10372     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10373     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10374 
10375     // There is always a chain and a glue type at the end
10376     ValueVTs.push_back(MVT::Other);
10377     ValueVTs.push_back(MVT::Glue);
10378     NodeTys = DAG.getVTList(ValueVTs);
10379   } else
10380     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10381 
10382   // Replace the target specific call node with a PATCHPOINT node.
10383   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10384 
10385   // Update the NodeMap.
10386   if (HasDef) {
10387     if (IsAnyRegCC)
10388       setValue(&CB, SDValue(PPV.getNode(), 0));
10389     else
10390       setValue(&CB, Result.first);
10391   }
10392 
10393   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10394   // call sequence. Furthermore the location of the chain and glue can change
10395   // when the AnyReg calling convention is used and the intrinsic returns a
10396   // value.
10397   if (IsAnyRegCC && HasDef) {
10398     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10399     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10400     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10401   } else
10402     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10403   DAG.DeleteNode(Call);
10404 
10405   // Inform the Frame Information that we have a patchpoint in this function.
10406   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10407 }
10408 
10409 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10410                                             unsigned Intrinsic) {
10411   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10412   SDValue Op1 = getValue(I.getArgOperand(0));
10413   SDValue Op2;
10414   if (I.arg_size() > 1)
10415     Op2 = getValue(I.getArgOperand(1));
10416   SDLoc dl = getCurSDLoc();
10417   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10418   SDValue Res;
10419   SDNodeFlags SDFlags;
10420   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10421     SDFlags.copyFMF(*FPMO);
10422 
10423   switch (Intrinsic) {
10424   case Intrinsic::vector_reduce_fadd:
10425     if (SDFlags.hasAllowReassociation())
10426       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10427                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10428                         SDFlags);
10429     else
10430       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10431     break;
10432   case Intrinsic::vector_reduce_fmul:
10433     if (SDFlags.hasAllowReassociation())
10434       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10435                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10436                         SDFlags);
10437     else
10438       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10439     break;
10440   case Intrinsic::vector_reduce_add:
10441     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10442     break;
10443   case Intrinsic::vector_reduce_mul:
10444     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10445     break;
10446   case Intrinsic::vector_reduce_and:
10447     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10448     break;
10449   case Intrinsic::vector_reduce_or:
10450     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10451     break;
10452   case Intrinsic::vector_reduce_xor:
10453     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10454     break;
10455   case Intrinsic::vector_reduce_smax:
10456     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10457     break;
10458   case Intrinsic::vector_reduce_smin:
10459     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10460     break;
10461   case Intrinsic::vector_reduce_umax:
10462     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10463     break;
10464   case Intrinsic::vector_reduce_umin:
10465     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10466     break;
10467   case Intrinsic::vector_reduce_fmax:
10468     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10469     break;
10470   case Intrinsic::vector_reduce_fmin:
10471     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10472     break;
10473   case Intrinsic::vector_reduce_fmaximum:
10474     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10475     break;
10476   case Intrinsic::vector_reduce_fminimum:
10477     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10478     break;
10479   default:
10480     llvm_unreachable("Unhandled vector reduce intrinsic");
10481   }
10482   setValue(&I, Res);
10483 }
10484 
10485 /// Returns an AttributeList representing the attributes applied to the return
10486 /// value of the given call.
10487 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10488   SmallVector<Attribute::AttrKind, 2> Attrs;
10489   if (CLI.RetSExt)
10490     Attrs.push_back(Attribute::SExt);
10491   if (CLI.RetZExt)
10492     Attrs.push_back(Attribute::ZExt);
10493   if (CLI.IsInReg)
10494     Attrs.push_back(Attribute::InReg);
10495 
10496   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10497                             Attrs);
10498 }
10499 
10500 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10501 /// implementation, which just calls LowerCall.
10502 /// FIXME: When all targets are
10503 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10504 std::pair<SDValue, SDValue>
10505 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10506   // Handle the incoming return values from the call.
10507   CLI.Ins.clear();
10508   Type *OrigRetTy = CLI.RetTy;
10509   SmallVector<EVT, 4> RetTys;
10510   SmallVector<TypeSize, 4> Offsets;
10511   auto &DL = CLI.DAG.getDataLayout();
10512   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10513 
10514   if (CLI.IsPostTypeLegalization) {
10515     // If we are lowering a libcall after legalization, split the return type.
10516     SmallVector<EVT, 4> OldRetTys;
10517     SmallVector<TypeSize, 4> OldOffsets;
10518     RetTys.swap(OldRetTys);
10519     Offsets.swap(OldOffsets);
10520 
10521     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10522       EVT RetVT = OldRetTys[i];
10523       uint64_t Offset = OldOffsets[i];
10524       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10525       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10526       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10527       RetTys.append(NumRegs, RegisterVT);
10528       for (unsigned j = 0; j != NumRegs; ++j)
10529         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10530     }
10531   }
10532 
10533   SmallVector<ISD::OutputArg, 4> Outs;
10534   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10535 
10536   bool CanLowerReturn =
10537       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10538                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10539 
10540   SDValue DemoteStackSlot;
10541   int DemoteStackIdx = -100;
10542   if (!CanLowerReturn) {
10543     // FIXME: equivalent assert?
10544     // assert(!CS.hasInAllocaArgument() &&
10545     //        "sret demotion is incompatible with inalloca");
10546     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10547     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10548     MachineFunction &MF = CLI.DAG.getMachineFunction();
10549     DemoteStackIdx =
10550         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10551     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10552                                               DL.getAllocaAddrSpace());
10553 
10554     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10555     ArgListEntry Entry;
10556     Entry.Node = DemoteStackSlot;
10557     Entry.Ty = StackSlotPtrType;
10558     Entry.IsSExt = false;
10559     Entry.IsZExt = false;
10560     Entry.IsInReg = false;
10561     Entry.IsSRet = true;
10562     Entry.IsNest = false;
10563     Entry.IsByVal = false;
10564     Entry.IsByRef = false;
10565     Entry.IsReturned = false;
10566     Entry.IsSwiftSelf = false;
10567     Entry.IsSwiftAsync = false;
10568     Entry.IsSwiftError = false;
10569     Entry.IsCFGuardTarget = false;
10570     Entry.Alignment = Alignment;
10571     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10572     CLI.NumFixedArgs += 1;
10573     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10574     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10575 
10576     // sret demotion isn't compatible with tail-calls, since the sret argument
10577     // points into the callers stack frame.
10578     CLI.IsTailCall = false;
10579   } else {
10580     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10581         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10582     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10583       ISD::ArgFlagsTy Flags;
10584       if (NeedsRegBlock) {
10585         Flags.setInConsecutiveRegs();
10586         if (I == RetTys.size() - 1)
10587           Flags.setInConsecutiveRegsLast();
10588       }
10589       EVT VT = RetTys[I];
10590       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10591                                                      CLI.CallConv, VT);
10592       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10593                                                        CLI.CallConv, VT);
10594       for (unsigned i = 0; i != NumRegs; ++i) {
10595         ISD::InputArg MyFlags;
10596         MyFlags.Flags = Flags;
10597         MyFlags.VT = RegisterVT;
10598         MyFlags.ArgVT = VT;
10599         MyFlags.Used = CLI.IsReturnValueUsed;
10600         if (CLI.RetTy->isPointerTy()) {
10601           MyFlags.Flags.setPointer();
10602           MyFlags.Flags.setPointerAddrSpace(
10603               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10604         }
10605         if (CLI.RetSExt)
10606           MyFlags.Flags.setSExt();
10607         if (CLI.RetZExt)
10608           MyFlags.Flags.setZExt();
10609         if (CLI.IsInReg)
10610           MyFlags.Flags.setInReg();
10611         CLI.Ins.push_back(MyFlags);
10612       }
10613     }
10614   }
10615 
10616   // We push in swifterror return as the last element of CLI.Ins.
10617   ArgListTy &Args = CLI.getArgs();
10618   if (supportSwiftError()) {
10619     for (const ArgListEntry &Arg : Args) {
10620       if (Arg.IsSwiftError) {
10621         ISD::InputArg MyFlags;
10622         MyFlags.VT = getPointerTy(DL);
10623         MyFlags.ArgVT = EVT(getPointerTy(DL));
10624         MyFlags.Flags.setSwiftError();
10625         CLI.Ins.push_back(MyFlags);
10626       }
10627     }
10628   }
10629 
10630   // Handle all of the outgoing arguments.
10631   CLI.Outs.clear();
10632   CLI.OutVals.clear();
10633   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10634     SmallVector<EVT, 4> ValueVTs;
10635     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10636     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10637     Type *FinalType = Args[i].Ty;
10638     if (Args[i].IsByVal)
10639       FinalType = Args[i].IndirectType;
10640     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10641         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10642     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10643          ++Value) {
10644       EVT VT = ValueVTs[Value];
10645       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10646       SDValue Op = SDValue(Args[i].Node.getNode(),
10647                            Args[i].Node.getResNo() + Value);
10648       ISD::ArgFlagsTy Flags;
10649 
10650       // Certain targets (such as MIPS), may have a different ABI alignment
10651       // for a type depending on the context. Give the target a chance to
10652       // specify the alignment it wants.
10653       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10654       Flags.setOrigAlign(OriginalAlignment);
10655 
10656       if (Args[i].Ty->isPointerTy()) {
10657         Flags.setPointer();
10658         Flags.setPointerAddrSpace(
10659             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10660       }
10661       if (Args[i].IsZExt)
10662         Flags.setZExt();
10663       if (Args[i].IsSExt)
10664         Flags.setSExt();
10665       if (Args[i].IsInReg) {
10666         // If we are using vectorcall calling convention, a structure that is
10667         // passed InReg - is surely an HVA
10668         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10669             isa<StructType>(FinalType)) {
10670           // The first value of a structure is marked
10671           if (0 == Value)
10672             Flags.setHvaStart();
10673           Flags.setHva();
10674         }
10675         // Set InReg Flag
10676         Flags.setInReg();
10677       }
10678       if (Args[i].IsSRet)
10679         Flags.setSRet();
10680       if (Args[i].IsSwiftSelf)
10681         Flags.setSwiftSelf();
10682       if (Args[i].IsSwiftAsync)
10683         Flags.setSwiftAsync();
10684       if (Args[i].IsSwiftError)
10685         Flags.setSwiftError();
10686       if (Args[i].IsCFGuardTarget)
10687         Flags.setCFGuardTarget();
10688       if (Args[i].IsByVal)
10689         Flags.setByVal();
10690       if (Args[i].IsByRef)
10691         Flags.setByRef();
10692       if (Args[i].IsPreallocated) {
10693         Flags.setPreallocated();
10694         // Set the byval flag for CCAssignFn callbacks that don't know about
10695         // preallocated.  This way we can know how many bytes we should've
10696         // allocated and how many bytes a callee cleanup function will pop.  If
10697         // we port preallocated to more targets, we'll have to add custom
10698         // preallocated handling in the various CC lowering callbacks.
10699         Flags.setByVal();
10700       }
10701       if (Args[i].IsInAlloca) {
10702         Flags.setInAlloca();
10703         // Set the byval flag for CCAssignFn callbacks that don't know about
10704         // inalloca.  This way we can know how many bytes we should've allocated
10705         // and how many bytes a callee cleanup function will pop.  If we port
10706         // inalloca to more targets, we'll have to add custom inalloca handling
10707         // in the various CC lowering callbacks.
10708         Flags.setByVal();
10709       }
10710       Align MemAlign;
10711       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10712         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10713         Flags.setByValSize(FrameSize);
10714 
10715         // info is not there but there are cases it cannot get right.
10716         if (auto MA = Args[i].Alignment)
10717           MemAlign = *MA;
10718         else
10719           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10720       } else if (auto MA = Args[i].Alignment) {
10721         MemAlign = *MA;
10722       } else {
10723         MemAlign = OriginalAlignment;
10724       }
10725       Flags.setMemAlign(MemAlign);
10726       if (Args[i].IsNest)
10727         Flags.setNest();
10728       if (NeedsRegBlock)
10729         Flags.setInConsecutiveRegs();
10730 
10731       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10732                                                  CLI.CallConv, VT);
10733       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10734                                                         CLI.CallConv, VT);
10735       SmallVector<SDValue, 4> Parts(NumParts);
10736       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10737 
10738       if (Args[i].IsSExt)
10739         ExtendKind = ISD::SIGN_EXTEND;
10740       else if (Args[i].IsZExt)
10741         ExtendKind = ISD::ZERO_EXTEND;
10742 
10743       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10744       // for now.
10745       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10746           CanLowerReturn) {
10747         assert((CLI.RetTy == Args[i].Ty ||
10748                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10749                  CLI.RetTy->getPointerAddressSpace() ==
10750                      Args[i].Ty->getPointerAddressSpace())) &&
10751                RetTys.size() == NumValues && "unexpected use of 'returned'");
10752         // Before passing 'returned' to the target lowering code, ensure that
10753         // either the register MVT and the actual EVT are the same size or that
10754         // the return value and argument are extended in the same way; in these
10755         // cases it's safe to pass the argument register value unchanged as the
10756         // return register value (although it's at the target's option whether
10757         // to do so)
10758         // TODO: allow code generation to take advantage of partially preserved
10759         // registers rather than clobbering the entire register when the
10760         // parameter extension method is not compatible with the return
10761         // extension method
10762         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10763             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10764              CLI.RetZExt == Args[i].IsZExt))
10765           Flags.setReturned();
10766       }
10767 
10768       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10769                      CLI.CallConv, ExtendKind);
10770 
10771       for (unsigned j = 0; j != NumParts; ++j) {
10772         // if it isn't first piece, alignment must be 1
10773         // For scalable vectors the scalable part is currently handled
10774         // by individual targets, so we just use the known minimum size here.
10775         ISD::OutputArg MyFlags(
10776             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10777             i < CLI.NumFixedArgs, i,
10778             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10779         if (NumParts > 1 && j == 0)
10780           MyFlags.Flags.setSplit();
10781         else if (j != 0) {
10782           MyFlags.Flags.setOrigAlign(Align(1));
10783           if (j == NumParts - 1)
10784             MyFlags.Flags.setSplitEnd();
10785         }
10786 
10787         CLI.Outs.push_back(MyFlags);
10788         CLI.OutVals.push_back(Parts[j]);
10789       }
10790 
10791       if (NeedsRegBlock && Value == NumValues - 1)
10792         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10793     }
10794   }
10795 
10796   SmallVector<SDValue, 4> InVals;
10797   CLI.Chain = LowerCall(CLI, InVals);
10798 
10799   // Update CLI.InVals to use outside of this function.
10800   CLI.InVals = InVals;
10801 
10802   // Verify that the target's LowerCall behaved as expected.
10803   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
10804          "LowerCall didn't return a valid chain!");
10805   assert((!CLI.IsTailCall || InVals.empty()) &&
10806          "LowerCall emitted a return value for a tail call!");
10807   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
10808          "LowerCall didn't emit the correct number of values!");
10809 
10810   // For a tail call, the return value is merely live-out and there aren't
10811   // any nodes in the DAG representing it. Return a special value to
10812   // indicate that a tail call has been emitted and no more Instructions
10813   // should be processed in the current block.
10814   if (CLI.IsTailCall) {
10815     CLI.DAG.setRoot(CLI.Chain);
10816     return std::make_pair(SDValue(), SDValue());
10817   }
10818 
10819 #ifndef NDEBUG
10820   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
10821     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
10822     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
10823            "LowerCall emitted a value with the wrong type!");
10824   }
10825 #endif
10826 
10827   SmallVector<SDValue, 4> ReturnValues;
10828   if (!CanLowerReturn) {
10829     // The instruction result is the result of loading from the
10830     // hidden sret parameter.
10831     SmallVector<EVT, 1> PVTs;
10832     Type *PtrRetTy =
10833         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
10834 
10835     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
10836     assert(PVTs.size() == 1 && "Pointers should fit in one register");
10837     EVT PtrVT = PVTs[0];
10838 
10839     unsigned NumValues = RetTys.size();
10840     ReturnValues.resize(NumValues);
10841     SmallVector<SDValue, 4> Chains(NumValues);
10842 
10843     // An aggregate return value cannot wrap around the address space, so
10844     // offsets to its parts don't wrap either.
10845     SDNodeFlags Flags;
10846     Flags.setNoUnsignedWrap(true);
10847 
10848     MachineFunction &MF = CLI.DAG.getMachineFunction();
10849     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
10850     for (unsigned i = 0; i < NumValues; ++i) {
10851       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
10852                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
10853                                                         PtrVT), Flags);
10854       SDValue L = CLI.DAG.getLoad(
10855           RetTys[i], CLI.DL, CLI.Chain, Add,
10856           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
10857                                             DemoteStackIdx, Offsets[i]),
10858           HiddenSRetAlign);
10859       ReturnValues[i] = L;
10860       Chains[i] = L.getValue(1);
10861     }
10862 
10863     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
10864   } else {
10865     // Collect the legal value parts into potentially illegal values
10866     // that correspond to the original function's return values.
10867     std::optional<ISD::NodeType> AssertOp;
10868     if (CLI.RetSExt)
10869       AssertOp = ISD::AssertSext;
10870     else if (CLI.RetZExt)
10871       AssertOp = ISD::AssertZext;
10872     unsigned CurReg = 0;
10873     for (EVT VT : RetTys) {
10874       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10875                                                      CLI.CallConv, VT);
10876       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10877                                                        CLI.CallConv, VT);
10878 
10879       ReturnValues.push_back(getCopyFromParts(
10880           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
10881           CLI.Chain, CLI.CallConv, AssertOp));
10882       CurReg += NumRegs;
10883     }
10884 
10885     // For a function returning void, there is no return value. We can't create
10886     // such a node, so we just return a null return value in that case. In
10887     // that case, nothing will actually look at the value.
10888     if (ReturnValues.empty())
10889       return std::make_pair(SDValue(), CLI.Chain);
10890   }
10891 
10892   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
10893                                 CLI.DAG.getVTList(RetTys), ReturnValues);
10894   return std::make_pair(Res, CLI.Chain);
10895 }
10896 
10897 /// Places new result values for the node in Results (their number
10898 /// and types must exactly match those of the original return values of
10899 /// the node), or leaves Results empty, which indicates that the node is not
10900 /// to be custom lowered after all.
10901 void TargetLowering::LowerOperationWrapper(SDNode *N,
10902                                            SmallVectorImpl<SDValue> &Results,
10903                                            SelectionDAG &DAG) const {
10904   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
10905 
10906   if (!Res.getNode())
10907     return;
10908 
10909   // If the original node has one result, take the return value from
10910   // LowerOperation as is. It might not be result number 0.
10911   if (N->getNumValues() == 1) {
10912     Results.push_back(Res);
10913     return;
10914   }
10915 
10916   // If the original node has multiple results, then the return node should
10917   // have the same number of results.
10918   assert((N->getNumValues() == Res->getNumValues()) &&
10919       "Lowering returned the wrong number of results!");
10920 
10921   // Places new result values base on N result number.
10922   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
10923     Results.push_back(Res.getValue(I));
10924 }
10925 
10926 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
10927   llvm_unreachable("LowerOperation not implemented for this target!");
10928 }
10929 
10930 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
10931                                                      unsigned Reg,
10932                                                      ISD::NodeType ExtendType) {
10933   SDValue Op = getNonRegisterValue(V);
10934   assert((Op.getOpcode() != ISD::CopyFromReg ||
10935           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
10936          "Copy from a reg to the same reg!");
10937   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
10938 
10939   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10940   // If this is an InlineAsm we have to match the registers required, not the
10941   // notional registers required by the type.
10942 
10943   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
10944                    std::nullopt); // This is not an ABI copy.
10945   SDValue Chain = DAG.getEntryNode();
10946 
10947   if (ExtendType == ISD::ANY_EXTEND) {
10948     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
10949     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
10950       ExtendType = PreferredExtendIt->second;
10951   }
10952   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
10953   PendingExports.push_back(Chain);
10954 }
10955 
10956 #include "llvm/CodeGen/SelectionDAGISel.h"
10957 
10958 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
10959 /// entry block, return true.  This includes arguments used by switches, since
10960 /// the switch may expand into multiple basic blocks.
10961 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
10962   // With FastISel active, we may be splitting blocks, so force creation
10963   // of virtual registers for all non-dead arguments.
10964   if (FastISel)
10965     return A->use_empty();
10966 
10967   const BasicBlock &Entry = A->getParent()->front();
10968   for (const User *U : A->users())
10969     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
10970       return false;  // Use not in entry block.
10971 
10972   return true;
10973 }
10974 
10975 using ArgCopyElisionMapTy =
10976     DenseMap<const Argument *,
10977              std::pair<const AllocaInst *, const StoreInst *>>;
10978 
10979 /// Scan the entry block of the function in FuncInfo for arguments that look
10980 /// like copies into a local alloca. Record any copied arguments in
10981 /// ArgCopyElisionCandidates.
10982 static void
10983 findArgumentCopyElisionCandidates(const DataLayout &DL,
10984                                   FunctionLoweringInfo *FuncInfo,
10985                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
10986   // Record the state of every static alloca used in the entry block. Argument
10987   // allocas are all used in the entry block, so we need approximately as many
10988   // entries as we have arguments.
10989   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
10990   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
10991   unsigned NumArgs = FuncInfo->Fn->arg_size();
10992   StaticAllocas.reserve(NumArgs * 2);
10993 
10994   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
10995     if (!V)
10996       return nullptr;
10997     V = V->stripPointerCasts();
10998     const auto *AI = dyn_cast<AllocaInst>(V);
10999     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11000       return nullptr;
11001     auto Iter = StaticAllocas.insert({AI, Unknown});
11002     return &Iter.first->second;
11003   };
11004 
11005   // Look for stores of arguments to static allocas. Look through bitcasts and
11006   // GEPs to handle type coercions, as long as the alloca is fully initialized
11007   // by the store. Any non-store use of an alloca escapes it and any subsequent
11008   // unanalyzed store might write it.
11009   // FIXME: Handle structs initialized with multiple stores.
11010   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11011     // Look for stores, and handle non-store uses conservatively.
11012     const auto *SI = dyn_cast<StoreInst>(&I);
11013     if (!SI) {
11014       // We will look through cast uses, so ignore them completely.
11015       if (I.isCast())
11016         continue;
11017       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11018       // to allocas.
11019       if (I.isDebugOrPseudoInst())
11020         continue;
11021       // This is an unknown instruction. Assume it escapes or writes to all
11022       // static alloca operands.
11023       for (const Use &U : I.operands()) {
11024         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11025           *Info = StaticAllocaInfo::Clobbered;
11026       }
11027       continue;
11028     }
11029 
11030     // If the stored value is a static alloca, mark it as escaped.
11031     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11032       *Info = StaticAllocaInfo::Clobbered;
11033 
11034     // Check if the destination is a static alloca.
11035     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11036     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11037     if (!Info)
11038       continue;
11039     const AllocaInst *AI = cast<AllocaInst>(Dst);
11040 
11041     // Skip allocas that have been initialized or clobbered.
11042     if (*Info != StaticAllocaInfo::Unknown)
11043       continue;
11044 
11045     // Check if the stored value is an argument, and that this store fully
11046     // initializes the alloca.
11047     // If the argument type has padding bits we can't directly forward a pointer
11048     // as the upper bits may contain garbage.
11049     // Don't elide copies from the same argument twice.
11050     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11051     const auto *Arg = dyn_cast<Argument>(Val);
11052     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11053         Arg->getType()->isEmptyTy() ||
11054         DL.getTypeStoreSize(Arg->getType()) !=
11055             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11056         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11057         ArgCopyElisionCandidates.count(Arg)) {
11058       *Info = StaticAllocaInfo::Clobbered;
11059       continue;
11060     }
11061 
11062     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11063                       << '\n');
11064 
11065     // Mark this alloca and store for argument copy elision.
11066     *Info = StaticAllocaInfo::Elidable;
11067     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11068 
11069     // Stop scanning if we've seen all arguments. This will happen early in -O0
11070     // builds, which is useful, because -O0 builds have large entry blocks and
11071     // many allocas.
11072     if (ArgCopyElisionCandidates.size() == NumArgs)
11073       break;
11074   }
11075 }
11076 
11077 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11078 /// ArgVal is a load from a suitable fixed stack object.
11079 static void tryToElideArgumentCopy(
11080     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11081     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11082     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11083     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11084     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11085   // Check if this is a load from a fixed stack object.
11086   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11087   if (!LNode)
11088     return;
11089   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11090   if (!FINode)
11091     return;
11092 
11093   // Check that the fixed stack object is the right size and alignment.
11094   // Look at the alignment that the user wrote on the alloca instead of looking
11095   // at the stack object.
11096   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11097   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11098   const AllocaInst *AI = ArgCopyIter->second.first;
11099   int FixedIndex = FINode->getIndex();
11100   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11101   int OldIndex = AllocaIndex;
11102   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11103   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11104     LLVM_DEBUG(
11105         dbgs() << "  argument copy elision failed due to bad fixed stack "
11106                   "object size\n");
11107     return;
11108   }
11109   Align RequiredAlignment = AI->getAlign();
11110   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11111     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11112                          "greater than stack argument alignment ("
11113                       << DebugStr(RequiredAlignment) << " vs "
11114                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11115     return;
11116   }
11117 
11118   // Perform the elision. Delete the old stack object and replace its only use
11119   // in the variable info map. Mark the stack object as mutable.
11120   LLVM_DEBUG({
11121     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11122            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11123            << '\n';
11124   });
11125   MFI.RemoveStackObject(OldIndex);
11126   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11127   AllocaIndex = FixedIndex;
11128   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11129   for (SDValue ArgVal : ArgVals)
11130     Chains.push_back(ArgVal.getValue(1));
11131 
11132   // Avoid emitting code for the store implementing the copy.
11133   const StoreInst *SI = ArgCopyIter->second.second;
11134   ElidedArgCopyInstrs.insert(SI);
11135 
11136   // Check for uses of the argument again so that we can avoid exporting ArgVal
11137   // if it is't used by anything other than the store.
11138   for (const Value *U : Arg.users()) {
11139     if (U != SI) {
11140       ArgHasUses = true;
11141       break;
11142     }
11143   }
11144 }
11145 
11146 void SelectionDAGISel::LowerArguments(const Function &F) {
11147   SelectionDAG &DAG = SDB->DAG;
11148   SDLoc dl = SDB->getCurSDLoc();
11149   const DataLayout &DL = DAG.getDataLayout();
11150   SmallVector<ISD::InputArg, 16> Ins;
11151 
11152   // In Naked functions we aren't going to save any registers.
11153   if (F.hasFnAttribute(Attribute::Naked))
11154     return;
11155 
11156   if (!FuncInfo->CanLowerReturn) {
11157     // Put in an sret pointer parameter before all the other parameters.
11158     SmallVector<EVT, 1> ValueVTs;
11159     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11160                     PointerType::get(F.getContext(),
11161                                      DAG.getDataLayout().getAllocaAddrSpace()),
11162                     ValueVTs);
11163 
11164     // NOTE: Assuming that a pointer will never break down to more than one VT
11165     // or one register.
11166     ISD::ArgFlagsTy Flags;
11167     Flags.setSRet();
11168     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11169     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11170                          ISD::InputArg::NoArgIndex, 0);
11171     Ins.push_back(RetArg);
11172   }
11173 
11174   // Look for stores of arguments to static allocas. Mark such arguments with a
11175   // flag to ask the target to give us the memory location of that argument if
11176   // available.
11177   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11178   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11179                                     ArgCopyElisionCandidates);
11180 
11181   // Set up the incoming argument description vector.
11182   for (const Argument &Arg : F.args()) {
11183     unsigned ArgNo = Arg.getArgNo();
11184     SmallVector<EVT, 4> ValueVTs;
11185     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11186     bool isArgValueUsed = !Arg.use_empty();
11187     unsigned PartBase = 0;
11188     Type *FinalType = Arg.getType();
11189     if (Arg.hasAttribute(Attribute::ByVal))
11190       FinalType = Arg.getParamByValType();
11191     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11192         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11193     for (unsigned Value = 0, NumValues = ValueVTs.size();
11194          Value != NumValues; ++Value) {
11195       EVT VT = ValueVTs[Value];
11196       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11197       ISD::ArgFlagsTy Flags;
11198 
11199 
11200       if (Arg.getType()->isPointerTy()) {
11201         Flags.setPointer();
11202         Flags.setPointerAddrSpace(
11203             cast<PointerType>(Arg.getType())->getAddressSpace());
11204       }
11205       if (Arg.hasAttribute(Attribute::ZExt))
11206         Flags.setZExt();
11207       if (Arg.hasAttribute(Attribute::SExt))
11208         Flags.setSExt();
11209       if (Arg.hasAttribute(Attribute::InReg)) {
11210         // If we are using vectorcall calling convention, a structure that is
11211         // passed InReg - is surely an HVA
11212         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11213             isa<StructType>(Arg.getType())) {
11214           // The first value of a structure is marked
11215           if (0 == Value)
11216             Flags.setHvaStart();
11217           Flags.setHva();
11218         }
11219         // Set InReg Flag
11220         Flags.setInReg();
11221       }
11222       if (Arg.hasAttribute(Attribute::StructRet))
11223         Flags.setSRet();
11224       if (Arg.hasAttribute(Attribute::SwiftSelf))
11225         Flags.setSwiftSelf();
11226       if (Arg.hasAttribute(Attribute::SwiftAsync))
11227         Flags.setSwiftAsync();
11228       if (Arg.hasAttribute(Attribute::SwiftError))
11229         Flags.setSwiftError();
11230       if (Arg.hasAttribute(Attribute::ByVal))
11231         Flags.setByVal();
11232       if (Arg.hasAttribute(Attribute::ByRef))
11233         Flags.setByRef();
11234       if (Arg.hasAttribute(Attribute::InAlloca)) {
11235         Flags.setInAlloca();
11236         // Set the byval flag for CCAssignFn callbacks that don't know about
11237         // inalloca.  This way we can know how many bytes we should've allocated
11238         // and how many bytes a callee cleanup function will pop.  If we port
11239         // inalloca to more targets, we'll have to add custom inalloca handling
11240         // in the various CC lowering callbacks.
11241         Flags.setByVal();
11242       }
11243       if (Arg.hasAttribute(Attribute::Preallocated)) {
11244         Flags.setPreallocated();
11245         // Set the byval flag for CCAssignFn callbacks that don't know about
11246         // preallocated.  This way we can know how many bytes we should've
11247         // allocated and how many bytes a callee cleanup function will pop.  If
11248         // we port preallocated to more targets, we'll have to add custom
11249         // preallocated handling in the various CC lowering callbacks.
11250         Flags.setByVal();
11251       }
11252 
11253       // Certain targets (such as MIPS), may have a different ABI alignment
11254       // for a type depending on the context. Give the target a chance to
11255       // specify the alignment it wants.
11256       const Align OriginalAlignment(
11257           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11258       Flags.setOrigAlign(OriginalAlignment);
11259 
11260       Align MemAlign;
11261       Type *ArgMemTy = nullptr;
11262       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11263           Flags.isByRef()) {
11264         if (!ArgMemTy)
11265           ArgMemTy = Arg.getPointeeInMemoryValueType();
11266 
11267         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11268 
11269         // For in-memory arguments, size and alignment should be passed from FE.
11270         // BE will guess if this info is not there but there are cases it cannot
11271         // get right.
11272         if (auto ParamAlign = Arg.getParamStackAlign())
11273           MemAlign = *ParamAlign;
11274         else if ((ParamAlign = Arg.getParamAlign()))
11275           MemAlign = *ParamAlign;
11276         else
11277           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11278         if (Flags.isByRef())
11279           Flags.setByRefSize(MemSize);
11280         else
11281           Flags.setByValSize(MemSize);
11282       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11283         MemAlign = *ParamAlign;
11284       } else {
11285         MemAlign = OriginalAlignment;
11286       }
11287       Flags.setMemAlign(MemAlign);
11288 
11289       if (Arg.hasAttribute(Attribute::Nest))
11290         Flags.setNest();
11291       if (NeedsRegBlock)
11292         Flags.setInConsecutiveRegs();
11293       if (ArgCopyElisionCandidates.count(&Arg))
11294         Flags.setCopyElisionCandidate();
11295       if (Arg.hasAttribute(Attribute::Returned))
11296         Flags.setReturned();
11297 
11298       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11299           *CurDAG->getContext(), F.getCallingConv(), VT);
11300       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11301           *CurDAG->getContext(), F.getCallingConv(), VT);
11302       for (unsigned i = 0; i != NumRegs; ++i) {
11303         // For scalable vectors, use the minimum size; individual targets
11304         // are responsible for handling scalable vector arguments and
11305         // return values.
11306         ISD::InputArg MyFlags(
11307             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11308             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11309         if (NumRegs > 1 && i == 0)
11310           MyFlags.Flags.setSplit();
11311         // if it isn't first piece, alignment must be 1
11312         else if (i > 0) {
11313           MyFlags.Flags.setOrigAlign(Align(1));
11314           if (i == NumRegs - 1)
11315             MyFlags.Flags.setSplitEnd();
11316         }
11317         Ins.push_back(MyFlags);
11318       }
11319       if (NeedsRegBlock && Value == NumValues - 1)
11320         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11321       PartBase += VT.getStoreSize().getKnownMinValue();
11322     }
11323   }
11324 
11325   // Call the target to set up the argument values.
11326   SmallVector<SDValue, 8> InVals;
11327   SDValue NewRoot = TLI->LowerFormalArguments(
11328       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11329 
11330   // Verify that the target's LowerFormalArguments behaved as expected.
11331   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11332          "LowerFormalArguments didn't return a valid chain!");
11333   assert(InVals.size() == Ins.size() &&
11334          "LowerFormalArguments didn't emit the correct number of values!");
11335   LLVM_DEBUG({
11336     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11337       assert(InVals[i].getNode() &&
11338              "LowerFormalArguments emitted a null value!");
11339       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11340              "LowerFormalArguments emitted a value with the wrong type!");
11341     }
11342   });
11343 
11344   // Update the DAG with the new chain value resulting from argument lowering.
11345   DAG.setRoot(NewRoot);
11346 
11347   // Set up the argument values.
11348   unsigned i = 0;
11349   if (!FuncInfo->CanLowerReturn) {
11350     // Create a virtual register for the sret pointer, and put in a copy
11351     // from the sret argument into it.
11352     SmallVector<EVT, 1> ValueVTs;
11353     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11354                     PointerType::get(F.getContext(),
11355                                      DAG.getDataLayout().getAllocaAddrSpace()),
11356                     ValueVTs);
11357     MVT VT = ValueVTs[0].getSimpleVT();
11358     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11359     std::optional<ISD::NodeType> AssertOp;
11360     SDValue ArgValue =
11361         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11362                          F.getCallingConv(), AssertOp);
11363 
11364     MachineFunction& MF = SDB->DAG.getMachineFunction();
11365     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11366     Register SRetReg =
11367         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11368     FuncInfo->DemoteRegister = SRetReg;
11369     NewRoot =
11370         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11371     DAG.setRoot(NewRoot);
11372 
11373     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11374     ++i;
11375   }
11376 
11377   SmallVector<SDValue, 4> Chains;
11378   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11379   for (const Argument &Arg : F.args()) {
11380     SmallVector<SDValue, 4> ArgValues;
11381     SmallVector<EVT, 4> ValueVTs;
11382     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11383     unsigned NumValues = ValueVTs.size();
11384     if (NumValues == 0)
11385       continue;
11386 
11387     bool ArgHasUses = !Arg.use_empty();
11388 
11389     // Elide the copying store if the target loaded this argument from a
11390     // suitable fixed stack object.
11391     if (Ins[i].Flags.isCopyElisionCandidate()) {
11392       unsigned NumParts = 0;
11393       for (EVT VT : ValueVTs)
11394         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11395                                                        F.getCallingConv(), VT);
11396 
11397       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11398                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11399                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11400     }
11401 
11402     // If this argument is unused then remember its value. It is used to generate
11403     // debugging information.
11404     bool isSwiftErrorArg =
11405         TLI->supportSwiftError() &&
11406         Arg.hasAttribute(Attribute::SwiftError);
11407     if (!ArgHasUses && !isSwiftErrorArg) {
11408       SDB->setUnusedArgValue(&Arg, InVals[i]);
11409 
11410       // Also remember any frame index for use in FastISel.
11411       if (FrameIndexSDNode *FI =
11412           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11413         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11414     }
11415 
11416     for (unsigned Val = 0; Val != NumValues; ++Val) {
11417       EVT VT = ValueVTs[Val];
11418       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11419                                                       F.getCallingConv(), VT);
11420       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11421           *CurDAG->getContext(), F.getCallingConv(), VT);
11422 
11423       // Even an apparent 'unused' swifterror argument needs to be returned. So
11424       // we do generate a copy for it that can be used on return from the
11425       // function.
11426       if (ArgHasUses || isSwiftErrorArg) {
11427         std::optional<ISD::NodeType> AssertOp;
11428         if (Arg.hasAttribute(Attribute::SExt))
11429           AssertOp = ISD::AssertSext;
11430         else if (Arg.hasAttribute(Attribute::ZExt))
11431           AssertOp = ISD::AssertZext;
11432 
11433         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11434                                              PartVT, VT, nullptr, NewRoot,
11435                                              F.getCallingConv(), AssertOp));
11436       }
11437 
11438       i += NumParts;
11439     }
11440 
11441     // We don't need to do anything else for unused arguments.
11442     if (ArgValues.empty())
11443       continue;
11444 
11445     // Note down frame index.
11446     if (FrameIndexSDNode *FI =
11447         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11448       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11449 
11450     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11451                                      SDB->getCurSDLoc());
11452 
11453     SDB->setValue(&Arg, Res);
11454     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11455       // We want to associate the argument with the frame index, among
11456       // involved operands, that correspond to the lowest address. The
11457       // getCopyFromParts function, called earlier, is swapping the order of
11458       // the operands to BUILD_PAIR depending on endianness. The result of
11459       // that swapping is that the least significant bits of the argument will
11460       // be in the first operand of the BUILD_PAIR node, and the most
11461       // significant bits will be in the second operand.
11462       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11463       if (LoadSDNode *LNode =
11464           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11465         if (FrameIndexSDNode *FI =
11466             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11467           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11468     }
11469 
11470     // Analyses past this point are naive and don't expect an assertion.
11471     if (Res.getOpcode() == ISD::AssertZext)
11472       Res = Res.getOperand(0);
11473 
11474     // Update the SwiftErrorVRegDefMap.
11475     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11476       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11477       if (Register::isVirtualRegister(Reg))
11478         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11479                                    Reg);
11480     }
11481 
11482     // If this argument is live outside of the entry block, insert a copy from
11483     // wherever we got it to the vreg that other BB's will reference it as.
11484     if (Res.getOpcode() == ISD::CopyFromReg) {
11485       // If we can, though, try to skip creating an unnecessary vreg.
11486       // FIXME: This isn't very clean... it would be nice to make this more
11487       // general.
11488       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11489       if (Register::isVirtualRegister(Reg)) {
11490         FuncInfo->ValueMap[&Arg] = Reg;
11491         continue;
11492       }
11493     }
11494     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11495       FuncInfo->InitializeRegForValue(&Arg);
11496       SDB->CopyToExportRegsIfNeeded(&Arg);
11497     }
11498   }
11499 
11500   if (!Chains.empty()) {
11501     Chains.push_back(NewRoot);
11502     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11503   }
11504 
11505   DAG.setRoot(NewRoot);
11506 
11507   assert(i == InVals.size() && "Argument register count mismatch!");
11508 
11509   // If any argument copy elisions occurred and we have debug info, update the
11510   // stale frame indices used in the dbg.declare variable info table.
11511   if (!ArgCopyElisionFrameIndexMap.empty()) {
11512     for (MachineFunction::VariableDbgInfo &VI :
11513          MF->getInStackSlotVariableDbgInfo()) {
11514       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11515       if (I != ArgCopyElisionFrameIndexMap.end())
11516         VI.updateStackSlot(I->second);
11517     }
11518   }
11519 
11520   // Finally, if the target has anything special to do, allow it to do so.
11521   emitFunctionEntryCode();
11522 }
11523 
11524 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11525 /// ensure constants are generated when needed.  Remember the virtual registers
11526 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11527 /// directly add them, because expansion might result in multiple MBB's for one
11528 /// BB.  As such, the start of the BB might correspond to a different MBB than
11529 /// the end.
11530 void
11531 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11532   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11533 
11534   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11535 
11536   // Check PHI nodes in successors that expect a value to be available from this
11537   // block.
11538   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11539     if (!isa<PHINode>(SuccBB->begin())) continue;
11540     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11541 
11542     // If this terminator has multiple identical successors (common for
11543     // switches), only handle each succ once.
11544     if (!SuccsHandled.insert(SuccMBB).second)
11545       continue;
11546 
11547     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11548 
11549     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11550     // nodes and Machine PHI nodes, but the incoming operands have not been
11551     // emitted yet.
11552     for (const PHINode &PN : SuccBB->phis()) {
11553       // Ignore dead phi's.
11554       if (PN.use_empty())
11555         continue;
11556 
11557       // Skip empty types
11558       if (PN.getType()->isEmptyTy())
11559         continue;
11560 
11561       unsigned Reg;
11562       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11563 
11564       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11565         unsigned &RegOut = ConstantsOut[C];
11566         if (RegOut == 0) {
11567           RegOut = FuncInfo.CreateRegs(C);
11568           // We need to zero/sign extend ConstantInt phi operands to match
11569           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11570           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11571           if (auto *CI = dyn_cast<ConstantInt>(C))
11572             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11573                                                     : ISD::ZERO_EXTEND;
11574           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11575         }
11576         Reg = RegOut;
11577       } else {
11578         DenseMap<const Value *, Register>::iterator I =
11579           FuncInfo.ValueMap.find(PHIOp);
11580         if (I != FuncInfo.ValueMap.end())
11581           Reg = I->second;
11582         else {
11583           assert(isa<AllocaInst>(PHIOp) &&
11584                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11585                  "Didn't codegen value into a register!??");
11586           Reg = FuncInfo.CreateRegs(PHIOp);
11587           CopyValueToVirtualRegister(PHIOp, Reg);
11588         }
11589       }
11590 
11591       // Remember that this register needs to added to the machine PHI node as
11592       // the input for this MBB.
11593       SmallVector<EVT, 4> ValueVTs;
11594       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11595       for (EVT VT : ValueVTs) {
11596         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11597         for (unsigned i = 0; i != NumRegisters; ++i)
11598           FuncInfo.PHINodesToUpdate.push_back(
11599               std::make_pair(&*MBBI++, Reg + i));
11600         Reg += NumRegisters;
11601       }
11602     }
11603   }
11604 
11605   ConstantsOut.clear();
11606 }
11607 
11608 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11609   MachineFunction::iterator I(MBB);
11610   if (++I == FuncInfo.MF->end())
11611     return nullptr;
11612   return &*I;
11613 }
11614 
11615 /// During lowering new call nodes can be created (such as memset, etc.).
11616 /// Those will become new roots of the current DAG, but complications arise
11617 /// when they are tail calls. In such cases, the call lowering will update
11618 /// the root, but the builder still needs to know that a tail call has been
11619 /// lowered in order to avoid generating an additional return.
11620 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11621   // If the node is null, we do have a tail call.
11622   if (MaybeTC.getNode() != nullptr)
11623     DAG.setRoot(MaybeTC);
11624   else
11625     HasTailCall = true;
11626 }
11627 
11628 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11629                                         MachineBasicBlock *SwitchMBB,
11630                                         MachineBasicBlock *DefaultMBB) {
11631   MachineFunction *CurMF = FuncInfo.MF;
11632   MachineBasicBlock *NextMBB = nullptr;
11633   MachineFunction::iterator BBI(W.MBB);
11634   if (++BBI != FuncInfo.MF->end())
11635     NextMBB = &*BBI;
11636 
11637   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11638 
11639   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11640 
11641   if (Size == 2 && W.MBB == SwitchMBB) {
11642     // If any two of the cases has the same destination, and if one value
11643     // is the same as the other, but has one bit unset that the other has set,
11644     // use bit manipulation to do two compares at once.  For example:
11645     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11646     // TODO: This could be extended to merge any 2 cases in switches with 3
11647     // cases.
11648     // TODO: Handle cases where W.CaseBB != SwitchBB.
11649     CaseCluster &Small = *W.FirstCluster;
11650     CaseCluster &Big = *W.LastCluster;
11651 
11652     if (Small.Low == Small.High && Big.Low == Big.High &&
11653         Small.MBB == Big.MBB) {
11654       const APInt &SmallValue = Small.Low->getValue();
11655       const APInt &BigValue = Big.Low->getValue();
11656 
11657       // Check that there is only one bit different.
11658       APInt CommonBit = BigValue ^ SmallValue;
11659       if (CommonBit.isPowerOf2()) {
11660         SDValue CondLHS = getValue(Cond);
11661         EVT VT = CondLHS.getValueType();
11662         SDLoc DL = getCurSDLoc();
11663 
11664         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11665                                  DAG.getConstant(CommonBit, DL, VT));
11666         SDValue Cond = DAG.getSetCC(
11667             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11668             ISD::SETEQ);
11669 
11670         // Update successor info.
11671         // Both Small and Big will jump to Small.BB, so we sum up the
11672         // probabilities.
11673         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11674         if (BPI)
11675           addSuccessorWithProb(
11676               SwitchMBB, DefaultMBB,
11677               // The default destination is the first successor in IR.
11678               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11679         else
11680           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11681 
11682         // Insert the true branch.
11683         SDValue BrCond =
11684             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11685                         DAG.getBasicBlock(Small.MBB));
11686         // Insert the false branch.
11687         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11688                              DAG.getBasicBlock(DefaultMBB));
11689 
11690         DAG.setRoot(BrCond);
11691         return;
11692       }
11693     }
11694   }
11695 
11696   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11697     // Here, we order cases by probability so the most likely case will be
11698     // checked first. However, two clusters can have the same probability in
11699     // which case their relative ordering is non-deterministic. So we use Low
11700     // as a tie-breaker as clusters are guaranteed to never overlap.
11701     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11702                [](const CaseCluster &a, const CaseCluster &b) {
11703       return a.Prob != b.Prob ?
11704              a.Prob > b.Prob :
11705              a.Low->getValue().slt(b.Low->getValue());
11706     });
11707 
11708     // Rearrange the case blocks so that the last one falls through if possible
11709     // without changing the order of probabilities.
11710     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11711       --I;
11712       if (I->Prob > W.LastCluster->Prob)
11713         break;
11714       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11715         std::swap(*I, *W.LastCluster);
11716         break;
11717       }
11718     }
11719   }
11720 
11721   // Compute total probability.
11722   BranchProbability DefaultProb = W.DefaultProb;
11723   BranchProbability UnhandledProbs = DefaultProb;
11724   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11725     UnhandledProbs += I->Prob;
11726 
11727   MachineBasicBlock *CurMBB = W.MBB;
11728   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11729     bool FallthroughUnreachable = false;
11730     MachineBasicBlock *Fallthrough;
11731     if (I == W.LastCluster) {
11732       // For the last cluster, fall through to the default destination.
11733       Fallthrough = DefaultMBB;
11734       FallthroughUnreachable = isa<UnreachableInst>(
11735           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11736     } else {
11737       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11738       CurMF->insert(BBI, Fallthrough);
11739       // Put Cond in a virtual register to make it available from the new blocks.
11740       ExportFromCurrentBlock(Cond);
11741     }
11742     UnhandledProbs -= I->Prob;
11743 
11744     switch (I->Kind) {
11745       case CC_JumpTable: {
11746         // FIXME: Optimize away range check based on pivot comparisons.
11747         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11748         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11749 
11750         // The jump block hasn't been inserted yet; insert it here.
11751         MachineBasicBlock *JumpMBB = JT->MBB;
11752         CurMF->insert(BBI, JumpMBB);
11753 
11754         auto JumpProb = I->Prob;
11755         auto FallthroughProb = UnhandledProbs;
11756 
11757         // If the default statement is a target of the jump table, we evenly
11758         // distribute the default probability to successors of CurMBB. Also
11759         // update the probability on the edge from JumpMBB to Fallthrough.
11760         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11761                                               SE = JumpMBB->succ_end();
11762              SI != SE; ++SI) {
11763           if (*SI == DefaultMBB) {
11764             JumpProb += DefaultProb / 2;
11765             FallthroughProb -= DefaultProb / 2;
11766             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11767             JumpMBB->normalizeSuccProbs();
11768             break;
11769           }
11770         }
11771 
11772         // If the default clause is unreachable, propagate that knowledge into
11773         // JTH->FallthroughUnreachable which will use it to suppress the range
11774         // check.
11775         //
11776         // However, don't do this if we're doing branch target enforcement,
11777         // because a table branch _without_ a range check can be a tempting JOP
11778         // gadget - out-of-bounds inputs that are impossible in correct
11779         // execution become possible again if an attacker can influence the
11780         // control flow. So if an attacker doesn't already have a BTI bypass
11781         // available, we don't want them to be able to get one out of this
11782         // table branch.
11783         if (FallthroughUnreachable) {
11784           Function &CurFunc = CurMF->getFunction();
11785           bool HasBranchTargetEnforcement = false;
11786           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11787             HasBranchTargetEnforcement =
11788                 CurFunc.getFnAttribute("branch-target-enforcement")
11789                     .getValueAsBool();
11790           } else {
11791             HasBranchTargetEnforcement =
11792                 CurMF->getMMI().getModule()->getModuleFlag(
11793                     "branch-target-enforcement");
11794           }
11795           if (!HasBranchTargetEnforcement)
11796             JTH->FallthroughUnreachable = true;
11797         }
11798 
11799         if (!JTH->FallthroughUnreachable)
11800           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
11801         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
11802         CurMBB->normalizeSuccProbs();
11803 
11804         // The jump table header will be inserted in our current block, do the
11805         // range check, and fall through to our fallthrough block.
11806         JTH->HeaderBB = CurMBB;
11807         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
11808 
11809         // If we're in the right place, emit the jump table header right now.
11810         if (CurMBB == SwitchMBB) {
11811           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
11812           JTH->Emitted = true;
11813         }
11814         break;
11815       }
11816       case CC_BitTests: {
11817         // FIXME: Optimize away range check based on pivot comparisons.
11818         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
11819 
11820         // The bit test blocks haven't been inserted yet; insert them here.
11821         for (BitTestCase &BTC : BTB->Cases)
11822           CurMF->insert(BBI, BTC.ThisBB);
11823 
11824         // Fill in fields of the BitTestBlock.
11825         BTB->Parent = CurMBB;
11826         BTB->Default = Fallthrough;
11827 
11828         BTB->DefaultProb = UnhandledProbs;
11829         // If the cases in bit test don't form a contiguous range, we evenly
11830         // distribute the probability on the edge to Fallthrough to two
11831         // successors of CurMBB.
11832         if (!BTB->ContiguousRange) {
11833           BTB->Prob += DefaultProb / 2;
11834           BTB->DefaultProb -= DefaultProb / 2;
11835         }
11836 
11837         if (FallthroughUnreachable)
11838           BTB->FallthroughUnreachable = true;
11839 
11840         // If we're in the right place, emit the bit test header right now.
11841         if (CurMBB == SwitchMBB) {
11842           visitBitTestHeader(*BTB, SwitchMBB);
11843           BTB->Emitted = true;
11844         }
11845         break;
11846       }
11847       case CC_Range: {
11848         const Value *RHS, *LHS, *MHS;
11849         ISD::CondCode CC;
11850         if (I->Low == I->High) {
11851           // Check Cond == I->Low.
11852           CC = ISD::SETEQ;
11853           LHS = Cond;
11854           RHS=I->Low;
11855           MHS = nullptr;
11856         } else {
11857           // Check I->Low <= Cond <= I->High.
11858           CC = ISD::SETLE;
11859           LHS = I->Low;
11860           MHS = Cond;
11861           RHS = I->High;
11862         }
11863 
11864         // If Fallthrough is unreachable, fold away the comparison.
11865         if (FallthroughUnreachable)
11866           CC = ISD::SETTRUE;
11867 
11868         // The false probability is the sum of all unhandled cases.
11869         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
11870                      getCurSDLoc(), I->Prob, UnhandledProbs);
11871 
11872         if (CurMBB == SwitchMBB)
11873           visitSwitchCase(CB, SwitchMBB);
11874         else
11875           SL->SwitchCases.push_back(CB);
11876 
11877         break;
11878       }
11879     }
11880     CurMBB = Fallthrough;
11881   }
11882 }
11883 
11884 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
11885                                         const SwitchWorkListItem &W,
11886                                         Value *Cond,
11887                                         MachineBasicBlock *SwitchMBB) {
11888   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
11889          "Clusters not sorted?");
11890   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
11891 
11892   auto [LastLeft, FirstRight, LeftProb, RightProb] =
11893       SL->computeSplitWorkItemInfo(W);
11894 
11895   // Use the first element on the right as pivot since we will make less-than
11896   // comparisons against it.
11897   CaseClusterIt PivotCluster = FirstRight;
11898   assert(PivotCluster > W.FirstCluster);
11899   assert(PivotCluster <= W.LastCluster);
11900 
11901   CaseClusterIt FirstLeft = W.FirstCluster;
11902   CaseClusterIt LastRight = W.LastCluster;
11903 
11904   const ConstantInt *Pivot = PivotCluster->Low;
11905 
11906   // New blocks will be inserted immediately after the current one.
11907   MachineFunction::iterator BBI(W.MBB);
11908   ++BBI;
11909 
11910   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
11911   // we can branch to its destination directly if it's squeezed exactly in
11912   // between the known lower bound and Pivot - 1.
11913   MachineBasicBlock *LeftMBB;
11914   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
11915       FirstLeft->Low == W.GE &&
11916       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
11917     LeftMBB = FirstLeft->MBB;
11918   } else {
11919     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11920     FuncInfo.MF->insert(BBI, LeftMBB);
11921     WorkList.push_back(
11922         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
11923     // Put Cond in a virtual register to make it available from the new blocks.
11924     ExportFromCurrentBlock(Cond);
11925   }
11926 
11927   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
11928   // single cluster, RHS.Low == Pivot, and we can branch to its destination
11929   // directly if RHS.High equals the current upper bound.
11930   MachineBasicBlock *RightMBB;
11931   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
11932       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
11933     RightMBB = FirstRight->MBB;
11934   } else {
11935     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
11936     FuncInfo.MF->insert(BBI, RightMBB);
11937     WorkList.push_back(
11938         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
11939     // Put Cond in a virtual register to make it available from the new blocks.
11940     ExportFromCurrentBlock(Cond);
11941   }
11942 
11943   // Create the CaseBlock record that will be used to lower the branch.
11944   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
11945                getCurSDLoc(), LeftProb, RightProb);
11946 
11947   if (W.MBB == SwitchMBB)
11948     visitSwitchCase(CB, SwitchMBB);
11949   else
11950     SL->SwitchCases.push_back(CB);
11951 }
11952 
11953 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
11954 // from the swith statement.
11955 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
11956                                             BranchProbability PeeledCaseProb) {
11957   if (PeeledCaseProb == BranchProbability::getOne())
11958     return BranchProbability::getZero();
11959   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
11960 
11961   uint32_t Numerator = CaseProb.getNumerator();
11962   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
11963   return BranchProbability(Numerator, std::max(Numerator, Denominator));
11964 }
11965 
11966 // Try to peel the top probability case if it exceeds the threshold.
11967 // Return current MachineBasicBlock for the switch statement if the peeling
11968 // does not occur.
11969 // If the peeling is performed, return the newly created MachineBasicBlock
11970 // for the peeled switch statement. Also update Clusters to remove the peeled
11971 // case. PeeledCaseProb is the BranchProbability for the peeled case.
11972 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
11973     const SwitchInst &SI, CaseClusterVector &Clusters,
11974     BranchProbability &PeeledCaseProb) {
11975   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
11976   // Don't perform if there is only one cluster or optimizing for size.
11977   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
11978       TM.getOptLevel() == CodeGenOptLevel::None ||
11979       SwitchMBB->getParent()->getFunction().hasMinSize())
11980     return SwitchMBB;
11981 
11982   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
11983   unsigned PeeledCaseIndex = 0;
11984   bool SwitchPeeled = false;
11985   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
11986     CaseCluster &CC = Clusters[Index];
11987     if (CC.Prob < TopCaseProb)
11988       continue;
11989     TopCaseProb = CC.Prob;
11990     PeeledCaseIndex = Index;
11991     SwitchPeeled = true;
11992   }
11993   if (!SwitchPeeled)
11994     return SwitchMBB;
11995 
11996   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
11997                     << TopCaseProb << "\n");
11998 
11999   // Record the MBB for the peeled switch statement.
12000   MachineFunction::iterator BBI(SwitchMBB);
12001   ++BBI;
12002   MachineBasicBlock *PeeledSwitchMBB =
12003       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12004   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12005 
12006   ExportFromCurrentBlock(SI.getCondition());
12007   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12008   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12009                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12010   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12011 
12012   Clusters.erase(PeeledCaseIt);
12013   for (CaseCluster &CC : Clusters) {
12014     LLVM_DEBUG(
12015         dbgs() << "Scale the probablity for one cluster, before scaling: "
12016                << CC.Prob << "\n");
12017     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12018     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12019   }
12020   PeeledCaseProb = TopCaseProb;
12021   return PeeledSwitchMBB;
12022 }
12023 
12024 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12025   // Extract cases from the switch.
12026   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12027   CaseClusterVector Clusters;
12028   Clusters.reserve(SI.getNumCases());
12029   for (auto I : SI.cases()) {
12030     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
12031     const ConstantInt *CaseVal = I.getCaseValue();
12032     BranchProbability Prob =
12033         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12034             : BranchProbability(1, SI.getNumCases() + 1);
12035     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12036   }
12037 
12038   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
12039 
12040   // Cluster adjacent cases with the same destination. We do this at all
12041   // optimization levels because it's cheap to do and will make codegen faster
12042   // if there are many clusters.
12043   sortAndRangeify(Clusters);
12044 
12045   // The branch probablity of the peeled case.
12046   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12047   MachineBasicBlock *PeeledSwitchMBB =
12048       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12049 
12050   // If there is only the default destination, jump there directly.
12051   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12052   if (Clusters.empty()) {
12053     assert(PeeledSwitchMBB == SwitchMBB);
12054     SwitchMBB->addSuccessor(DefaultMBB);
12055     if (DefaultMBB != NextBlock(SwitchMBB)) {
12056       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12057                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12058     }
12059     return;
12060   }
12061 
12062   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12063                      DAG.getBFI());
12064   SL->findBitTestClusters(Clusters, &SI);
12065 
12066   LLVM_DEBUG({
12067     dbgs() << "Case clusters: ";
12068     for (const CaseCluster &C : Clusters) {
12069       if (C.Kind == CC_JumpTable)
12070         dbgs() << "JT:";
12071       if (C.Kind == CC_BitTests)
12072         dbgs() << "BT:";
12073 
12074       C.Low->getValue().print(dbgs(), true);
12075       if (C.Low != C.High) {
12076         dbgs() << '-';
12077         C.High->getValue().print(dbgs(), true);
12078       }
12079       dbgs() << ' ';
12080     }
12081     dbgs() << '\n';
12082   });
12083 
12084   assert(!Clusters.empty());
12085   SwitchWorkList WorkList;
12086   CaseClusterIt First = Clusters.begin();
12087   CaseClusterIt Last = Clusters.end() - 1;
12088   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12089   // Scale the branchprobability for DefaultMBB if the peel occurs and
12090   // DefaultMBB is not replaced.
12091   if (PeeledCaseProb != BranchProbability::getZero() &&
12092       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
12093     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12094   WorkList.push_back(
12095       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12096 
12097   while (!WorkList.empty()) {
12098     SwitchWorkListItem W = WorkList.pop_back_val();
12099     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12100 
12101     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12102         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12103       // For optimized builds, lower large range as a balanced binary tree.
12104       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12105       continue;
12106     }
12107 
12108     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12109   }
12110 }
12111 
12112 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12114   auto DL = getCurSDLoc();
12115   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12116   setValue(&I, DAG.getStepVector(DL, ResultVT));
12117 }
12118 
12119 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12120   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12121   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12122 
12123   SDLoc DL = getCurSDLoc();
12124   SDValue V = getValue(I.getOperand(0));
12125   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12126 
12127   if (VT.isScalableVector()) {
12128     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12129     return;
12130   }
12131 
12132   // Use VECTOR_SHUFFLE for the fixed-length vector
12133   // to maintain existing behavior.
12134   SmallVector<int, 8> Mask;
12135   unsigned NumElts = VT.getVectorMinNumElements();
12136   for (unsigned i = 0; i != NumElts; ++i)
12137     Mask.push_back(NumElts - 1 - i);
12138 
12139   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12140 }
12141 
12142 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12143   auto DL = getCurSDLoc();
12144   SDValue InVec = getValue(I.getOperand(0));
12145   EVT OutVT =
12146       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12147 
12148   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12149 
12150   // ISD Node needs the input vectors split into two equal parts
12151   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12152                            DAG.getVectorIdxConstant(0, DL));
12153   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12154                            DAG.getVectorIdxConstant(OutNumElts, DL));
12155 
12156   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12157   // legalisation and combines.
12158   if (OutVT.isFixedLengthVector()) {
12159     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12160                                         createStrideMask(0, 2, OutNumElts));
12161     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12162                                        createStrideMask(1, 2, OutNumElts));
12163     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12164     setValue(&I, Res);
12165     return;
12166   }
12167 
12168   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12169                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12170   setValue(&I, Res);
12171 }
12172 
12173 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12174   auto DL = getCurSDLoc();
12175   EVT InVT = getValue(I.getOperand(0)).getValueType();
12176   SDValue InVec0 = getValue(I.getOperand(0));
12177   SDValue InVec1 = getValue(I.getOperand(1));
12178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12179   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12180 
12181   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12182   // legalisation and combines.
12183   if (OutVT.isFixedLengthVector()) {
12184     unsigned NumElts = InVT.getVectorMinNumElements();
12185     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12186     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12187                                       createInterleaveMask(NumElts, 2)));
12188     return;
12189   }
12190 
12191   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12192                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12193   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12194                     Res.getValue(1));
12195   setValue(&I, Res);
12196 }
12197 
12198 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12199   SmallVector<EVT, 4> ValueVTs;
12200   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12201                   ValueVTs);
12202   unsigned NumValues = ValueVTs.size();
12203   if (NumValues == 0) return;
12204 
12205   SmallVector<SDValue, 4> Values(NumValues);
12206   SDValue Op = getValue(I.getOperand(0));
12207 
12208   for (unsigned i = 0; i != NumValues; ++i)
12209     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12210                             SDValue(Op.getNode(), Op.getResNo() + i));
12211 
12212   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12213                            DAG.getVTList(ValueVTs), Values));
12214 }
12215 
12216 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12217   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12218   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12219 
12220   SDLoc DL = getCurSDLoc();
12221   SDValue V1 = getValue(I.getOperand(0));
12222   SDValue V2 = getValue(I.getOperand(1));
12223   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12224 
12225   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12226   if (VT.isScalableVector()) {
12227     MVT IdxVT = TLI.getVectorIdxTy(DAG.getDataLayout());
12228     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12229                              DAG.getConstant(Imm, DL, IdxVT)));
12230     return;
12231   }
12232 
12233   unsigned NumElts = VT.getVectorNumElements();
12234 
12235   uint64_t Idx = (NumElts + Imm) % NumElts;
12236 
12237   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12238   SmallVector<int, 8> Mask;
12239   for (unsigned i = 0; i < NumElts; ++i)
12240     Mask.push_back(Idx + i);
12241   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12242 }
12243 
12244 // Consider the following MIR after SelectionDAG, which produces output in
12245 // phyregs in the first case or virtregs in the second case.
12246 //
12247 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12248 // %5:gr32 = COPY $ebx
12249 // %6:gr32 = COPY $edx
12250 // %1:gr32 = COPY %6:gr32
12251 // %0:gr32 = COPY %5:gr32
12252 //
12253 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12254 // %1:gr32 = COPY %6:gr32
12255 // %0:gr32 = COPY %5:gr32
12256 //
12257 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12258 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12259 //
12260 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12261 // to a single virtreg (such as %0). The remaining outputs monotonically
12262 // increase in virtreg number from there. If a callbr has no outputs, then it
12263 // should not have a corresponding callbr landingpad; in fact, the callbr
12264 // landingpad would not even be able to refer to such a callbr.
12265 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12266   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12267   // There is definitely at least one copy.
12268   assert(MI->getOpcode() == TargetOpcode::COPY &&
12269          "start of copy chain MUST be COPY");
12270   Reg = MI->getOperand(1).getReg();
12271   MI = MRI.def_begin(Reg)->getParent();
12272   // There may be an optional second copy.
12273   if (MI->getOpcode() == TargetOpcode::COPY) {
12274     assert(Reg.isVirtual() && "expected COPY of virtual register");
12275     Reg = MI->getOperand(1).getReg();
12276     assert(Reg.isPhysical() && "expected COPY of physical register");
12277     MI = MRI.def_begin(Reg)->getParent();
12278   }
12279   // The start of the chain must be an INLINEASM_BR.
12280   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12281          "end of copy chain MUST be INLINEASM_BR");
12282   return Reg;
12283 }
12284 
12285 // We must do this walk rather than the simpler
12286 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12287 // otherwise we will end up with copies of virtregs only valid along direct
12288 // edges.
12289 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12290   SmallVector<EVT, 8> ResultVTs;
12291   SmallVector<SDValue, 8> ResultValues;
12292   const auto *CBR =
12293       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12294 
12295   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12296   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12297   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12298 
12299   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12300   SDValue Chain = DAG.getRoot();
12301 
12302   // Re-parse the asm constraints string.
12303   TargetLowering::AsmOperandInfoVector TargetConstraints =
12304       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12305   for (auto &T : TargetConstraints) {
12306     SDISelAsmOperandInfo OpInfo(T);
12307     if (OpInfo.Type != InlineAsm::isOutput)
12308       continue;
12309 
12310     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12311     // individual constraint.
12312     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12313 
12314     switch (OpInfo.ConstraintType) {
12315     case TargetLowering::C_Register:
12316     case TargetLowering::C_RegisterClass: {
12317       // Fill in OpInfo.AssignedRegs.Regs.
12318       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12319 
12320       // getRegistersForValue may produce 1 to many registers based on whether
12321       // the OpInfo.ConstraintVT is legal on the target or not.
12322       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
12323         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12324         if (Register::isPhysicalRegister(OriginalDef))
12325           FuncInfo.MBB->addLiveIn(OriginalDef);
12326         // Update the assigned registers to use the original defs.
12327         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
12328       }
12329 
12330       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12331           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12332       ResultValues.push_back(V);
12333       ResultVTs.push_back(OpInfo.ConstraintVT);
12334       break;
12335     }
12336     case TargetLowering::C_Other: {
12337       SDValue Flag;
12338       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12339                                                   OpInfo, DAG);
12340       ++InitialDef;
12341       ResultValues.push_back(V);
12342       ResultVTs.push_back(OpInfo.ConstraintVT);
12343       break;
12344     }
12345     default:
12346       break;
12347     }
12348   }
12349   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12350                           DAG.getVTList(ResultVTs), ResultValues);
12351   setValue(&I, V);
12352 }
12353