xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 89881480030f48f83af668175b70a9798edca2fb)
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/MemoryModelRelaxationAnnotations.h"
84 #include "llvm/IR/Metadata.h"
85 #include "llvm/IR/Module.h"
86 #include "llvm/IR/Operator.h"
87 #include "llvm/IR/PatternMatch.h"
88 #include "llvm/IR/Statepoint.h"
89 #include "llvm/IR/Type.h"
90 #include "llvm/IR/User.h"
91 #include "llvm/IR/Value.h"
92 #include "llvm/MC/MCContext.h"
93 #include "llvm/Support/AtomicOrdering.h"
94 #include "llvm/Support/Casting.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/InstructionCost.h"
99 #include "llvm/Support/MathExtras.h"
100 #include "llvm/Support/raw_ostream.h"
101 #include "llvm/Target/TargetIntrinsicInfo.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include "llvm/TargetParser/Triple.h"
105 #include "llvm/Transforms/Utils/Local.h"
106 #include <cstddef>
107 #include <iterator>
108 #include <limits>
109 #include <optional>
110 #include <tuple>
111 
112 using namespace llvm;
113 using namespace PatternMatch;
114 using namespace SwitchCG;
115 
116 #define DEBUG_TYPE "isel"
117 
118 /// LimitFloatPrecision - Generate low-precision inline sequences for
119 /// some float libcalls (6, 8 or 12 bits).
120 static unsigned LimitFloatPrecision;
121 
122 static cl::opt<bool>
123     InsertAssertAlign("insert-assert-align", cl::init(true),
124                       cl::desc("Insert the experimental `assertalign` node."),
125                       cl::ReallyHidden);
126 
127 static cl::opt<unsigned, true>
128     LimitFPPrecision("limit-float-precision",
129                      cl::desc("Generate low-precision inline sequences "
130                               "for some float libcalls"),
131                      cl::location(LimitFloatPrecision), cl::Hidden,
132                      cl::init(0));
133 
134 static cl::opt<unsigned> SwitchPeelThreshold(
135     "switch-peel-threshold", cl::Hidden, cl::init(66),
136     cl::desc("Set the case probability threshold for peeling the case from a "
137              "switch statement. A value greater than 100 will void this "
138              "optimization"));
139 
140 // Limit the width of DAG chains. This is important in general to prevent
141 // DAG-based analysis from blowing up. For example, alias analysis and
142 // load clustering may not complete in reasonable time. It is difficult to
143 // recognize and avoid this situation within each individual analysis, and
144 // future analyses are likely to have the same behavior. Limiting DAG width is
145 // the safe approach and will be especially important with global DAGs.
146 //
147 // MaxParallelChains default is arbitrarily high to avoid affecting
148 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
149 // sequence over this should have been converted to llvm.memcpy by the
150 // frontend. It is easy to induce this behavior with .ll code such as:
151 // %buffer = alloca [4096 x i8]
152 // %data = load [4096 x i8]* %argPtr
153 // store [4096 x i8] %data, [4096 x i8]* %buffer
154 static const unsigned MaxParallelChains = 64;
155 
156 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
157                                       const SDValue *Parts, unsigned NumParts,
158                                       MVT PartVT, EVT ValueVT, const Value *V,
159                                       SDValue InChain,
160                                       std::optional<CallingConv::ID> CC);
161 
162 /// getCopyFromParts - Create a value that contains the specified legal parts
163 /// combined into the value they represent.  If the parts combine to a type
164 /// larger than ValueVT then AssertOp can be used to specify whether the extra
165 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
166 /// (ISD::AssertSext).
167 static SDValue
168 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
169                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
170                  SDValue InChain,
171                  std::optional<CallingConv::ID> CC = std::nullopt,
172                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
173   // Let the target assemble the parts if it wants to
174   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
175   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
176                                                    PartVT, ValueVT, CC))
177     return Val;
178 
179   if (ValueVT.isVector())
180     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
181                                   InChain, CC);
182 
183   assert(NumParts > 0 && "No parts to assemble!");
184   SDValue Val = Parts[0];
185 
186   if (NumParts > 1) {
187     // Assemble the value from multiple parts.
188     if (ValueVT.isInteger()) {
189       unsigned PartBits = PartVT.getSizeInBits();
190       unsigned ValueBits = ValueVT.getSizeInBits();
191 
192       // Assemble the power of 2 part.
193       unsigned RoundParts = llvm::bit_floor(NumParts);
194       unsigned RoundBits = PartBits * RoundParts;
195       EVT RoundVT = RoundBits == ValueBits ?
196         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
197       SDValue Lo, Hi;
198 
199       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
200 
201       if (RoundParts > 2) {
202         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
203                               InChain);
204         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
205                               PartVT, HalfVT, V, InChain);
206       } else {
207         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
208         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
209       }
210 
211       if (DAG.getDataLayout().isBigEndian())
212         std::swap(Lo, Hi);
213 
214       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
215 
216       if (RoundParts < NumParts) {
217         // Assemble the trailing non-power-of-2 part.
218         unsigned OddParts = NumParts - RoundParts;
219         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
220         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
221                               OddVT, V, InChain, CC);
222 
223         // Combine the round and odd parts.
224         Lo = Val;
225         if (DAG.getDataLayout().isBigEndian())
226           std::swap(Lo, Hi);
227         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
228         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
229         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
230                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
231                                          TLI.getShiftAmountTy(
232                                              TotalVT, DAG.getDataLayout())));
233         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
234         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
235       }
236     } else if (PartVT.isFloatingPoint()) {
237       // FP split into multiple FP parts (for ppcf128)
238       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
239              "Unexpected split");
240       SDValue Lo, Hi;
241       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
242       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
243       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
244         std::swap(Lo, Hi);
245       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
246     } else {
247       // FP split into integer parts (soft fp)
248       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
249              !PartVT.isVector() && "Unexpected split");
250       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
251       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
252                              InChain, CC);
253     }
254   }
255 
256   // There is now one part, held in Val.  Correct it to match ValueVT.
257   // PartEVT is the type of the register class that holds the value.
258   // ValueVT is the type of the inline asm operation.
259   EVT PartEVT = Val.getValueType();
260 
261   if (PartEVT == ValueVT)
262     return Val;
263 
264   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
265       ValueVT.bitsLT(PartEVT)) {
266     // For an FP value in an integer part, we need to truncate to the right
267     // width first.
268     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
269     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
270   }
271 
272   // Handle types that have the same size.
273   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
274     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
275 
276   // Handle types with different sizes.
277   if (PartEVT.isInteger() && ValueVT.isInteger()) {
278     if (ValueVT.bitsLT(PartEVT)) {
279       // For a truncate, see if we have any information to
280       // indicate whether the truncated bits will always be
281       // zero or sign-extension.
282       if (AssertOp)
283         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
284                           DAG.getValueType(ValueVT));
285       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
286     }
287     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
288   }
289 
290   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
291     // FP_ROUND's are always exact here.
292     if (ValueVT.bitsLT(Val.getValueType())) {
293 
294       SDValue NoChange =
295           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
296 
297       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
298               llvm::Attribute::StrictFP)) {
299         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
300                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
301                            NoChange);
302       }
303 
304       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
305     }
306 
307     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
308   }
309 
310   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
311   // then truncating.
312   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
313       ValueVT.bitsLT(PartEVT)) {
314     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
315     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
316   }
317 
318   report_fatal_error("Unknown mismatch in getCopyFromParts!");
319 }
320 
321 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
322                                               const Twine &ErrMsg) {
323   const Instruction *I = dyn_cast_or_null<Instruction>(V);
324   if (!V)
325     return Ctx.emitError(ErrMsg);
326 
327   const char *AsmError = ", possible invalid constraint for vector type";
328   if (const CallInst *CI = dyn_cast<CallInst>(I))
329     if (CI->isInlineAsm())
330       return Ctx.emitError(I, ErrMsg + AsmError);
331 
332   return Ctx.emitError(I, ErrMsg);
333 }
334 
335 /// getCopyFromPartsVector - Create a value that contains the specified legal
336 /// parts combined into the value they represent.  If the parts combine to a
337 /// type larger than ValueVT then AssertOp can be used to specify whether the
338 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
339 /// ValueVT (ISD::AssertSext).
340 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
341                                       const SDValue *Parts, unsigned NumParts,
342                                       MVT PartVT, EVT ValueVT, const Value *V,
343                                       SDValue InChain,
344                                       std::optional<CallingConv::ID> CallConv) {
345   assert(ValueVT.isVector() && "Not a vector value");
346   assert(NumParts > 0 && "No parts to assemble!");
347   const bool IsABIRegCopy = CallConv.has_value();
348 
349   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
350   SDValue Val = Parts[0];
351 
352   // Handle a multi-element vector.
353   if (NumParts > 1) {
354     EVT IntermediateVT;
355     MVT RegisterVT;
356     unsigned NumIntermediates;
357     unsigned NumRegs;
358 
359     if (IsABIRegCopy) {
360       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
361           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
362           NumIntermediates, RegisterVT);
363     } else {
364       NumRegs =
365           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
366                                      NumIntermediates, RegisterVT);
367     }
368 
369     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
370     NumParts = NumRegs; // Silence a compiler warning.
371     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
372     assert(RegisterVT.getSizeInBits() ==
373            Parts[0].getSimpleValueType().getSizeInBits() &&
374            "Part type sizes don't match!");
375 
376     // Assemble the parts into intermediate operands.
377     SmallVector<SDValue, 8> Ops(NumIntermediates);
378     if (NumIntermediates == NumParts) {
379       // If the register was not expanded, truncate or copy the value,
380       // as appropriate.
381       for (unsigned i = 0; i != NumParts; ++i)
382         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
383                                   V, InChain, CallConv);
384     } else if (NumParts > 0) {
385       // If the intermediate type was expanded, build the intermediate
386       // operands from the parts.
387       assert(NumParts % NumIntermediates == 0 &&
388              "Must expand into a divisible number of parts!");
389       unsigned Factor = NumParts / NumIntermediates;
390       for (unsigned i = 0; i != NumIntermediates; ++i)
391         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
392                                   IntermediateVT, V, InChain, CallConv);
393     }
394 
395     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
396     // intermediate operands.
397     EVT BuiltVectorTy =
398         IntermediateVT.isVector()
399             ? EVT::getVectorVT(
400                   *DAG.getContext(), IntermediateVT.getScalarType(),
401                   IntermediateVT.getVectorElementCount() * NumParts)
402             : EVT::getVectorVT(*DAG.getContext(),
403                                IntermediateVT.getScalarType(),
404                                NumIntermediates);
405     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
406                                                 : ISD::BUILD_VECTOR,
407                       DL, BuiltVectorTy, Ops);
408   }
409 
410   // There is now one part, held in Val.  Correct it to match ValueVT.
411   EVT PartEVT = Val.getValueType();
412 
413   if (PartEVT == ValueVT)
414     return Val;
415 
416   if (PartEVT.isVector()) {
417     // Vector/Vector bitcast.
418     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
419       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
420 
421     // If the parts vector has more elements than the value vector, then we
422     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
423     // Extract the elements we want.
424     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
425       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
426               ValueVT.getVectorElementCount().getKnownMinValue()) &&
427              (PartEVT.getVectorElementCount().isScalable() ==
428               ValueVT.getVectorElementCount().isScalable()) &&
429              "Cannot narrow, it would be a lossy transformation");
430       PartEVT =
431           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
432                            ValueVT.getVectorElementCount());
433       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
434                         DAG.getVectorIdxConstant(0, DL));
435       if (PartEVT == ValueVT)
436         return Val;
437       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
438         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
439 
440       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
441       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
442         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
443     }
444 
445     // Promoted vector extract
446     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
447   }
448 
449   // Trivial bitcast if the types are the same size and the destination
450   // vector type is legal.
451   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
452       TLI.isTypeLegal(ValueVT))
453     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
454 
455   if (ValueVT.getVectorNumElements() != 1) {
456      // Certain ABIs require that vectors are passed as integers. For vectors
457      // are the same size, this is an obvious bitcast.
458      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
459        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
460      } else if (ValueVT.bitsLT(PartEVT)) {
461        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
462        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
463        // Drop the extra bits.
464        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
465        return DAG.getBitcast(ValueVT, Val);
466      }
467 
468      diagnosePossiblyInvalidConstraint(
469          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
470      return DAG.getUNDEF(ValueVT);
471   }
472 
473   // Handle cases such as i8 -> <1 x i1>
474   EVT ValueSVT = ValueVT.getVectorElementType();
475   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
476     unsigned ValueSize = ValueSVT.getSizeInBits();
477     if (ValueSize == PartEVT.getSizeInBits()) {
478       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
479     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
480       // It's possible a scalar floating point type gets softened to integer and
481       // then promoted to a larger integer. If PartEVT is the larger integer
482       // we need to truncate it and then bitcast to the FP type.
483       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
484       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
485       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
486       Val = DAG.getBitcast(ValueSVT, Val);
487     } else {
488       Val = ValueVT.isFloatingPoint()
489                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
490                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
491     }
492   }
493 
494   return DAG.getBuildVector(ValueVT, DL, Val);
495 }
496 
497 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
498                                  SDValue Val, SDValue *Parts, unsigned NumParts,
499                                  MVT PartVT, const Value *V,
500                                  std::optional<CallingConv::ID> CallConv);
501 
502 /// getCopyToParts - Create a series of nodes that contain the specified value
503 /// split into legal parts.  If the parts contain more bits than Val, then, for
504 /// integers, ExtendKind can be used to specify how to generate the extra bits.
505 static void
506 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
507                unsigned NumParts, MVT PartVT, const Value *V,
508                std::optional<CallingConv::ID> CallConv = std::nullopt,
509                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
510   // Let the target split the parts if it wants to
511   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
512   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
513                                       CallConv))
514     return;
515   EVT ValueVT = Val.getValueType();
516 
517   // Handle the vector case separately.
518   if (ValueVT.isVector())
519     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
520                                 CallConv);
521 
522   unsigned OrigNumParts = NumParts;
523   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
524          "Copying to an illegal type!");
525 
526   if (NumParts == 0)
527     return;
528 
529   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
530   EVT PartEVT = PartVT;
531   if (PartEVT == ValueVT) {
532     assert(NumParts == 1 && "No-op copy with multiple parts!");
533     Parts[0] = Val;
534     return;
535   }
536 
537   unsigned PartBits = PartVT.getSizeInBits();
538   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
539     // If the parts cover more bits than the value has, promote the value.
540     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
541       assert(NumParts == 1 && "Do not know what to promote to!");
542       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
543     } else {
544       if (ValueVT.isFloatingPoint()) {
545         // FP values need to be bitcast, then extended if they are being put
546         // into a larger container.
547         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
548         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
549       }
550       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
551              ValueVT.isInteger() &&
552              "Unknown mismatch!");
553       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
554       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
555       if (PartVT == MVT::x86mmx)
556         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
557     }
558   } else if (PartBits == ValueVT.getSizeInBits()) {
559     // Different types of the same size.
560     assert(NumParts == 1 && PartEVT != ValueVT);
561     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
562   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
563     // If the parts cover less bits than value has, truncate the value.
564     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
565            ValueVT.isInteger() &&
566            "Unknown mismatch!");
567     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
568     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
569     if (PartVT == MVT::x86mmx)
570       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
571   }
572 
573   // The value may have changed - recompute ValueVT.
574   ValueVT = Val.getValueType();
575   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
576          "Failed to tile the value with PartVT!");
577 
578   if (NumParts == 1) {
579     if (PartEVT != ValueVT) {
580       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
581                                         "scalar-to-vector conversion failed");
582       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
583     }
584 
585     Parts[0] = Val;
586     return;
587   }
588 
589   // Expand the value into multiple parts.
590   if (NumParts & (NumParts - 1)) {
591     // The number of parts is not a power of 2.  Split off and copy the tail.
592     assert(PartVT.isInteger() && ValueVT.isInteger() &&
593            "Do not know what to expand to!");
594     unsigned RoundParts = llvm::bit_floor(NumParts);
595     unsigned RoundBits = RoundParts * PartBits;
596     unsigned OddParts = NumParts - RoundParts;
597     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
598       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
599 
600     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
601                    CallConv);
602 
603     if (DAG.getDataLayout().isBigEndian())
604       // The odd parts were reversed by getCopyToParts - unreverse them.
605       std::reverse(Parts + RoundParts, Parts + NumParts);
606 
607     NumParts = RoundParts;
608     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
609     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
610   }
611 
612   // The number of parts is a power of 2.  Repeatedly bisect the value using
613   // EXTRACT_ELEMENT.
614   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
615                          EVT::getIntegerVT(*DAG.getContext(),
616                                            ValueVT.getSizeInBits()),
617                          Val);
618 
619   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
620     for (unsigned i = 0; i < NumParts; i += StepSize) {
621       unsigned ThisBits = StepSize * PartBits / 2;
622       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
623       SDValue &Part0 = Parts[i];
624       SDValue &Part1 = Parts[i+StepSize/2];
625 
626       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
627                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
628       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
629                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
630 
631       if (ThisBits == PartBits && ThisVT != PartVT) {
632         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
633         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
634       }
635     }
636   }
637 
638   if (DAG.getDataLayout().isBigEndian())
639     std::reverse(Parts, Parts + OrigNumParts);
640 }
641 
642 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
643                                      const SDLoc &DL, EVT PartVT) {
644   if (!PartVT.isVector())
645     return SDValue();
646 
647   EVT ValueVT = Val.getValueType();
648   EVT PartEVT = PartVT.getVectorElementType();
649   EVT ValueEVT = ValueVT.getVectorElementType();
650   ElementCount PartNumElts = PartVT.getVectorElementCount();
651   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
652 
653   // We only support widening vectors with equivalent element types and
654   // fixed/scalable properties. If a target needs to widen a fixed-length type
655   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
656   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
657       PartNumElts.isScalable() != ValueNumElts.isScalable())
658     return SDValue();
659 
660   // Have a try for bf16 because some targets share its ABI with fp16.
661   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
662     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
663            "Cannot widen to illegal type");
664     Val = DAG.getNode(ISD::BITCAST, DL,
665                       ValueVT.changeVectorElementType(MVT::f16), Val);
666   } else if (PartEVT != ValueEVT) {
667     return SDValue();
668   }
669 
670   // Widening a scalable vector to another scalable vector is done by inserting
671   // the vector into a larger undef one.
672   if (PartNumElts.isScalable())
673     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
674                        Val, DAG.getVectorIdxConstant(0, DL));
675 
676   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
677   // undef elements.
678   SmallVector<SDValue, 16> Ops;
679   DAG.ExtractVectorElements(Val, Ops);
680   SDValue EltUndef = DAG.getUNDEF(PartEVT);
681   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
682 
683   // FIXME: Use CONCAT for 2x -> 4x.
684   return DAG.getBuildVector(PartVT, DL, Ops);
685 }
686 
687 /// getCopyToPartsVector - Create a series of nodes that contain the specified
688 /// value split into legal parts.
689 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
690                                  SDValue Val, SDValue *Parts, unsigned NumParts,
691                                  MVT PartVT, const Value *V,
692                                  std::optional<CallingConv::ID> CallConv) {
693   EVT ValueVT = Val.getValueType();
694   assert(ValueVT.isVector() && "Not a vector");
695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
696   const bool IsABIRegCopy = CallConv.has_value();
697 
698   if (NumParts == 1) {
699     EVT PartEVT = PartVT;
700     if (PartEVT == ValueVT) {
701       // Nothing to do.
702     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
703       // Bitconvert vector->vector case.
704       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
705     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
706       Val = Widened;
707     } else if (PartVT.isVector() &&
708                PartEVT.getVectorElementType().bitsGE(
709                    ValueVT.getVectorElementType()) &&
710                PartEVT.getVectorElementCount() ==
711                    ValueVT.getVectorElementCount()) {
712 
713       // Promoted vector extract
714       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
715     } else if (PartEVT.isVector() &&
716                PartEVT.getVectorElementType() !=
717                    ValueVT.getVectorElementType() &&
718                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
719                    TargetLowering::TypeWidenVector) {
720       // Combination of widening and promotion.
721       EVT WidenVT =
722           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
723                            PartVT.getVectorElementCount());
724       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
725       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
726     } else {
727       // Don't extract an integer from a float vector. This can happen if the
728       // FP type gets softened to integer and then promoted. The promotion
729       // prevents it from being picked up by the earlier bitcast case.
730       if (ValueVT.getVectorElementCount().isScalar() &&
731           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
732         // If we reach this condition and PartVT is FP, this means that
733         // ValueVT is also FP and both have a different size, otherwise we
734         // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
735         // would be invalid since that would mean the smaller FP type has to
736         // be extended to the larger one.
737         if (PartVT.isFloatingPoint()) {
738           Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
739           Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
740         } else
741           Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
742                             DAG.getVectorIdxConstant(0, DL));
743       } else {
744         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
745         assert(PartVT.getFixedSizeInBits() > ValueSize &&
746                "lossy conversion of vector to scalar type");
747         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
748         Val = DAG.getBitcast(IntermediateType, Val);
749         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
750       }
751     }
752 
753     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
754     Parts[0] = Val;
755     return;
756   }
757 
758   // Handle a multi-element vector.
759   EVT IntermediateVT;
760   MVT RegisterVT;
761   unsigned NumIntermediates;
762   unsigned NumRegs;
763   if (IsABIRegCopy) {
764     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
765         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
766         RegisterVT);
767   } else {
768     NumRegs =
769         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
770                                    NumIntermediates, RegisterVT);
771   }
772 
773   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
774   NumParts = NumRegs; // Silence a compiler warning.
775   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
776 
777   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
778          "Mixing scalable and fixed vectors when copying in parts");
779 
780   std::optional<ElementCount> DestEltCnt;
781 
782   if (IntermediateVT.isVector())
783     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
784   else
785     DestEltCnt = ElementCount::getFixed(NumIntermediates);
786 
787   EVT BuiltVectorTy = EVT::getVectorVT(
788       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
789 
790   if (ValueVT == BuiltVectorTy) {
791     // Nothing to do.
792   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
793     // Bitconvert vector->vector case.
794     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
795   } else {
796     if (BuiltVectorTy.getVectorElementType().bitsGT(
797             ValueVT.getVectorElementType())) {
798       // Integer promotion.
799       ValueVT = EVT::getVectorVT(*DAG.getContext(),
800                                  BuiltVectorTy.getVectorElementType(),
801                                  ValueVT.getVectorElementCount());
802       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
803     }
804 
805     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
806       Val = Widened;
807     }
808   }
809 
810   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
811 
812   // Split the vector into intermediate operands.
813   SmallVector<SDValue, 8> Ops(NumIntermediates);
814   for (unsigned i = 0; i != NumIntermediates; ++i) {
815     if (IntermediateVT.isVector()) {
816       // This does something sensible for scalable vectors - see the
817       // definition of EXTRACT_SUBVECTOR for further details.
818       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
819       Ops[i] =
820           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
821                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
822     } else {
823       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
824                            DAG.getVectorIdxConstant(i, DL));
825     }
826   }
827 
828   // Split the intermediate operands into legal parts.
829   if (NumParts == NumIntermediates) {
830     // If the register was not expanded, promote or copy the value,
831     // as appropriate.
832     for (unsigned i = 0; i != NumParts; ++i)
833       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
834   } else if (NumParts > 0) {
835     // If the intermediate type was expanded, split each the value into
836     // legal parts.
837     assert(NumIntermediates != 0 && "division by zero");
838     assert(NumParts % NumIntermediates == 0 &&
839            "Must expand into a divisible number of parts!");
840     unsigned Factor = NumParts / NumIntermediates;
841     for (unsigned i = 0; i != NumIntermediates; ++i)
842       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
843                      CallConv);
844   }
845 }
846 
847 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
848                            EVT valuevt, std::optional<CallingConv::ID> CC)
849     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
850       RegCount(1, regs.size()), CallConv(CC) {}
851 
852 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
853                            const DataLayout &DL, unsigned Reg, Type *Ty,
854                            std::optional<CallingConv::ID> CC) {
855   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
856 
857   CallConv = CC;
858 
859   for (EVT ValueVT : ValueVTs) {
860     unsigned NumRegs =
861         isABIMangled()
862             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
863             : TLI.getNumRegisters(Context, ValueVT);
864     MVT RegisterVT =
865         isABIMangled()
866             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
867             : TLI.getRegisterType(Context, ValueVT);
868     for (unsigned i = 0; i != NumRegs; ++i)
869       Regs.push_back(Reg + i);
870     RegVTs.push_back(RegisterVT);
871     RegCount.push_back(NumRegs);
872     Reg += NumRegs;
873   }
874 }
875 
876 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
877                                       FunctionLoweringInfo &FuncInfo,
878                                       const SDLoc &dl, SDValue &Chain,
879                                       SDValue *Glue, const Value *V) const {
880   // A Value with type {} or [0 x %t] needs no registers.
881   if (ValueVTs.empty())
882     return SDValue();
883 
884   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
885 
886   // Assemble the legal parts into the final values.
887   SmallVector<SDValue, 4> Values(ValueVTs.size());
888   SmallVector<SDValue, 8> Parts;
889   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
890     // Copy the legal parts from the registers.
891     EVT ValueVT = ValueVTs[Value];
892     unsigned NumRegs = RegCount[Value];
893     MVT RegisterVT = isABIMangled()
894                          ? TLI.getRegisterTypeForCallingConv(
895                                *DAG.getContext(), *CallConv, RegVTs[Value])
896                          : RegVTs[Value];
897 
898     Parts.resize(NumRegs);
899     for (unsigned i = 0; i != NumRegs; ++i) {
900       SDValue P;
901       if (!Glue) {
902         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
903       } else {
904         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
905         *Glue = P.getValue(2);
906       }
907 
908       Chain = P.getValue(1);
909       Parts[i] = P;
910 
911       // If the source register was virtual and if we know something about it,
912       // add an assert node.
913       if (!Register::isVirtualRegister(Regs[Part + i]) ||
914           !RegisterVT.isInteger())
915         continue;
916 
917       const FunctionLoweringInfo::LiveOutInfo *LOI =
918         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
919       if (!LOI)
920         continue;
921 
922       unsigned RegSize = RegisterVT.getScalarSizeInBits();
923       unsigned NumSignBits = LOI->NumSignBits;
924       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
925 
926       if (NumZeroBits == RegSize) {
927         // The current value is a zero.
928         // Explicitly express that as it would be easier for
929         // optimizations to kick in.
930         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
931         continue;
932       }
933 
934       // FIXME: We capture more information than the dag can represent.  For
935       // now, just use the tightest assertzext/assertsext possible.
936       bool isSExt;
937       EVT FromVT(MVT::Other);
938       if (NumZeroBits) {
939         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
940         isSExt = false;
941       } else if (NumSignBits > 1) {
942         FromVT =
943             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
944         isSExt = true;
945       } else {
946         continue;
947       }
948       // Add an assertion node.
949       assert(FromVT != MVT::Other);
950       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
951                              RegisterVT, P, DAG.getValueType(FromVT));
952     }
953 
954     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
955                                      RegisterVT, ValueVT, V, Chain, CallConv);
956     Part += NumRegs;
957     Parts.clear();
958   }
959 
960   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
961 }
962 
963 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
964                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
965                                  const Value *V,
966                                  ISD::NodeType PreferredExtendType) const {
967   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
968   ISD::NodeType ExtendKind = PreferredExtendType;
969 
970   // Get the list of the values's legal parts.
971   unsigned NumRegs = Regs.size();
972   SmallVector<SDValue, 8> Parts(NumRegs);
973   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
974     unsigned NumParts = RegCount[Value];
975 
976     MVT RegisterVT = isABIMangled()
977                          ? TLI.getRegisterTypeForCallingConv(
978                                *DAG.getContext(), *CallConv, RegVTs[Value])
979                          : RegVTs[Value];
980 
981     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
982       ExtendKind = ISD::ZERO_EXTEND;
983 
984     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
985                    NumParts, RegisterVT, V, CallConv, ExtendKind);
986     Part += NumParts;
987   }
988 
989   // Copy the parts into the registers.
990   SmallVector<SDValue, 8> Chains(NumRegs);
991   for (unsigned i = 0; i != NumRegs; ++i) {
992     SDValue Part;
993     if (!Glue) {
994       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
995     } else {
996       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
997       *Glue = Part.getValue(1);
998     }
999 
1000     Chains[i] = Part.getValue(0);
1001   }
1002 
1003   if (NumRegs == 1 || Glue)
1004     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1005     // flagged to it. That is the CopyToReg nodes and the user are considered
1006     // a single scheduling unit. If we create a TokenFactor and return it as
1007     // chain, then the TokenFactor is both a predecessor (operand) of the
1008     // user as well as a successor (the TF operands are flagged to the user).
1009     // c1, f1 = CopyToReg
1010     // c2, f2 = CopyToReg
1011     // c3     = TokenFactor c1, c2
1012     // ...
1013     //        = op c3, ..., f2
1014     Chain = Chains[NumRegs-1];
1015   else
1016     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1017 }
1018 
1019 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1020                                         unsigned MatchingIdx, const SDLoc &dl,
1021                                         SelectionDAG &DAG,
1022                                         std::vector<SDValue> &Ops) const {
1023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1024 
1025   InlineAsm::Flag Flag(Code, Regs.size());
1026   if (HasMatching)
1027     Flag.setMatchingOp(MatchingIdx);
1028   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1029     // Put the register class of the virtual registers in the flag word.  That
1030     // way, later passes can recompute register class constraints for inline
1031     // assembly as well as normal instructions.
1032     // Don't do this for tied operands that can use the regclass information
1033     // from the def.
1034     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1035     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1036     Flag.setRegClass(RC->getID());
1037   }
1038 
1039   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1040   Ops.push_back(Res);
1041 
1042   if (Code == InlineAsm::Kind::Clobber) {
1043     // Clobbers should always have a 1:1 mapping with registers, and may
1044     // reference registers that have illegal (e.g. vector) types. Hence, we
1045     // shouldn't try to apply any sort of splitting logic to them.
1046     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1047            "No 1:1 mapping from clobbers to regs?");
1048     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1049     (void)SP;
1050     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1051       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1052       assert(
1053           (Regs[I] != SP ||
1054            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1055           "If we clobbered the stack pointer, MFI should know about it.");
1056     }
1057     return;
1058   }
1059 
1060   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1061     MVT RegisterVT = RegVTs[Value];
1062     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1063                                            RegisterVT);
1064     for (unsigned i = 0; i != NumRegs; ++i) {
1065       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1066       unsigned TheReg = Regs[Reg++];
1067       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1068     }
1069   }
1070 }
1071 
1072 SmallVector<std::pair<unsigned, TypeSize>, 4>
1073 RegsForValue::getRegsAndSizes() const {
1074   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1075   unsigned I = 0;
1076   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1077     unsigned RegCount = std::get<0>(CountAndVT);
1078     MVT RegisterVT = std::get<1>(CountAndVT);
1079     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1080     for (unsigned E = I + RegCount; I != E; ++I)
1081       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1082   }
1083   return OutVec;
1084 }
1085 
1086 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1087                                AssumptionCache *ac,
1088                                const TargetLibraryInfo *li) {
1089   AA = aa;
1090   AC = ac;
1091   GFI = gfi;
1092   LibInfo = li;
1093   Context = DAG.getContext();
1094   LPadToCallSiteMap.clear();
1095   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1096   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1097       *DAG.getMachineFunction().getFunction().getParent());
1098 }
1099 
1100 void SelectionDAGBuilder::clear() {
1101   NodeMap.clear();
1102   UnusedArgNodeMap.clear();
1103   PendingLoads.clear();
1104   PendingExports.clear();
1105   PendingConstrainedFP.clear();
1106   PendingConstrainedFPStrict.clear();
1107   CurInst = nullptr;
1108   HasTailCall = false;
1109   SDNodeOrder = LowestSDNodeOrder;
1110   StatepointLowering.clear();
1111 }
1112 
1113 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1114   DanglingDebugInfoMap.clear();
1115 }
1116 
1117 // Update DAG root to include dependencies on Pending chains.
1118 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1119   SDValue Root = DAG.getRoot();
1120 
1121   if (Pending.empty())
1122     return Root;
1123 
1124   // Add current root to PendingChains, unless we already indirectly
1125   // depend on it.
1126   if (Root.getOpcode() != ISD::EntryToken) {
1127     unsigned i = 0, e = Pending.size();
1128     for (; i != e; ++i) {
1129       assert(Pending[i].getNode()->getNumOperands() > 1);
1130       if (Pending[i].getNode()->getOperand(0) == Root)
1131         break;  // Don't add the root if we already indirectly depend on it.
1132     }
1133 
1134     if (i == e)
1135       Pending.push_back(Root);
1136   }
1137 
1138   if (Pending.size() == 1)
1139     Root = Pending[0];
1140   else
1141     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1142 
1143   DAG.setRoot(Root);
1144   Pending.clear();
1145   return Root;
1146 }
1147 
1148 SDValue SelectionDAGBuilder::getMemoryRoot() {
1149   return updateRoot(PendingLoads);
1150 }
1151 
1152 SDValue SelectionDAGBuilder::getRoot() {
1153   // Chain up all pending constrained intrinsics together with all
1154   // pending loads, by simply appending them to PendingLoads and
1155   // then calling getMemoryRoot().
1156   PendingLoads.reserve(PendingLoads.size() +
1157                        PendingConstrainedFP.size() +
1158                        PendingConstrainedFPStrict.size());
1159   PendingLoads.append(PendingConstrainedFP.begin(),
1160                       PendingConstrainedFP.end());
1161   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1162                       PendingConstrainedFPStrict.end());
1163   PendingConstrainedFP.clear();
1164   PendingConstrainedFPStrict.clear();
1165   return getMemoryRoot();
1166 }
1167 
1168 SDValue SelectionDAGBuilder::getControlRoot() {
1169   // We need to emit pending fpexcept.strict constrained intrinsics,
1170   // so append them to the PendingExports list.
1171   PendingExports.append(PendingConstrainedFPStrict.begin(),
1172                         PendingConstrainedFPStrict.end());
1173   PendingConstrainedFPStrict.clear();
1174   return updateRoot(PendingExports);
1175 }
1176 
1177 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1178                                              DILocalVariable *Variable,
1179                                              DIExpression *Expression,
1180                                              DebugLoc DL) {
1181   assert(Variable && "Missing variable");
1182 
1183   // Check if address has undef value.
1184   if (!Address || isa<UndefValue>(Address) ||
1185       (Address->use_empty() && !isa<Argument>(Address))) {
1186     LLVM_DEBUG(
1187         dbgs()
1188         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1189     return;
1190   }
1191 
1192   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1193 
1194   SDValue &N = NodeMap[Address];
1195   if (!N.getNode() && isa<Argument>(Address))
1196     // Check unused arguments map.
1197     N = UnusedArgNodeMap[Address];
1198   SDDbgValue *SDV;
1199   if (N.getNode()) {
1200     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1201       Address = BCI->getOperand(0);
1202     // Parameters are handled specially.
1203     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1204     if (IsParameter && FINode) {
1205       // Byval parameter. We have a frame index at this point.
1206       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1207                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1208     } else if (isa<Argument>(Address)) {
1209       // Address is an argument, so try to emit its dbg value using
1210       // virtual register info from the FuncInfo.ValueMap.
1211       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1212                                FuncArgumentDbgValueKind::Declare, N);
1213       return;
1214     } else {
1215       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1216                             true, DL, SDNodeOrder);
1217     }
1218     DAG.AddDbgValue(SDV, IsParameter);
1219   } else {
1220     // If Address is an argument then try to emit its dbg value using
1221     // virtual register info from the FuncInfo.ValueMap.
1222     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1223                                   FuncArgumentDbgValueKind::Declare, N)) {
1224       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1225                         << " (could not emit func-arg dbg_value)\n");
1226     }
1227   }
1228   return;
1229 }
1230 
1231 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1232   // Add SDDbgValue nodes for any var locs here. Do so before updating
1233   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1234   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1235     // Add SDDbgValue nodes for any var locs here. Do so before updating
1236     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1237     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1238          It != End; ++It) {
1239       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1240       dropDanglingDebugInfo(Var, It->Expr);
1241       if (It->Values.isKillLocation(It->Expr)) {
1242         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1243         continue;
1244       }
1245       SmallVector<Value *> Values(It->Values.location_ops());
1246       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1247                             It->Values.hasArgList())) {
1248         SmallVector<Value *, 4> Vals;
1249         for (Value *V : It->Values.location_ops())
1250           Vals.push_back(V);
1251         addDanglingDebugInfo(Vals,
1252                              FnVarLocs->getDILocalVariable(It->VariableID),
1253                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1254       }
1255     }
1256   }
1257 
1258   // We must skip DbgVariableRecords if they've already been processed above as
1259   // we have just emitted the debug values resulting from assignment tracking
1260   // analysis, making any existing DbgVariableRecords redundant (and probably
1261   // less correct). We still need to process DbgLabelRecords. This does sink
1262   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1263   // be important as it does so deterministcally and ordering between
1264   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1265   // printing).
1266   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1267   // Is there is any debug-info attached to this instruction, in the form of
1268   // DbgRecord non-instruction debug-info records.
1269   for (DbgRecord &DR : I.getDbgRecordRange()) {
1270     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1271       assert(DLR->getLabel() && "Missing label");
1272       SDDbgLabel *SDV =
1273           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1274       DAG.AddDbgLabel(SDV);
1275       continue;
1276     }
1277 
1278     if (SkipDbgVariableRecords)
1279       continue;
1280     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1281     DILocalVariable *Variable = DVR.getVariable();
1282     DIExpression *Expression = DVR.getExpression();
1283     dropDanglingDebugInfo(Variable, Expression);
1284 
1285     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1286       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1287         continue;
1288       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1289                         << "\n");
1290       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1291                          DVR.getDebugLoc());
1292       continue;
1293     }
1294 
1295     // A DbgVariableRecord with no locations is a kill location.
1296     SmallVector<Value *, 4> Values(DVR.location_ops());
1297     if (Values.empty()) {
1298       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1299                            SDNodeOrder);
1300       continue;
1301     }
1302 
1303     // A DbgVariableRecord with an undef or absent location is also a kill
1304     // location.
1305     if (llvm::any_of(Values,
1306                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1307       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1308                            SDNodeOrder);
1309       continue;
1310     }
1311 
1312     bool IsVariadic = DVR.hasArgList();
1313     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1314                           SDNodeOrder, IsVariadic)) {
1315       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1316                            DVR.getDebugLoc(), SDNodeOrder);
1317     }
1318   }
1319 }
1320 
1321 void SelectionDAGBuilder::visit(const Instruction &I) {
1322   visitDbgInfo(I);
1323 
1324   // Set up outgoing PHI node register values before emitting the terminator.
1325   if (I.isTerminator()) {
1326     HandlePHINodesInSuccessorBlocks(I.getParent());
1327   }
1328 
1329   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1330   if (!isa<DbgInfoIntrinsic>(I))
1331     ++SDNodeOrder;
1332 
1333   CurInst = &I;
1334 
1335   // Set inserted listener only if required.
1336   bool NodeInserted = false;
1337   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1338   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1339   MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1340   if (PCSectionsMD || MMRA) {
1341     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1342         DAG, [&](SDNode *) { NodeInserted = true; });
1343   }
1344 
1345   visit(I.getOpcode(), I);
1346 
1347   if (!I.isTerminator() && !HasTailCall &&
1348       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1349     CopyToExportRegsIfNeeded(&I);
1350 
1351   // Handle metadata.
1352   if (PCSectionsMD || MMRA) {
1353     auto It = NodeMap.find(&I);
1354     if (It != NodeMap.end()) {
1355       if (PCSectionsMD)
1356         DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1357       if (MMRA)
1358         DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1359     } else if (NodeInserted) {
1360       // This should not happen; if it does, don't let it go unnoticed so we can
1361       // fix it. Relevant visit*() function is probably missing a setValue().
1362       errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1363              << I.getModule()->getName() << "]\n";
1364       LLVM_DEBUG(I.dump());
1365       assert(false);
1366     }
1367   }
1368 
1369   CurInst = nullptr;
1370 }
1371 
1372 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1373   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1374 }
1375 
1376 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1377   // Note: this doesn't use InstVisitor, because it has to work with
1378   // ConstantExpr's in addition to instructions.
1379   switch (Opcode) {
1380   default: llvm_unreachable("Unknown instruction type encountered!");
1381     // Build the switch statement using the Instruction.def file.
1382 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1383     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1384 #include "llvm/IR/Instruction.def"
1385   }
1386 }
1387 
1388 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1389                                             DILocalVariable *Variable,
1390                                             DebugLoc DL, unsigned Order,
1391                                             SmallVectorImpl<Value *> &Values,
1392                                             DIExpression *Expression) {
1393   // For variadic dbg_values we will now insert an undef.
1394   // FIXME: We can potentially recover these!
1395   SmallVector<SDDbgOperand, 2> Locs;
1396   for (const Value *V : Values) {
1397     auto *Undef = UndefValue::get(V->getType());
1398     Locs.push_back(SDDbgOperand::fromConst(Undef));
1399   }
1400   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1401                                         /*IsIndirect=*/false, DL, Order,
1402                                         /*IsVariadic=*/true);
1403   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1404   return true;
1405 }
1406 
1407 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1408                                                DILocalVariable *Var,
1409                                                DIExpression *Expr,
1410                                                bool IsVariadic, DebugLoc DL,
1411                                                unsigned Order) {
1412   if (IsVariadic) {
1413     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1414     return;
1415   }
1416   // TODO: Dangling debug info will eventually either be resolved or produce
1417   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1418   // between the original dbg.value location and its resolved DBG_VALUE,
1419   // which we should ideally fill with an extra Undef DBG_VALUE.
1420   assert(Values.size() == 1);
1421   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1422 }
1423 
1424 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1425                                                 const DIExpression *Expr) {
1426   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1427     DIVariable *DanglingVariable = DDI.getVariable();
1428     DIExpression *DanglingExpr = DDI.getExpression();
1429     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1430       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1431                         << printDDI(nullptr, DDI) << "\n");
1432       return true;
1433     }
1434     return false;
1435   };
1436 
1437   for (auto &DDIMI : DanglingDebugInfoMap) {
1438     DanglingDebugInfoVector &DDIV = DDIMI.second;
1439 
1440     // If debug info is to be dropped, run it through final checks to see
1441     // whether it can be salvaged.
1442     for (auto &DDI : DDIV)
1443       if (isMatchingDbgValue(DDI))
1444         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1445 
1446     erase_if(DDIV, isMatchingDbgValue);
1447   }
1448 }
1449 
1450 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1451 // generate the debug data structures now that we've seen its definition.
1452 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1453                                                    SDValue Val) {
1454   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1455   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1456     return;
1457 
1458   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1459   for (auto &DDI : DDIV) {
1460     DebugLoc DL = DDI.getDebugLoc();
1461     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1462     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1463     DILocalVariable *Variable = DDI.getVariable();
1464     DIExpression *Expr = DDI.getExpression();
1465     assert(Variable->isValidLocationForIntrinsic(DL) &&
1466            "Expected inlined-at fields to agree");
1467     SDDbgValue *SDV;
1468     if (Val.getNode()) {
1469       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1470       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1471       // we couldn't resolve it directly when examining the DbgValue intrinsic
1472       // in the first place we should not be more successful here). Unless we
1473       // have some test case that prove this to be correct we should avoid
1474       // calling EmitFuncArgumentDbgValue here.
1475       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1476                                     FuncArgumentDbgValueKind::Value, Val)) {
1477         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1478                           << printDDI(V, DDI) << "\n");
1479         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1480         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1481         // inserted after the definition of Val when emitting the instructions
1482         // after ISel. An alternative could be to teach
1483         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1484         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1485                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1486                    << ValSDNodeOrder << "\n");
1487         SDV = getDbgValue(Val, Variable, Expr, DL,
1488                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1489         DAG.AddDbgValue(SDV, false);
1490       } else
1491         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1492                           << printDDI(V, DDI)
1493                           << " in EmitFuncArgumentDbgValue\n");
1494     } else {
1495       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1496                         << "\n");
1497       auto Undef = UndefValue::get(V->getType());
1498       auto SDV =
1499           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1500       DAG.AddDbgValue(SDV, false);
1501     }
1502   }
1503   DDIV.clear();
1504 }
1505 
1506 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1507                                                     DanglingDebugInfo &DDI) {
1508   // TODO: For the variadic implementation, instead of only checking the fail
1509   // state of `handleDebugValue`, we need know specifically which values were
1510   // invalid, so that we attempt to salvage only those values when processing
1511   // a DIArgList.
1512   const Value *OrigV = V;
1513   DILocalVariable *Var = DDI.getVariable();
1514   DIExpression *Expr = DDI.getExpression();
1515   DebugLoc DL = DDI.getDebugLoc();
1516   unsigned SDOrder = DDI.getSDNodeOrder();
1517 
1518   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1519   // that DW_OP_stack_value is desired.
1520   bool StackValue = true;
1521 
1522   // Can this Value can be encoded without any further work?
1523   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1524     return;
1525 
1526   // Attempt to salvage back through as many instructions as possible. Bail if
1527   // a non-instruction is seen, such as a constant expression or global
1528   // variable. FIXME: Further work could recover those too.
1529   while (isa<Instruction>(V)) {
1530     const Instruction &VAsInst = *cast<const Instruction>(V);
1531     // Temporary "0", awaiting real implementation.
1532     SmallVector<uint64_t, 16> Ops;
1533     SmallVector<Value *, 4> AdditionalValues;
1534     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1535                              Expr->getNumLocationOperands(), Ops,
1536                              AdditionalValues);
1537     // If we cannot salvage any further, and haven't yet found a suitable debug
1538     // expression, bail out.
1539     if (!V)
1540       break;
1541 
1542     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1543     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1544     // here for variadic dbg_values, remove that condition.
1545     if (!AdditionalValues.empty())
1546       break;
1547 
1548     // New value and expr now represent this debuginfo.
1549     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1550 
1551     // Some kind of simplification occurred: check whether the operand of the
1552     // salvaged debug expression can be encoded in this DAG.
1553     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1554       LLVM_DEBUG(
1555           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1556                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1557       return;
1558     }
1559   }
1560 
1561   // This was the final opportunity to salvage this debug information, and it
1562   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1563   // any earlier variable location.
1564   assert(OrigV && "V shouldn't be null");
1565   auto *Undef = UndefValue::get(OrigV->getType());
1566   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1567   DAG.AddDbgValue(SDV, false);
1568   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1569                     << printDDI(OrigV, DDI) << "\n");
1570 }
1571 
1572 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1573                                                DIExpression *Expr,
1574                                                DebugLoc DbgLoc,
1575                                                unsigned Order) {
1576   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1577   DIExpression *NewExpr =
1578       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1579   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1580                    /*IsVariadic*/ false);
1581 }
1582 
1583 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1584                                            DILocalVariable *Var,
1585                                            DIExpression *Expr, DebugLoc DbgLoc,
1586                                            unsigned Order, bool IsVariadic) {
1587   if (Values.empty())
1588     return true;
1589 
1590   // Filter EntryValue locations out early.
1591   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1592     return true;
1593 
1594   SmallVector<SDDbgOperand> LocationOps;
1595   SmallVector<SDNode *> Dependencies;
1596   for (const Value *V : Values) {
1597     // Constant value.
1598     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1599         isa<ConstantPointerNull>(V)) {
1600       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1601       continue;
1602     }
1603 
1604     // Look through IntToPtr constants.
1605     if (auto *CE = dyn_cast<ConstantExpr>(V))
1606       if (CE->getOpcode() == Instruction::IntToPtr) {
1607         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1608         continue;
1609       }
1610 
1611     // If the Value is a frame index, we can create a FrameIndex debug value
1612     // without relying on the DAG at all.
1613     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1614       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1615       if (SI != FuncInfo.StaticAllocaMap.end()) {
1616         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1617         continue;
1618       }
1619     }
1620 
1621     // Do not use getValue() in here; we don't want to generate code at
1622     // this point if it hasn't been done yet.
1623     SDValue N = NodeMap[V];
1624     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1625       N = UnusedArgNodeMap[V];
1626     if (N.getNode()) {
1627       // Only emit func arg dbg value for non-variadic dbg.values for now.
1628       if (!IsVariadic &&
1629           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1630                                    FuncArgumentDbgValueKind::Value, N))
1631         return true;
1632       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1633         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1634         // describe stack slot locations.
1635         //
1636         // Consider "int x = 0; int *px = &x;". There are two kinds of
1637         // interesting debug values here after optimization:
1638         //
1639         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1640         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1641         //
1642         // Both describe the direct values of their associated variables.
1643         Dependencies.push_back(N.getNode());
1644         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1645         continue;
1646       }
1647       LocationOps.emplace_back(
1648           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1649       continue;
1650     }
1651 
1652     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1653     // Special rules apply for the first dbg.values of parameter variables in a
1654     // function. Identify them by the fact they reference Argument Values, that
1655     // they're parameters, and they are parameters of the current function. We
1656     // need to let them dangle until they get an SDNode.
1657     bool IsParamOfFunc =
1658         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1659     if (IsParamOfFunc)
1660       return false;
1661 
1662     // The value is not used in this block yet (or it would have an SDNode).
1663     // We still want the value to appear for the user if possible -- if it has
1664     // an associated VReg, we can refer to that instead.
1665     auto VMI = FuncInfo.ValueMap.find(V);
1666     if (VMI != FuncInfo.ValueMap.end()) {
1667       unsigned Reg = VMI->second;
1668       // If this is a PHI node, it may be split up into several MI PHI nodes
1669       // (in FunctionLoweringInfo::set).
1670       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1671                        V->getType(), std::nullopt);
1672       if (RFV.occupiesMultipleRegs()) {
1673         // FIXME: We could potentially support variadic dbg_values here.
1674         if (IsVariadic)
1675           return false;
1676         unsigned Offset = 0;
1677         unsigned BitsToDescribe = 0;
1678         if (auto VarSize = Var->getSizeInBits())
1679           BitsToDescribe = *VarSize;
1680         if (auto Fragment = Expr->getFragmentInfo())
1681           BitsToDescribe = Fragment->SizeInBits;
1682         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1683           // Bail out if all bits are described already.
1684           if (Offset >= BitsToDescribe)
1685             break;
1686           // TODO: handle scalable vectors.
1687           unsigned RegisterSize = RegAndSize.second;
1688           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1689                                       ? BitsToDescribe - Offset
1690                                       : RegisterSize;
1691           auto FragmentExpr = DIExpression::createFragmentExpression(
1692               Expr, Offset, FragmentSize);
1693           if (!FragmentExpr)
1694             continue;
1695           SDDbgValue *SDV = DAG.getVRegDbgValue(
1696               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1697           DAG.AddDbgValue(SDV, false);
1698           Offset += RegisterSize;
1699         }
1700         return true;
1701       }
1702       // We can use simple vreg locations for variadic dbg_values as well.
1703       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1704       continue;
1705     }
1706     // We failed to create a SDDbgOperand for V.
1707     return false;
1708   }
1709 
1710   // We have created a SDDbgOperand for each Value in Values.
1711   assert(!LocationOps.empty());
1712   SDDbgValue *SDV =
1713       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1714                           /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1715   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1716   return true;
1717 }
1718 
1719 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1720   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1721   for (auto &Pair : DanglingDebugInfoMap)
1722     for (auto &DDI : Pair.second)
1723       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1724   clearDanglingDebugInfo();
1725 }
1726 
1727 /// getCopyFromRegs - If there was virtual register allocated for the value V
1728 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1729 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1730   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1731   SDValue Result;
1732 
1733   if (It != FuncInfo.ValueMap.end()) {
1734     Register InReg = It->second;
1735 
1736     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1737                      DAG.getDataLayout(), InReg, Ty,
1738                      std::nullopt); // This is not an ABI copy.
1739     SDValue Chain = DAG.getEntryNode();
1740     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1741                                  V);
1742     resolveDanglingDebugInfo(V, Result);
1743   }
1744 
1745   return Result;
1746 }
1747 
1748 /// getValue - Return an SDValue for the given Value.
1749 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1750   // If we already have an SDValue for this value, use it. It's important
1751   // to do this first, so that we don't create a CopyFromReg if we already
1752   // have a regular SDValue.
1753   SDValue &N = NodeMap[V];
1754   if (N.getNode()) return N;
1755 
1756   // If there's a virtual register allocated and initialized for this
1757   // value, use it.
1758   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1759     return copyFromReg;
1760 
1761   // Otherwise create a new SDValue and remember it.
1762   SDValue Val = getValueImpl(V);
1763   NodeMap[V] = Val;
1764   resolveDanglingDebugInfo(V, Val);
1765   return Val;
1766 }
1767 
1768 /// getNonRegisterValue - Return an SDValue for the given Value, but
1769 /// don't look in FuncInfo.ValueMap for a virtual register.
1770 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1771   // If we already have an SDValue for this value, use it.
1772   SDValue &N = NodeMap[V];
1773   if (N.getNode()) {
1774     if (isIntOrFPConstant(N)) {
1775       // Remove the debug location from the node as the node is about to be used
1776       // in a location which may differ from the original debug location.  This
1777       // is relevant to Constant and ConstantFP nodes because they can appear
1778       // as constant expressions inside PHI nodes.
1779       N->setDebugLoc(DebugLoc());
1780     }
1781     return N;
1782   }
1783 
1784   // Otherwise create a new SDValue and remember it.
1785   SDValue Val = getValueImpl(V);
1786   NodeMap[V] = Val;
1787   resolveDanglingDebugInfo(V, Val);
1788   return Val;
1789 }
1790 
1791 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1792 /// Create an SDValue for the given value.
1793 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1794   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1795 
1796   if (const Constant *C = dyn_cast<Constant>(V)) {
1797     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1798 
1799     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1800       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1801 
1802     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1803       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1804 
1805     if (isa<ConstantPointerNull>(C)) {
1806       unsigned AS = V->getType()->getPointerAddressSpace();
1807       return DAG.getConstant(0, getCurSDLoc(),
1808                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1809     }
1810 
1811     if (match(C, m_VScale()))
1812       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1813 
1814     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1815       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1816 
1817     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1818       return DAG.getUNDEF(VT);
1819 
1820     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1821       visit(CE->getOpcode(), *CE);
1822       SDValue N1 = NodeMap[V];
1823       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1824       return N1;
1825     }
1826 
1827     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1828       SmallVector<SDValue, 4> Constants;
1829       for (const Use &U : C->operands()) {
1830         SDNode *Val = getValue(U).getNode();
1831         // If the operand is an empty aggregate, there are no values.
1832         if (!Val) continue;
1833         // Add each leaf value from the operand to the Constants list
1834         // to form a flattened list of all the values.
1835         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1836           Constants.push_back(SDValue(Val, i));
1837       }
1838 
1839       return DAG.getMergeValues(Constants, getCurSDLoc());
1840     }
1841 
1842     if (const ConstantDataSequential *CDS =
1843           dyn_cast<ConstantDataSequential>(C)) {
1844       SmallVector<SDValue, 4> Ops;
1845       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1846         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1847         // Add each leaf value from the operand to the Constants list
1848         // to form a flattened list of all the values.
1849         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1850           Ops.push_back(SDValue(Val, i));
1851       }
1852 
1853       if (isa<ArrayType>(CDS->getType()))
1854         return DAG.getMergeValues(Ops, getCurSDLoc());
1855       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1856     }
1857 
1858     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1859       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1860              "Unknown struct or array constant!");
1861 
1862       SmallVector<EVT, 4> ValueVTs;
1863       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1864       unsigned NumElts = ValueVTs.size();
1865       if (NumElts == 0)
1866         return SDValue(); // empty struct
1867       SmallVector<SDValue, 4> Constants(NumElts);
1868       for (unsigned i = 0; i != NumElts; ++i) {
1869         EVT EltVT = ValueVTs[i];
1870         if (isa<UndefValue>(C))
1871           Constants[i] = DAG.getUNDEF(EltVT);
1872         else if (EltVT.isFloatingPoint())
1873           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1874         else
1875           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1876       }
1877 
1878       return DAG.getMergeValues(Constants, getCurSDLoc());
1879     }
1880 
1881     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1882       return DAG.getBlockAddress(BA, VT);
1883 
1884     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1885       return getValue(Equiv->getGlobalValue());
1886 
1887     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1888       return getValue(NC->getGlobalValue());
1889 
1890     if (VT == MVT::aarch64svcount) {
1891       assert(C->isNullValue() && "Can only zero this target type!");
1892       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1893                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1894     }
1895 
1896     VectorType *VecTy = cast<VectorType>(V->getType());
1897 
1898     // Now that we know the number and type of the elements, get that number of
1899     // elements into the Ops array based on what kind of constant it is.
1900     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1901       SmallVector<SDValue, 16> Ops;
1902       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1903       for (unsigned i = 0; i != NumElements; ++i)
1904         Ops.push_back(getValue(CV->getOperand(i)));
1905 
1906       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1907     }
1908 
1909     if (isa<ConstantAggregateZero>(C)) {
1910       EVT EltVT =
1911           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1912 
1913       SDValue Op;
1914       if (EltVT.isFloatingPoint())
1915         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1916       else
1917         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1918 
1919       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1920     }
1921 
1922     llvm_unreachable("Unknown vector constant");
1923   }
1924 
1925   // If this is a static alloca, generate it as the frameindex instead of
1926   // computation.
1927   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1928     DenseMap<const AllocaInst*, int>::iterator SI =
1929       FuncInfo.StaticAllocaMap.find(AI);
1930     if (SI != FuncInfo.StaticAllocaMap.end())
1931       return DAG.getFrameIndex(
1932           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1933   }
1934 
1935   // If this is an instruction which fast-isel has deferred, select it now.
1936   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1937     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1938 
1939     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1940                      Inst->getType(), std::nullopt);
1941     SDValue Chain = DAG.getEntryNode();
1942     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1943   }
1944 
1945   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1946     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1947 
1948   if (const auto *BB = dyn_cast<BasicBlock>(V))
1949     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1950 
1951   llvm_unreachable("Can't get register for value!");
1952 }
1953 
1954 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1955   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1956   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1957   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1958   bool IsSEH = isAsynchronousEHPersonality(Pers);
1959   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1960   if (!IsSEH)
1961     CatchPadMBB->setIsEHScopeEntry();
1962   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1963   if (IsMSVCCXX || IsCoreCLR)
1964     CatchPadMBB->setIsEHFuncletEntry();
1965 }
1966 
1967 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1968   // Update machine-CFG edge.
1969   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1970   FuncInfo.MBB->addSuccessor(TargetMBB);
1971   TargetMBB->setIsEHCatchretTarget(true);
1972   DAG.getMachineFunction().setHasEHCatchret(true);
1973 
1974   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1975   bool IsSEH = isAsynchronousEHPersonality(Pers);
1976   if (IsSEH) {
1977     // If this is not a fall-through branch or optimizations are switched off,
1978     // emit the branch.
1979     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1980         TM.getOptLevel() == CodeGenOptLevel::None)
1981       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1982                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1983     return;
1984   }
1985 
1986   // Figure out the funclet membership for the catchret's successor.
1987   // This will be used by the FuncletLayout pass to determine how to order the
1988   // BB's.
1989   // A 'catchret' returns to the outer scope's color.
1990   Value *ParentPad = I.getCatchSwitchParentPad();
1991   const BasicBlock *SuccessorColor;
1992   if (isa<ConstantTokenNone>(ParentPad))
1993     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
1994   else
1995     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
1996   assert(SuccessorColor && "No parent funclet for catchret!");
1997   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
1998   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
1999 
2000   // Create the terminator node.
2001   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2002                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
2003                             DAG.getBasicBlock(SuccessorColorMBB));
2004   DAG.setRoot(Ret);
2005 }
2006 
2007 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2008   // Don't emit any special code for the cleanuppad instruction. It just marks
2009   // the start of an EH scope/funclet.
2010   FuncInfo.MBB->setIsEHScopeEntry();
2011   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2012   if (Pers != EHPersonality::Wasm_CXX) {
2013     FuncInfo.MBB->setIsEHFuncletEntry();
2014     FuncInfo.MBB->setIsCleanupFuncletEntry();
2015   }
2016 }
2017 
2018 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2019 // not match, it is OK to add only the first unwind destination catchpad to the
2020 // successors, because there will be at least one invoke instruction within the
2021 // catch scope that points to the next unwind destination, if one exists, so
2022 // CFGSort cannot mess up with BB sorting order.
2023 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2024 // call within them, and catchpads only consisting of 'catch (...)' have a
2025 // '__cxa_end_catch' call within them, both of which generate invokes in case
2026 // the next unwind destination exists, i.e., the next unwind destination is not
2027 // the caller.)
2028 //
2029 // Having at most one EH pad successor is also simpler and helps later
2030 // transformations.
2031 //
2032 // For example,
2033 // current:
2034 //   invoke void @foo to ... unwind label %catch.dispatch
2035 // catch.dispatch:
2036 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2037 // catch.start:
2038 //   ...
2039 //   ... in this BB or some other child BB dominated by this BB there will be an
2040 //   invoke that points to 'next' BB as an unwind destination
2041 //
2042 // next: ; We don't need to add this to 'current' BB's successor
2043 //   ...
2044 static void findWasmUnwindDestinations(
2045     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2046     BranchProbability Prob,
2047     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2048         &UnwindDests) {
2049   while (EHPadBB) {
2050     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2051     if (isa<CleanupPadInst>(Pad)) {
2052       // Stop on cleanup pads.
2053       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2054       UnwindDests.back().first->setIsEHScopeEntry();
2055       break;
2056     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2057       // Add the catchpad handlers to the possible destinations. We don't
2058       // continue to the unwind destination of the catchswitch for wasm.
2059       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2060         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2061         UnwindDests.back().first->setIsEHScopeEntry();
2062       }
2063       break;
2064     } else {
2065       continue;
2066     }
2067   }
2068 }
2069 
2070 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2071 /// many places it could ultimately go. In the IR, we have a single unwind
2072 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2073 /// This function skips over imaginary basic blocks that hold catchswitch
2074 /// instructions, and finds all the "real" machine
2075 /// basic block destinations. As those destinations may not be successors of
2076 /// EHPadBB, here we also calculate the edge probability to those destinations.
2077 /// The passed-in Prob is the edge probability to EHPadBB.
2078 static void findUnwindDestinations(
2079     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2080     BranchProbability Prob,
2081     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2082         &UnwindDests) {
2083   EHPersonality Personality =
2084     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2085   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2086   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2087   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2088   bool IsSEH = isAsynchronousEHPersonality(Personality);
2089 
2090   if (IsWasmCXX) {
2091     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2092     assert(UnwindDests.size() <= 1 &&
2093            "There should be at most one unwind destination for wasm");
2094     return;
2095   }
2096 
2097   while (EHPadBB) {
2098     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2099     BasicBlock *NewEHPadBB = nullptr;
2100     if (isa<LandingPadInst>(Pad)) {
2101       // Stop on landingpads. They are not funclets.
2102       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2103       break;
2104     } else if (isa<CleanupPadInst>(Pad)) {
2105       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2106       // personalities.
2107       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2108       UnwindDests.back().first->setIsEHScopeEntry();
2109       UnwindDests.back().first->setIsEHFuncletEntry();
2110       break;
2111     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2112       // Add the catchpad handlers to the possible destinations.
2113       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2114         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2115         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2116         if (IsMSVCCXX || IsCoreCLR)
2117           UnwindDests.back().first->setIsEHFuncletEntry();
2118         if (!IsSEH)
2119           UnwindDests.back().first->setIsEHScopeEntry();
2120       }
2121       NewEHPadBB = CatchSwitch->getUnwindDest();
2122     } else {
2123       continue;
2124     }
2125 
2126     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2127     if (BPI && NewEHPadBB)
2128       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2129     EHPadBB = NewEHPadBB;
2130   }
2131 }
2132 
2133 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2134   // Update successor info.
2135   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2136   auto UnwindDest = I.getUnwindDest();
2137   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2138   BranchProbability UnwindDestProb =
2139       (BPI && UnwindDest)
2140           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2141           : BranchProbability::getZero();
2142   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2143   for (auto &UnwindDest : UnwindDests) {
2144     UnwindDest.first->setIsEHPad();
2145     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2146   }
2147   FuncInfo.MBB->normalizeSuccProbs();
2148 
2149   // Create the terminator node.
2150   SDValue Ret =
2151       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2152   DAG.setRoot(Ret);
2153 }
2154 
2155 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2156   report_fatal_error("visitCatchSwitch not yet implemented!");
2157 }
2158 
2159 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2160   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2161   auto &DL = DAG.getDataLayout();
2162   SDValue Chain = getControlRoot();
2163   SmallVector<ISD::OutputArg, 8> Outs;
2164   SmallVector<SDValue, 8> OutVals;
2165 
2166   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2167   // lower
2168   //
2169   //   %val = call <ty> @llvm.experimental.deoptimize()
2170   //   ret <ty> %val
2171   //
2172   // differently.
2173   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2174     LowerDeoptimizingReturn();
2175     return;
2176   }
2177 
2178   if (!FuncInfo.CanLowerReturn) {
2179     unsigned DemoteReg = FuncInfo.DemoteRegister;
2180     const Function *F = I.getParent()->getParent();
2181 
2182     // Emit a store of the return value through the virtual register.
2183     // Leave Outs empty so that LowerReturn won't try to load return
2184     // registers the usual way.
2185     SmallVector<EVT, 1> PtrValueVTs;
2186     ComputeValueVTs(TLI, DL,
2187                     PointerType::get(F->getContext(),
2188                                      DAG.getDataLayout().getAllocaAddrSpace()),
2189                     PtrValueVTs);
2190 
2191     SDValue RetPtr =
2192         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2193     SDValue RetOp = getValue(I.getOperand(0));
2194 
2195     SmallVector<EVT, 4> ValueVTs, MemVTs;
2196     SmallVector<uint64_t, 4> Offsets;
2197     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2198                     &Offsets, 0);
2199     unsigned NumValues = ValueVTs.size();
2200 
2201     SmallVector<SDValue, 4> Chains(NumValues);
2202     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2203     for (unsigned i = 0; i != NumValues; ++i) {
2204       // An aggregate return value cannot wrap around the address space, so
2205       // offsets to its parts don't wrap either.
2206       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2207                                            TypeSize::getFixed(Offsets[i]));
2208 
2209       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2210       if (MemVTs[i] != ValueVTs[i])
2211         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2212       Chains[i] = DAG.getStore(
2213           Chain, getCurSDLoc(), Val,
2214           // FIXME: better loc info would be nice.
2215           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2216           commonAlignment(BaseAlign, Offsets[i]));
2217     }
2218 
2219     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2220                         MVT::Other, Chains);
2221   } else if (I.getNumOperands() != 0) {
2222     SmallVector<EVT, 4> ValueVTs;
2223     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2224     unsigned NumValues = ValueVTs.size();
2225     if (NumValues) {
2226       SDValue RetOp = getValue(I.getOperand(0));
2227 
2228       const Function *F = I.getParent()->getParent();
2229 
2230       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2231           I.getOperand(0)->getType(), F->getCallingConv(),
2232           /*IsVarArg*/ false, DL);
2233 
2234       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2235       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2236         ExtendKind = ISD::SIGN_EXTEND;
2237       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2238         ExtendKind = ISD::ZERO_EXTEND;
2239 
2240       LLVMContext &Context = F->getContext();
2241       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2242 
2243       for (unsigned j = 0; j != NumValues; ++j) {
2244         EVT VT = ValueVTs[j];
2245 
2246         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2247           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2248 
2249         CallingConv::ID CC = F->getCallingConv();
2250 
2251         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2252         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2253         SmallVector<SDValue, 4> Parts(NumParts);
2254         getCopyToParts(DAG, getCurSDLoc(),
2255                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2256                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2257 
2258         // 'inreg' on function refers to return value
2259         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2260         if (RetInReg)
2261           Flags.setInReg();
2262 
2263         if (I.getOperand(0)->getType()->isPointerTy()) {
2264           Flags.setPointer();
2265           Flags.setPointerAddrSpace(
2266               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2267         }
2268 
2269         if (NeedsRegBlock) {
2270           Flags.setInConsecutiveRegs();
2271           if (j == NumValues - 1)
2272             Flags.setInConsecutiveRegsLast();
2273         }
2274 
2275         // Propagate extension type if any
2276         if (ExtendKind == ISD::SIGN_EXTEND)
2277           Flags.setSExt();
2278         else if (ExtendKind == ISD::ZERO_EXTEND)
2279           Flags.setZExt();
2280 
2281         for (unsigned i = 0; i < NumParts; ++i) {
2282           Outs.push_back(ISD::OutputArg(Flags,
2283                                         Parts[i].getValueType().getSimpleVT(),
2284                                         VT, /*isfixed=*/true, 0, 0));
2285           OutVals.push_back(Parts[i]);
2286         }
2287       }
2288     }
2289   }
2290 
2291   // Push in swifterror virtual register as the last element of Outs. This makes
2292   // sure swifterror virtual register will be returned in the swifterror
2293   // physical register.
2294   const Function *F = I.getParent()->getParent();
2295   if (TLI.supportSwiftError() &&
2296       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2297     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2298     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2299     Flags.setSwiftError();
2300     Outs.push_back(ISD::OutputArg(
2301         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2302         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2303     // Create SDNode for the swifterror virtual register.
2304     OutVals.push_back(
2305         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2306                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2307                         EVT(TLI.getPointerTy(DL))));
2308   }
2309 
2310   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2311   CallingConv::ID CallConv =
2312     DAG.getMachineFunction().getFunction().getCallingConv();
2313   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2314       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2315 
2316   // Verify that the target's LowerReturn behaved as expected.
2317   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2318          "LowerReturn didn't return a valid chain!");
2319 
2320   // Update the DAG with the new chain value resulting from return lowering.
2321   DAG.setRoot(Chain);
2322 }
2323 
2324 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2325 /// created for it, emit nodes to copy the value into the virtual
2326 /// registers.
2327 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2328   // Skip empty types
2329   if (V->getType()->isEmptyTy())
2330     return;
2331 
2332   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2333   if (VMI != FuncInfo.ValueMap.end()) {
2334     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2335            "Unused value assigned virtual registers!");
2336     CopyValueToVirtualRegister(V, VMI->second);
2337   }
2338 }
2339 
2340 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2341 /// the current basic block, add it to ValueMap now so that we'll get a
2342 /// CopyTo/FromReg.
2343 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2344   // No need to export constants.
2345   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2346 
2347   // Already exported?
2348   if (FuncInfo.isExportedInst(V)) return;
2349 
2350   Register Reg = FuncInfo.InitializeRegForValue(V);
2351   CopyValueToVirtualRegister(V, Reg);
2352 }
2353 
2354 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2355                                                      const BasicBlock *FromBB) {
2356   // The operands of the setcc have to be in this block.  We don't know
2357   // how to export them from some other block.
2358   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2359     // Can export from current BB.
2360     if (VI->getParent() == FromBB)
2361       return true;
2362 
2363     // Is already exported, noop.
2364     return FuncInfo.isExportedInst(V);
2365   }
2366 
2367   // If this is an argument, we can export it if the BB is the entry block or
2368   // if it is already exported.
2369   if (isa<Argument>(V)) {
2370     if (FromBB->isEntryBlock())
2371       return true;
2372 
2373     // Otherwise, can only export this if it is already exported.
2374     return FuncInfo.isExportedInst(V);
2375   }
2376 
2377   // Otherwise, constants can always be exported.
2378   return true;
2379 }
2380 
2381 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2382 BranchProbability
2383 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2384                                         const MachineBasicBlock *Dst) const {
2385   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2386   const BasicBlock *SrcBB = Src->getBasicBlock();
2387   const BasicBlock *DstBB = Dst->getBasicBlock();
2388   if (!BPI) {
2389     // If BPI is not available, set the default probability as 1 / N, where N is
2390     // the number of successors.
2391     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2392     return BranchProbability(1, SuccSize);
2393   }
2394   return BPI->getEdgeProbability(SrcBB, DstBB);
2395 }
2396 
2397 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2398                                                MachineBasicBlock *Dst,
2399                                                BranchProbability Prob) {
2400   if (!FuncInfo.BPI)
2401     Src->addSuccessorWithoutProb(Dst);
2402   else {
2403     if (Prob.isUnknown())
2404       Prob = getEdgeProbability(Src, Dst);
2405     Src->addSuccessor(Dst, Prob);
2406   }
2407 }
2408 
2409 static bool InBlock(const Value *V, const BasicBlock *BB) {
2410   if (const Instruction *I = dyn_cast<Instruction>(V))
2411     return I->getParent() == BB;
2412   return true;
2413 }
2414 
2415 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2416 /// This function emits a branch and is used at the leaves of an OR or an
2417 /// AND operator tree.
2418 void
2419 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2420                                                   MachineBasicBlock *TBB,
2421                                                   MachineBasicBlock *FBB,
2422                                                   MachineBasicBlock *CurBB,
2423                                                   MachineBasicBlock *SwitchBB,
2424                                                   BranchProbability TProb,
2425                                                   BranchProbability FProb,
2426                                                   bool InvertCond) {
2427   const BasicBlock *BB = CurBB->getBasicBlock();
2428 
2429   // If the leaf of the tree is a comparison, merge the condition into
2430   // the caseblock.
2431   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2432     // The operands of the cmp have to be in this block.  We don't know
2433     // how to export them from some other block.  If this is the first block
2434     // of the sequence, no exporting is needed.
2435     if (CurBB == SwitchBB ||
2436         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2437          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2438       ISD::CondCode Condition;
2439       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2440         ICmpInst::Predicate Pred =
2441             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2442         Condition = getICmpCondCode(Pred);
2443       } else {
2444         const FCmpInst *FC = cast<FCmpInst>(Cond);
2445         FCmpInst::Predicate Pred =
2446             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2447         Condition = getFCmpCondCode(Pred);
2448         if (TM.Options.NoNaNsFPMath)
2449           Condition = getFCmpCodeWithoutNaN(Condition);
2450       }
2451 
2452       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2453                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2454       SL->SwitchCases.push_back(CB);
2455       return;
2456     }
2457   }
2458 
2459   // Create a CaseBlock record representing this branch.
2460   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2461   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2462                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2463   SL->SwitchCases.push_back(CB);
2464 }
2465 
2466 // Collect dependencies on V recursively. This is used for the cost analysis in
2467 // `shouldKeepJumpConditionsTogether`.
2468 static bool collectInstructionDeps(
2469     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2470     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2471     unsigned Depth = 0) {
2472   // Return false if we have an incomplete count.
2473   if (Depth >= SelectionDAG::MaxRecursionDepth)
2474     return false;
2475 
2476   auto *I = dyn_cast<Instruction>(V);
2477   if (I == nullptr)
2478     return true;
2479 
2480   if (Necessary != nullptr) {
2481     // This instruction is necessary for the other side of the condition so
2482     // don't count it.
2483     if (Necessary->contains(I))
2484       return true;
2485   }
2486 
2487   // Already added this dep.
2488   if (!Deps->try_emplace(I, false).second)
2489     return true;
2490 
2491   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2492     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2493                                 Depth + 1))
2494       return false;
2495   return true;
2496 }
2497 
2498 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2499     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2500     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2501     TargetLoweringBase::CondMergingParams Params) const {
2502   if (I.getNumSuccessors() != 2)
2503     return false;
2504 
2505   if (!I.isConditional())
2506     return false;
2507 
2508   if (Params.BaseCost < 0)
2509     return false;
2510 
2511   // Baseline cost.
2512   InstructionCost CostThresh = Params.BaseCost;
2513 
2514   BranchProbabilityInfo *BPI = nullptr;
2515   if (Params.LikelyBias || Params.UnlikelyBias)
2516     BPI = FuncInfo.BPI;
2517   if (BPI != nullptr) {
2518     // See if we are either likely to get an early out or compute both lhs/rhs
2519     // of the condition.
2520     BasicBlock *IfFalse = I.getSuccessor(0);
2521     BasicBlock *IfTrue = I.getSuccessor(1);
2522 
2523     std::optional<bool> Likely;
2524     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2525       Likely = true;
2526     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2527       Likely = false;
2528 
2529     if (Likely) {
2530       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2531         // Its likely we will have to compute both lhs and rhs of condition
2532         CostThresh += Params.LikelyBias;
2533       else {
2534         if (Params.UnlikelyBias < 0)
2535           return false;
2536         // Its likely we will get an early out.
2537         CostThresh -= Params.UnlikelyBias;
2538       }
2539     }
2540   }
2541 
2542   if (CostThresh <= 0)
2543     return false;
2544 
2545   // Collect "all" instructions that lhs condition is dependent on.
2546   // Use map for stable iteration (to avoid non-determanism of iteration of
2547   // SmallPtrSet). The `bool` value is just a dummy.
2548   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2549   collectInstructionDeps(&LhsDeps, Lhs);
2550   // Collect "all" instructions that rhs condition is dependent on AND are
2551   // dependencies of lhs. This gives us an estimate on which instructions we
2552   // stand to save by splitting the condition.
2553   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2554     return false;
2555   // Add the compare instruction itself unless its a dependency on the LHS.
2556   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2557     if (!LhsDeps.contains(RhsI))
2558       RhsDeps.try_emplace(RhsI, false);
2559 
2560   const auto &TLI = DAG.getTargetLoweringInfo();
2561   const auto &TTI =
2562       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2563 
2564   InstructionCost CostOfIncluding = 0;
2565   // See if this instruction will need to computed independently of whether RHS
2566   // is.
2567   Value *BrCond = I.getCondition();
2568   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2569     for (const auto *U : Ins->users()) {
2570       // If user is independent of RHS calculation we don't need to count it.
2571       if (auto *UIns = dyn_cast<Instruction>(U))
2572         if (UIns != BrCond && !RhsDeps.contains(UIns))
2573           return false;
2574     }
2575     return true;
2576   };
2577 
2578   // Prune instructions from RHS Deps that are dependencies of unrelated
2579   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2580   // arbitrary and just meant to cap the how much time we spend in the pruning
2581   // loop. Its highly unlikely to come into affect.
2582   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2583   // Stop after a certain point. No incorrectness from including too many
2584   // instructions.
2585   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2586     const Instruction *ToDrop = nullptr;
2587     for (const auto &InsPair : RhsDeps) {
2588       if (!ShouldCountInsn(InsPair.first)) {
2589         ToDrop = InsPair.first;
2590         break;
2591       }
2592     }
2593     if (ToDrop == nullptr)
2594       break;
2595     RhsDeps.erase(ToDrop);
2596   }
2597 
2598   for (const auto &InsPair : RhsDeps) {
2599     // Finally accumulate latency that we can only attribute to computing the
2600     // RHS condition. Use latency because we are essentially trying to calculate
2601     // the cost of the dependency chain.
2602     // Possible TODO: We could try to estimate ILP and make this more precise.
2603     CostOfIncluding +=
2604         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2605 
2606     if (CostOfIncluding > CostThresh)
2607       return false;
2608   }
2609   return true;
2610 }
2611 
2612 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2613                                                MachineBasicBlock *TBB,
2614                                                MachineBasicBlock *FBB,
2615                                                MachineBasicBlock *CurBB,
2616                                                MachineBasicBlock *SwitchBB,
2617                                                Instruction::BinaryOps Opc,
2618                                                BranchProbability TProb,
2619                                                BranchProbability FProb,
2620                                                bool InvertCond) {
2621   // Skip over not part of the tree and remember to invert op and operands at
2622   // next level.
2623   Value *NotCond;
2624   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2625       InBlock(NotCond, CurBB->getBasicBlock())) {
2626     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2627                          !InvertCond);
2628     return;
2629   }
2630 
2631   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2632   const Value *BOpOp0, *BOpOp1;
2633   // Compute the effective opcode for Cond, taking into account whether it needs
2634   // to be inverted, e.g.
2635   //   and (not (or A, B)), C
2636   // gets lowered as
2637   //   and (and (not A, not B), C)
2638   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2639   if (BOp) {
2640     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2641                ? Instruction::And
2642                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2643                       ? Instruction::Or
2644                       : (Instruction::BinaryOps)0);
2645     if (InvertCond) {
2646       if (BOpc == Instruction::And)
2647         BOpc = Instruction::Or;
2648       else if (BOpc == Instruction::Or)
2649         BOpc = Instruction::And;
2650     }
2651   }
2652 
2653   // If this node is not part of the or/and tree, emit it as a branch.
2654   // Note that all nodes in the tree should have same opcode.
2655   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2656   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2657       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2658       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2659     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2660                                  TProb, FProb, InvertCond);
2661     return;
2662   }
2663 
2664   //  Create TmpBB after CurBB.
2665   MachineFunction::iterator BBI(CurBB);
2666   MachineFunction &MF = DAG.getMachineFunction();
2667   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2668   CurBB->getParent()->insert(++BBI, TmpBB);
2669 
2670   if (Opc == Instruction::Or) {
2671     // Codegen X | Y as:
2672     // BB1:
2673     //   jmp_if_X TBB
2674     //   jmp TmpBB
2675     // TmpBB:
2676     //   jmp_if_Y TBB
2677     //   jmp FBB
2678     //
2679 
2680     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2681     // The requirement is that
2682     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2683     //     = TrueProb for original BB.
2684     // Assuming the original probabilities are A and B, one choice is to set
2685     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2686     // A/(1+B) and 2B/(1+B). This choice assumes that
2687     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2688     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2689     // TmpBB, but the math is more complicated.
2690 
2691     auto NewTrueProb = TProb / 2;
2692     auto NewFalseProb = TProb / 2 + FProb;
2693     // Emit the LHS condition.
2694     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2695                          NewFalseProb, InvertCond);
2696 
2697     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2698     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2699     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2700     // Emit the RHS condition into TmpBB.
2701     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2702                          Probs[1], InvertCond);
2703   } else {
2704     assert(Opc == Instruction::And && "Unknown merge op!");
2705     // Codegen X & Y as:
2706     // BB1:
2707     //   jmp_if_X TmpBB
2708     //   jmp FBB
2709     // TmpBB:
2710     //   jmp_if_Y TBB
2711     //   jmp FBB
2712     //
2713     //  This requires creation of TmpBB after CurBB.
2714 
2715     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2716     // The requirement is that
2717     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2718     //     = FalseProb for original BB.
2719     // Assuming the original probabilities are A and B, one choice is to set
2720     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2721     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2722     // TrueProb for BB1 * FalseProb for TmpBB.
2723 
2724     auto NewTrueProb = TProb + FProb / 2;
2725     auto NewFalseProb = FProb / 2;
2726     // Emit the LHS condition.
2727     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2728                          NewFalseProb, InvertCond);
2729 
2730     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2731     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2732     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2733     // Emit the RHS condition into TmpBB.
2734     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2735                          Probs[1], InvertCond);
2736   }
2737 }
2738 
2739 /// If the set of cases should be emitted as a series of branches, return true.
2740 /// If we should emit this as a bunch of and/or'd together conditions, return
2741 /// false.
2742 bool
2743 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2744   if (Cases.size() != 2) return true;
2745 
2746   // If this is two comparisons of the same values or'd or and'd together, they
2747   // will get folded into a single comparison, so don't emit two blocks.
2748   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2749        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2750       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2751        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2752     return false;
2753   }
2754 
2755   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2756   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2757   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2758       Cases[0].CC == Cases[1].CC &&
2759       isa<Constant>(Cases[0].CmpRHS) &&
2760       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2761     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2762       return false;
2763     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2764       return false;
2765   }
2766 
2767   return true;
2768 }
2769 
2770 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2771   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2772 
2773   // Update machine-CFG edges.
2774   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2775 
2776   if (I.isUnconditional()) {
2777     // Update machine-CFG edges.
2778     BrMBB->addSuccessor(Succ0MBB);
2779 
2780     // If this is not a fall-through branch or optimizations are switched off,
2781     // emit the branch.
2782     if (Succ0MBB != NextBlock(BrMBB) ||
2783         TM.getOptLevel() == CodeGenOptLevel::None) {
2784       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2785                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2786       setValue(&I, Br);
2787       DAG.setRoot(Br);
2788     }
2789 
2790     return;
2791   }
2792 
2793   // If this condition is one of the special cases we handle, do special stuff
2794   // now.
2795   const Value *CondVal = I.getCondition();
2796   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2797 
2798   // If this is a series of conditions that are or'd or and'd together, emit
2799   // this as a sequence of branches instead of setcc's with and/or operations.
2800   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2801   // unpredictable branches, and vector extracts because those jumps are likely
2802   // expensive for any target), this should improve performance.
2803   // For example, instead of something like:
2804   //     cmp A, B
2805   //     C = seteq
2806   //     cmp D, E
2807   //     F = setle
2808   //     or C, F
2809   //     jnz foo
2810   // Emit:
2811   //     cmp A, B
2812   //     je foo
2813   //     cmp D, E
2814   //     jle foo
2815   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2816   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2817       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2818     Value *Vec;
2819     const Value *BOp0, *BOp1;
2820     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2821     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2822       Opcode = Instruction::And;
2823     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2824       Opcode = Instruction::Or;
2825 
2826     if (Opcode &&
2827         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2828           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2829         !shouldKeepJumpConditionsTogether(
2830             FuncInfo, I, Opcode, BOp0, BOp1,
2831             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2832                 Opcode, BOp0, BOp1))) {
2833       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2834                            getEdgeProbability(BrMBB, Succ0MBB),
2835                            getEdgeProbability(BrMBB, Succ1MBB),
2836                            /*InvertCond=*/false);
2837       // If the compares in later blocks need to use values not currently
2838       // exported from this block, export them now.  This block should always
2839       // be the first entry.
2840       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2841 
2842       // Allow some cases to be rejected.
2843       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2844         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2845           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2846           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2847         }
2848 
2849         // Emit the branch for this block.
2850         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2851         SL->SwitchCases.erase(SL->SwitchCases.begin());
2852         return;
2853       }
2854 
2855       // Okay, we decided not to do this, remove any inserted MBB's and clear
2856       // SwitchCases.
2857       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2858         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2859 
2860       SL->SwitchCases.clear();
2861     }
2862   }
2863 
2864   // Create a CaseBlock record representing this branch.
2865   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2866                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2867 
2868   // Use visitSwitchCase to actually insert the fast branch sequence for this
2869   // cond branch.
2870   visitSwitchCase(CB, BrMBB);
2871 }
2872 
2873 /// visitSwitchCase - Emits the necessary code to represent a single node in
2874 /// the binary search tree resulting from lowering a switch instruction.
2875 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2876                                           MachineBasicBlock *SwitchBB) {
2877   SDValue Cond;
2878   SDValue CondLHS = getValue(CB.CmpLHS);
2879   SDLoc dl = CB.DL;
2880 
2881   if (CB.CC == ISD::SETTRUE) {
2882     // Branch or fall through to TrueBB.
2883     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2884     SwitchBB->normalizeSuccProbs();
2885     if (CB.TrueBB != NextBlock(SwitchBB)) {
2886       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2887                               DAG.getBasicBlock(CB.TrueBB)));
2888     }
2889     return;
2890   }
2891 
2892   auto &TLI = DAG.getTargetLoweringInfo();
2893   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2894 
2895   // Build the setcc now.
2896   if (!CB.CmpMHS) {
2897     // Fold "(X == true)" to X and "(X == false)" to !X to
2898     // handle common cases produced by branch lowering.
2899     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2900         CB.CC == ISD::SETEQ)
2901       Cond = CondLHS;
2902     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2903              CB.CC == ISD::SETEQ) {
2904       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2905       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2906     } else {
2907       SDValue CondRHS = getValue(CB.CmpRHS);
2908 
2909       // If a pointer's DAG type is larger than its memory type then the DAG
2910       // values are zero-extended. This breaks signed comparisons so truncate
2911       // back to the underlying type before doing the compare.
2912       if (CondLHS.getValueType() != MemVT) {
2913         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2914         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2915       }
2916       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2917     }
2918   } else {
2919     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2920 
2921     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2922     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2923 
2924     SDValue CmpOp = getValue(CB.CmpMHS);
2925     EVT VT = CmpOp.getValueType();
2926 
2927     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2928       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2929                           ISD::SETLE);
2930     } else {
2931       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2932                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2933       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2934                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2935     }
2936   }
2937 
2938   // Update successor info
2939   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2940   // TrueBB and FalseBB are always different unless the incoming IR is
2941   // degenerate. This only happens when running llc on weird IR.
2942   if (CB.TrueBB != CB.FalseBB)
2943     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2944   SwitchBB->normalizeSuccProbs();
2945 
2946   // If the lhs block is the next block, invert the condition so that we can
2947   // fall through to the lhs instead of the rhs block.
2948   if (CB.TrueBB == NextBlock(SwitchBB)) {
2949     std::swap(CB.TrueBB, CB.FalseBB);
2950     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2951     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2952   }
2953 
2954   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2955                                MVT::Other, getControlRoot(), Cond,
2956                                DAG.getBasicBlock(CB.TrueBB));
2957 
2958   setValue(CurInst, BrCond);
2959 
2960   // Insert the false branch. Do this even if it's a fall through branch,
2961   // this makes it easier to do DAG optimizations which require inverting
2962   // the branch condition.
2963   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2964                        DAG.getBasicBlock(CB.FalseBB));
2965 
2966   DAG.setRoot(BrCond);
2967 }
2968 
2969 /// visitJumpTable - Emit JumpTable node in the current MBB
2970 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2971   // Emit the code for the jump table
2972   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2973   assert(JT.Reg != -1U && "Should lower JT Header first!");
2974   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2975   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2976   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2977   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2978                                     Index.getValue(1), Table, Index);
2979   DAG.setRoot(BrJumpTable);
2980 }
2981 
2982 /// visitJumpTableHeader - This function emits necessary code to produce index
2983 /// in the JumpTable from switch case.
2984 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2985                                                JumpTableHeader &JTH,
2986                                                MachineBasicBlock *SwitchBB) {
2987   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2988   const SDLoc &dl = *JT.SL;
2989 
2990   // Subtract the lowest switch case value from the value being switched on.
2991   SDValue SwitchOp = getValue(JTH.SValue);
2992   EVT VT = SwitchOp.getValueType();
2993   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
2994                             DAG.getConstant(JTH.First, dl, VT));
2995 
2996   // The SDNode we just created, which holds the value being switched on minus
2997   // the smallest case value, needs to be copied to a virtual register so it
2998   // can be used as an index into the jump table in a subsequent basic block.
2999   // This value may be smaller or larger than the target's pointer type, and
3000   // therefore require extension or truncating.
3001   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3002   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
3003 
3004   unsigned JumpTableReg =
3005       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
3006   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
3007                                     JumpTableReg, SwitchOp);
3008   JT.Reg = JumpTableReg;
3009 
3010   if (!JTH.FallthroughUnreachable) {
3011     // Emit the range check for the jump table, and branch to the default block
3012     // for the switch statement if the value being switched on exceeds the
3013     // largest case in the switch.
3014     SDValue CMP = DAG.getSetCC(
3015         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3016                                    Sub.getValueType()),
3017         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3018 
3019     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3020                                  MVT::Other, CopyTo, CMP,
3021                                  DAG.getBasicBlock(JT.Default));
3022 
3023     // Avoid emitting unnecessary branches to the next block.
3024     if (JT.MBB != NextBlock(SwitchBB))
3025       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3026                            DAG.getBasicBlock(JT.MBB));
3027 
3028     DAG.setRoot(BrCond);
3029   } else {
3030     // Avoid emitting unnecessary branches to the next block.
3031     if (JT.MBB != NextBlock(SwitchBB))
3032       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3033                               DAG.getBasicBlock(JT.MBB)));
3034     else
3035       DAG.setRoot(CopyTo);
3036   }
3037 }
3038 
3039 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3040 /// variable if there exists one.
3041 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3042                                  SDValue &Chain) {
3043   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3044   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3045   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3046   MachineFunction &MF = DAG.getMachineFunction();
3047   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3048   MachineSDNode *Node =
3049       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3050   if (Global) {
3051     MachinePointerInfo MPInfo(Global);
3052     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3053                  MachineMemOperand::MODereferenceable;
3054     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3055         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3056         DAG.getEVTAlign(PtrTy));
3057     DAG.setNodeMemRefs(Node, {MemRef});
3058   }
3059   if (PtrTy != PtrMemTy)
3060     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3061   return SDValue(Node, 0);
3062 }
3063 
3064 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3065 /// tail spliced into a stack protector check success bb.
3066 ///
3067 /// For a high level explanation of how this fits into the stack protector
3068 /// generation see the comment on the declaration of class
3069 /// StackProtectorDescriptor.
3070 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3071                                                   MachineBasicBlock *ParentBB) {
3072 
3073   // First create the loads to the guard/stack slot for the comparison.
3074   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3075   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3076   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3077 
3078   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3079   int FI = MFI.getStackProtectorIndex();
3080 
3081   SDValue Guard;
3082   SDLoc dl = getCurSDLoc();
3083   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3084   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3085   Align Align =
3086       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3087 
3088   // Generate code to load the content of the guard slot.
3089   SDValue GuardVal = DAG.getLoad(
3090       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3091       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3092       MachineMemOperand::MOVolatile);
3093 
3094   if (TLI.useStackGuardXorFP())
3095     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3096 
3097   // Retrieve guard check function, nullptr if instrumentation is inlined.
3098   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3099     // The target provides a guard check function to validate the guard value.
3100     // Generate a call to that function with the content of the guard slot as
3101     // argument.
3102     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3103     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3104 
3105     TargetLowering::ArgListTy Args;
3106     TargetLowering::ArgListEntry Entry;
3107     Entry.Node = GuardVal;
3108     Entry.Ty = FnTy->getParamType(0);
3109     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3110       Entry.IsInReg = true;
3111     Args.push_back(Entry);
3112 
3113     TargetLowering::CallLoweringInfo CLI(DAG);
3114     CLI.setDebugLoc(getCurSDLoc())
3115         .setChain(DAG.getEntryNode())
3116         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3117                    getValue(GuardCheckFn), std::move(Args));
3118 
3119     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3120     DAG.setRoot(Result.second);
3121     return;
3122   }
3123 
3124   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3125   // Otherwise, emit a volatile load to retrieve the stack guard value.
3126   SDValue Chain = DAG.getEntryNode();
3127   if (TLI.useLoadStackGuardNode()) {
3128     Guard = getLoadStackGuard(DAG, dl, Chain);
3129   } else {
3130     const Value *IRGuard = TLI.getSDagStackGuard(M);
3131     SDValue GuardPtr = getValue(IRGuard);
3132 
3133     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3134                         MachinePointerInfo(IRGuard, 0), Align,
3135                         MachineMemOperand::MOVolatile);
3136   }
3137 
3138   // Perform the comparison via a getsetcc.
3139   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3140                                                         *DAG.getContext(),
3141                                                         Guard.getValueType()),
3142                              Guard, GuardVal, ISD::SETNE);
3143 
3144   // If the guard/stackslot do not equal, branch to failure MBB.
3145   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3146                                MVT::Other, GuardVal.getOperand(0),
3147                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3148   // Otherwise branch to success MBB.
3149   SDValue Br = DAG.getNode(ISD::BR, dl,
3150                            MVT::Other, BrCond,
3151                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3152 
3153   DAG.setRoot(Br);
3154 }
3155 
3156 /// Codegen the failure basic block for a stack protector check.
3157 ///
3158 /// A failure stack protector machine basic block consists simply of a call to
3159 /// __stack_chk_fail().
3160 ///
3161 /// For a high level explanation of how this fits into the stack protector
3162 /// generation see the comment on the declaration of class
3163 /// StackProtectorDescriptor.
3164 void
3165 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3166   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3167   TargetLowering::MakeLibCallOptions CallOptions;
3168   CallOptions.setDiscardResult(true);
3169   SDValue Chain =
3170       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3171                       std::nullopt, CallOptions, getCurSDLoc())
3172           .second;
3173   // On PS4/PS5, the "return address" must still be within the calling
3174   // function, even if it's at the very end, so emit an explicit TRAP here.
3175   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3176   if (TM.getTargetTriple().isPS())
3177     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3178   // WebAssembly needs an unreachable instruction after a non-returning call,
3179   // because the function return type can be different from __stack_chk_fail's
3180   // return type (void).
3181   if (TM.getTargetTriple().isWasm())
3182     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3183 
3184   DAG.setRoot(Chain);
3185 }
3186 
3187 /// visitBitTestHeader - This function emits necessary code to produce value
3188 /// suitable for "bit tests"
3189 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3190                                              MachineBasicBlock *SwitchBB) {
3191   SDLoc dl = getCurSDLoc();
3192 
3193   // Subtract the minimum value.
3194   SDValue SwitchOp = getValue(B.SValue);
3195   EVT VT = SwitchOp.getValueType();
3196   SDValue RangeSub =
3197       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3198 
3199   // Determine the type of the test operands.
3200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3201   bool UsePtrType = false;
3202   if (!TLI.isTypeLegal(VT)) {
3203     UsePtrType = true;
3204   } else {
3205     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3206       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3207         // Switch table case range are encoded into series of masks.
3208         // Just use pointer type, it's guaranteed to fit.
3209         UsePtrType = true;
3210         break;
3211       }
3212   }
3213   SDValue Sub = RangeSub;
3214   if (UsePtrType) {
3215     VT = TLI.getPointerTy(DAG.getDataLayout());
3216     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3217   }
3218 
3219   B.RegVT = VT.getSimpleVT();
3220   B.Reg = FuncInfo.CreateReg(B.RegVT);
3221   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3222 
3223   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3224 
3225   if (!B.FallthroughUnreachable)
3226     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3227   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3228   SwitchBB->normalizeSuccProbs();
3229 
3230   SDValue Root = CopyTo;
3231   if (!B.FallthroughUnreachable) {
3232     // Conditional branch to the default block.
3233     SDValue RangeCmp = DAG.getSetCC(dl,
3234         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3235                                RangeSub.getValueType()),
3236         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3237         ISD::SETUGT);
3238 
3239     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3240                        DAG.getBasicBlock(B.Default));
3241   }
3242 
3243   // Avoid emitting unnecessary branches to the next block.
3244   if (MBB != NextBlock(SwitchBB))
3245     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3246 
3247   DAG.setRoot(Root);
3248 }
3249 
3250 /// visitBitTestCase - this function produces one "bit test"
3251 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3252                                            MachineBasicBlock* NextMBB,
3253                                            BranchProbability BranchProbToNext,
3254                                            unsigned Reg,
3255                                            BitTestCase &B,
3256                                            MachineBasicBlock *SwitchBB) {
3257   SDLoc dl = getCurSDLoc();
3258   MVT VT = BB.RegVT;
3259   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3260   SDValue Cmp;
3261   unsigned PopCount = llvm::popcount(B.Mask);
3262   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3263   if (PopCount == 1) {
3264     // Testing for a single bit; just compare the shift count with what it
3265     // would need to be to shift a 1 bit in that position.
3266     Cmp = DAG.getSetCC(
3267         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3268         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3269         ISD::SETEQ);
3270   } else if (PopCount == BB.Range) {
3271     // There is only one zero bit in the range, test for it directly.
3272     Cmp = DAG.getSetCC(
3273         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3274         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3275   } else {
3276     // Make desired shift
3277     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3278                                     DAG.getConstant(1, dl, VT), ShiftOp);
3279 
3280     // Emit bit tests and jumps
3281     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3282                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3283     Cmp = DAG.getSetCC(
3284         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3285         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3286   }
3287 
3288   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3289   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3290   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3291   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3292   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3293   // one as they are relative probabilities (and thus work more like weights),
3294   // and hence we need to normalize them to let the sum of them become one.
3295   SwitchBB->normalizeSuccProbs();
3296 
3297   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3298                               MVT::Other, getControlRoot(),
3299                               Cmp, DAG.getBasicBlock(B.TargetBB));
3300 
3301   // Avoid emitting unnecessary branches to the next block.
3302   if (NextMBB != NextBlock(SwitchBB))
3303     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3304                         DAG.getBasicBlock(NextMBB));
3305 
3306   DAG.setRoot(BrAnd);
3307 }
3308 
3309 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3310   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3311 
3312   // Retrieve successors. Look through artificial IR level blocks like
3313   // catchswitch for successors.
3314   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3315   const BasicBlock *EHPadBB = I.getSuccessor(1);
3316   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3317 
3318   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3319   // have to do anything here to lower funclet bundles.
3320   assert(!I.hasOperandBundlesOtherThan(
3321              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3322               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3323               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3324               LLVMContext::OB_clang_arc_attachedcall}) &&
3325          "Cannot lower invokes with arbitrary operand bundles yet!");
3326 
3327   const Value *Callee(I.getCalledOperand());
3328   const Function *Fn = dyn_cast<Function>(Callee);
3329   if (isa<InlineAsm>(Callee))
3330     visitInlineAsm(I, EHPadBB);
3331   else if (Fn && Fn->isIntrinsic()) {
3332     switch (Fn->getIntrinsicID()) {
3333     default:
3334       llvm_unreachable("Cannot invoke this intrinsic");
3335     case Intrinsic::donothing:
3336       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3337     case Intrinsic::seh_try_begin:
3338     case Intrinsic::seh_scope_begin:
3339     case Intrinsic::seh_try_end:
3340     case Intrinsic::seh_scope_end:
3341       if (EHPadMBB)
3342           // a block referenced by EH table
3343           // so dtor-funclet not removed by opts
3344           EHPadMBB->setMachineBlockAddressTaken();
3345       break;
3346     case Intrinsic::experimental_patchpoint_void:
3347     case Intrinsic::experimental_patchpoint:
3348       visitPatchpoint(I, EHPadBB);
3349       break;
3350     case Intrinsic::experimental_gc_statepoint:
3351       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3352       break;
3353     case Intrinsic::wasm_rethrow: {
3354       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3355       // special because it can be invoked, so we manually lower it to a DAG
3356       // node here.
3357       SmallVector<SDValue, 8> Ops;
3358       Ops.push_back(getControlRoot()); // inchain for the terminator node
3359       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3360       Ops.push_back(
3361           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3362                                 TLI.getPointerTy(DAG.getDataLayout())));
3363       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3364       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3365       break;
3366     }
3367     }
3368   } else if (I.hasDeoptState()) {
3369     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3370     // Eventually we will support lowering the @llvm.experimental.deoptimize
3371     // intrinsic, and right now there are no plans to support other intrinsics
3372     // with deopt state.
3373     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3374   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3375     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3376   } else {
3377     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3378   }
3379 
3380   // If the value of the invoke is used outside of its defining block, make it
3381   // available as a virtual register.
3382   // We already took care of the exported value for the statepoint instruction
3383   // during call to the LowerStatepoint.
3384   if (!isa<GCStatepointInst>(I)) {
3385     CopyToExportRegsIfNeeded(&I);
3386   }
3387 
3388   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3389   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3390   BranchProbability EHPadBBProb =
3391       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3392           : BranchProbability::getZero();
3393   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3394 
3395   // Update successor info.
3396   addSuccessorWithProb(InvokeMBB, Return);
3397   for (auto &UnwindDest : UnwindDests) {
3398     UnwindDest.first->setIsEHPad();
3399     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3400   }
3401   InvokeMBB->normalizeSuccProbs();
3402 
3403   // Drop into normal successor.
3404   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3405                           DAG.getBasicBlock(Return)));
3406 }
3407 
3408 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3409   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3410 
3411   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3412   // have to do anything here to lower funclet bundles.
3413   assert(!I.hasOperandBundlesOtherThan(
3414              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3415          "Cannot lower callbrs with arbitrary operand bundles yet!");
3416 
3417   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3418   visitInlineAsm(I);
3419   CopyToExportRegsIfNeeded(&I);
3420 
3421   // Retrieve successors.
3422   SmallPtrSet<BasicBlock *, 8> Dests;
3423   Dests.insert(I.getDefaultDest());
3424   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3425 
3426   // Update successor info.
3427   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3428   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3429     BasicBlock *Dest = I.getIndirectDest(i);
3430     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3431     Target->setIsInlineAsmBrIndirectTarget();
3432     Target->setMachineBlockAddressTaken();
3433     Target->setLabelMustBeEmitted();
3434     // Don't add duplicate machine successors.
3435     if (Dests.insert(Dest).second)
3436       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3437   }
3438   CallBrMBB->normalizeSuccProbs();
3439 
3440   // Drop into default successor.
3441   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3442                           MVT::Other, getControlRoot(),
3443                           DAG.getBasicBlock(Return)));
3444 }
3445 
3446 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3447   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3448 }
3449 
3450 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3451   assert(FuncInfo.MBB->isEHPad() &&
3452          "Call to landingpad not in landing pad!");
3453 
3454   // If there aren't registers to copy the values into (e.g., during SjLj
3455   // exceptions), then don't bother to create these DAG nodes.
3456   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3457   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3458   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3459       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3460     return;
3461 
3462   // If landingpad's return type is token type, we don't create DAG nodes
3463   // for its exception pointer and selector value. The extraction of exception
3464   // pointer or selector value from token type landingpads is not currently
3465   // supported.
3466   if (LP.getType()->isTokenTy())
3467     return;
3468 
3469   SmallVector<EVT, 2> ValueVTs;
3470   SDLoc dl = getCurSDLoc();
3471   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3472   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3473 
3474   // Get the two live-in registers as SDValues. The physregs have already been
3475   // copied into virtual registers.
3476   SDValue Ops[2];
3477   if (FuncInfo.ExceptionPointerVirtReg) {
3478     Ops[0] = DAG.getZExtOrTrunc(
3479         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3480                            FuncInfo.ExceptionPointerVirtReg,
3481                            TLI.getPointerTy(DAG.getDataLayout())),
3482         dl, ValueVTs[0]);
3483   } else {
3484     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3485   }
3486   Ops[1] = DAG.getZExtOrTrunc(
3487       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3488                          FuncInfo.ExceptionSelectorVirtReg,
3489                          TLI.getPointerTy(DAG.getDataLayout())),
3490       dl, ValueVTs[1]);
3491 
3492   // Merge into one.
3493   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3494                             DAG.getVTList(ValueVTs), Ops);
3495   setValue(&LP, Res);
3496 }
3497 
3498 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3499                                            MachineBasicBlock *Last) {
3500   // Update JTCases.
3501   for (JumpTableBlock &JTB : SL->JTCases)
3502     if (JTB.first.HeaderBB == First)
3503       JTB.first.HeaderBB = Last;
3504 
3505   // Update BitTestCases.
3506   for (BitTestBlock &BTB : SL->BitTestCases)
3507     if (BTB.Parent == First)
3508       BTB.Parent = Last;
3509 }
3510 
3511 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3512   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3513 
3514   // Update machine-CFG edges with unique successors.
3515   SmallSet<BasicBlock*, 32> Done;
3516   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3517     BasicBlock *BB = I.getSuccessor(i);
3518     bool Inserted = Done.insert(BB).second;
3519     if (!Inserted)
3520         continue;
3521 
3522     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3523     addSuccessorWithProb(IndirectBrMBB, Succ);
3524   }
3525   IndirectBrMBB->normalizeSuccProbs();
3526 
3527   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3528                           MVT::Other, getControlRoot(),
3529                           getValue(I.getAddress())));
3530 }
3531 
3532 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3533   if (!DAG.getTarget().Options.TrapUnreachable)
3534     return;
3535 
3536   // We may be able to ignore unreachable behind a noreturn call.
3537   if (DAG.getTarget().Options.NoTrapAfterNoreturn) {
3538     if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode())) {
3539       if (Call->doesNotReturn())
3540         return;
3541     }
3542   }
3543 
3544   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3545 }
3546 
3547 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3548   SDNodeFlags Flags;
3549   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3550     Flags.copyFMF(*FPOp);
3551 
3552   SDValue Op = getValue(I.getOperand(0));
3553   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3554                                     Op, Flags);
3555   setValue(&I, UnNodeValue);
3556 }
3557 
3558 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3559   SDNodeFlags Flags;
3560   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3561     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3562     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3563   }
3564   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3565     Flags.setExact(ExactOp->isExact());
3566   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3567     Flags.setDisjoint(DisjointOp->isDisjoint());
3568   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3569     Flags.copyFMF(*FPOp);
3570 
3571   SDValue Op1 = getValue(I.getOperand(0));
3572   SDValue Op2 = getValue(I.getOperand(1));
3573   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3574                                      Op1, Op2, Flags);
3575   setValue(&I, BinNodeValue);
3576 }
3577 
3578 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3579   SDValue Op1 = getValue(I.getOperand(0));
3580   SDValue Op2 = getValue(I.getOperand(1));
3581 
3582   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3583       Op1.getValueType(), DAG.getDataLayout());
3584 
3585   // Coerce the shift amount to the right type if we can. This exposes the
3586   // truncate or zext to optimization early.
3587   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3588     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3589            "Unexpected shift type");
3590     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3591   }
3592 
3593   bool nuw = false;
3594   bool nsw = false;
3595   bool exact = false;
3596 
3597   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3598 
3599     if (const OverflowingBinaryOperator *OFBinOp =
3600             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3601       nuw = OFBinOp->hasNoUnsignedWrap();
3602       nsw = OFBinOp->hasNoSignedWrap();
3603     }
3604     if (const PossiblyExactOperator *ExactOp =
3605             dyn_cast<const PossiblyExactOperator>(&I))
3606       exact = ExactOp->isExact();
3607   }
3608   SDNodeFlags Flags;
3609   Flags.setExact(exact);
3610   Flags.setNoSignedWrap(nsw);
3611   Flags.setNoUnsignedWrap(nuw);
3612   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3613                             Flags);
3614   setValue(&I, Res);
3615 }
3616 
3617 void SelectionDAGBuilder::visitSDiv(const User &I) {
3618   SDValue Op1 = getValue(I.getOperand(0));
3619   SDValue Op2 = getValue(I.getOperand(1));
3620 
3621   SDNodeFlags Flags;
3622   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3623                  cast<PossiblyExactOperator>(&I)->isExact());
3624   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3625                            Op2, Flags));
3626 }
3627 
3628 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3629   ICmpInst::Predicate predicate = I.getPredicate();
3630   SDValue Op1 = getValue(I.getOperand(0));
3631   SDValue Op2 = getValue(I.getOperand(1));
3632   ISD::CondCode Opcode = getICmpCondCode(predicate);
3633 
3634   auto &TLI = DAG.getTargetLoweringInfo();
3635   EVT MemVT =
3636       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3637 
3638   // If a pointer's DAG type is larger than its memory type then the DAG values
3639   // are zero-extended. This breaks signed comparisons so truncate back to the
3640   // underlying type before doing the compare.
3641   if (Op1.getValueType() != MemVT) {
3642     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3643     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3644   }
3645 
3646   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3647                                                         I.getType());
3648   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3649 }
3650 
3651 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3652   FCmpInst::Predicate predicate = I.getPredicate();
3653   SDValue Op1 = getValue(I.getOperand(0));
3654   SDValue Op2 = getValue(I.getOperand(1));
3655 
3656   ISD::CondCode Condition = getFCmpCondCode(predicate);
3657   auto *FPMO = cast<FPMathOperator>(&I);
3658   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3659     Condition = getFCmpCodeWithoutNaN(Condition);
3660 
3661   SDNodeFlags Flags;
3662   Flags.copyFMF(*FPMO);
3663   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3664 
3665   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3666                                                         I.getType());
3667   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3668 }
3669 
3670 // Check if the condition of the select has one use or two users that are both
3671 // selects with the same condition.
3672 static bool hasOnlySelectUsers(const Value *Cond) {
3673   return llvm::all_of(Cond->users(), [](const Value *V) {
3674     return isa<SelectInst>(V);
3675   });
3676 }
3677 
3678 void SelectionDAGBuilder::visitSelect(const User &I) {
3679   SmallVector<EVT, 4> ValueVTs;
3680   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3681                   ValueVTs);
3682   unsigned NumValues = ValueVTs.size();
3683   if (NumValues == 0) return;
3684 
3685   SmallVector<SDValue, 4> Values(NumValues);
3686   SDValue Cond     = getValue(I.getOperand(0));
3687   SDValue LHSVal   = getValue(I.getOperand(1));
3688   SDValue RHSVal   = getValue(I.getOperand(2));
3689   SmallVector<SDValue, 1> BaseOps(1, Cond);
3690   ISD::NodeType OpCode =
3691       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3692 
3693   bool IsUnaryAbs = false;
3694   bool Negate = false;
3695 
3696   SDNodeFlags Flags;
3697   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3698     Flags.copyFMF(*FPOp);
3699 
3700   Flags.setUnpredictable(
3701       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3702 
3703   // Min/max matching is only viable if all output VTs are the same.
3704   if (all_equal(ValueVTs)) {
3705     EVT VT = ValueVTs[0];
3706     LLVMContext &Ctx = *DAG.getContext();
3707     auto &TLI = DAG.getTargetLoweringInfo();
3708 
3709     // We care about the legality of the operation after it has been type
3710     // legalized.
3711     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3712       VT = TLI.getTypeToTransformTo(Ctx, VT);
3713 
3714     // If the vselect is legal, assume we want to leave this as a vector setcc +
3715     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3716     // min/max is legal on the scalar type.
3717     bool UseScalarMinMax = VT.isVector() &&
3718       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3719 
3720     // ValueTracking's select pattern matching does not account for -0.0,
3721     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3722     // -0.0 is less than +0.0.
3723     Value *LHS, *RHS;
3724     auto SPR = matchSelectPattern(const_cast<User*>(&I), LHS, RHS);
3725     ISD::NodeType Opc = ISD::DELETED_NODE;
3726     switch (SPR.Flavor) {
3727     case SPF_UMAX:    Opc = ISD::UMAX; break;
3728     case SPF_UMIN:    Opc = ISD::UMIN; break;
3729     case SPF_SMAX:    Opc = ISD::SMAX; break;
3730     case SPF_SMIN:    Opc = ISD::SMIN; break;
3731     case SPF_FMINNUM:
3732       switch (SPR.NaNBehavior) {
3733       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3734       case SPNB_RETURNS_NAN: break;
3735       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3736       case SPNB_RETURNS_ANY:
3737         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3738             (UseScalarMinMax &&
3739              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3740           Opc = ISD::FMINNUM;
3741         break;
3742       }
3743       break;
3744     case SPF_FMAXNUM:
3745       switch (SPR.NaNBehavior) {
3746       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3747       case SPNB_RETURNS_NAN: break;
3748       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3749       case SPNB_RETURNS_ANY:
3750         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3751             (UseScalarMinMax &&
3752              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3753           Opc = ISD::FMAXNUM;
3754         break;
3755       }
3756       break;
3757     case SPF_NABS:
3758       Negate = true;
3759       [[fallthrough]];
3760     case SPF_ABS:
3761       IsUnaryAbs = true;
3762       Opc = ISD::ABS;
3763       break;
3764     default: break;
3765     }
3766 
3767     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3768         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3769          (UseScalarMinMax &&
3770           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3771         // If the underlying comparison instruction is used by any other
3772         // instruction, the consumed instructions won't be destroyed, so it is
3773         // not profitable to convert to a min/max.
3774         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3775       OpCode = Opc;
3776       LHSVal = getValue(LHS);
3777       RHSVal = getValue(RHS);
3778       BaseOps.clear();
3779     }
3780 
3781     if (IsUnaryAbs) {
3782       OpCode = Opc;
3783       LHSVal = getValue(LHS);
3784       BaseOps.clear();
3785     }
3786   }
3787 
3788   if (IsUnaryAbs) {
3789     for (unsigned i = 0; i != NumValues; ++i) {
3790       SDLoc dl = getCurSDLoc();
3791       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3792       Values[i] =
3793           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3794       if (Negate)
3795         Values[i] = DAG.getNegative(Values[i], dl, VT);
3796     }
3797   } else {
3798     for (unsigned i = 0; i != NumValues; ++i) {
3799       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3800       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3801       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3802       Values[i] = DAG.getNode(
3803           OpCode, getCurSDLoc(),
3804           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3805     }
3806   }
3807 
3808   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3809                            DAG.getVTList(ValueVTs), Values));
3810 }
3811 
3812 void SelectionDAGBuilder::visitTrunc(const User &I) {
3813   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3814   SDValue N = getValue(I.getOperand(0));
3815   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3816                                                         I.getType());
3817   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3818 }
3819 
3820 void SelectionDAGBuilder::visitZExt(const User &I) {
3821   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3822   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3823   SDValue N = getValue(I.getOperand(0));
3824   auto &TLI = DAG.getTargetLoweringInfo();
3825   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3826 
3827   SDNodeFlags Flags;
3828   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3829     Flags.setNonNeg(PNI->hasNonNeg());
3830 
3831   // Eagerly use nonneg information to canonicalize towards sign_extend if
3832   // that is the target's preference.
3833   // TODO: Let the target do this later.
3834   if (Flags.hasNonNeg() &&
3835       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3836     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3837     return;
3838   }
3839 
3840   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3841 }
3842 
3843 void SelectionDAGBuilder::visitSExt(const User &I) {
3844   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3845   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3846   SDValue N = getValue(I.getOperand(0));
3847   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3848                                                         I.getType());
3849   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3850 }
3851 
3852 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3853   // FPTrunc is never a no-op cast, no need to check
3854   SDValue N = getValue(I.getOperand(0));
3855   SDLoc dl = getCurSDLoc();
3856   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3857   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3858   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3859                            DAG.getTargetConstant(
3860                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3861 }
3862 
3863 void SelectionDAGBuilder::visitFPExt(const User &I) {
3864   // FPExt is never a no-op cast, no need to check
3865   SDValue N = getValue(I.getOperand(0));
3866   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3867                                                         I.getType());
3868   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3869 }
3870 
3871 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3872   // FPToUI is never a no-op cast, no need to check
3873   SDValue N = getValue(I.getOperand(0));
3874   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3875                                                         I.getType());
3876   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3877 }
3878 
3879 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3880   // FPToSI is never a no-op cast, no need to check
3881   SDValue N = getValue(I.getOperand(0));
3882   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3883                                                         I.getType());
3884   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3885 }
3886 
3887 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3888   // UIToFP is never a no-op cast, no need to check
3889   SDValue N = getValue(I.getOperand(0));
3890   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3891                                                         I.getType());
3892   SDNodeFlags Flags;
3893   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3894     Flags.setNonNeg(PNI->hasNonNeg());
3895 
3896   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3897 }
3898 
3899 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3900   // SIToFP is never a no-op cast, no need to check
3901   SDValue N = getValue(I.getOperand(0));
3902   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3903                                                         I.getType());
3904   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3905 }
3906 
3907 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3908   // What to do depends on the size of the integer and the size of the pointer.
3909   // We can either truncate, zero extend, or no-op, accordingly.
3910   SDValue N = getValue(I.getOperand(0));
3911   auto &TLI = DAG.getTargetLoweringInfo();
3912   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3913                                                         I.getType());
3914   EVT PtrMemVT =
3915       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3916   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3917   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3918   setValue(&I, N);
3919 }
3920 
3921 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3922   // What to do depends on the size of the integer and the size of the pointer.
3923   // We can either truncate, zero extend, or no-op, accordingly.
3924   SDValue N = getValue(I.getOperand(0));
3925   auto &TLI = DAG.getTargetLoweringInfo();
3926   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3927   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3928   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3929   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3930   setValue(&I, N);
3931 }
3932 
3933 void SelectionDAGBuilder::visitBitCast(const User &I) {
3934   SDValue N = getValue(I.getOperand(0));
3935   SDLoc dl = getCurSDLoc();
3936   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3937                                                         I.getType());
3938 
3939   // BitCast assures us that source and destination are the same size so this is
3940   // either a BITCAST or a no-op.
3941   if (DestVT != N.getValueType())
3942     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3943                              DestVT, N)); // convert types.
3944   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3945   // might fold any kind of constant expression to an integer constant and that
3946   // is not what we are looking for. Only recognize a bitcast of a genuine
3947   // constant integer as an opaque constant.
3948   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3949     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3950                                  /*isOpaque*/true));
3951   else
3952     setValue(&I, N);            // noop cast.
3953 }
3954 
3955 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3956   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3957   const Value *SV = I.getOperand(0);
3958   SDValue N = getValue(SV);
3959   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3960 
3961   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3962   unsigned DestAS = I.getType()->getPointerAddressSpace();
3963 
3964   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3965     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3966 
3967   setValue(&I, N);
3968 }
3969 
3970 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3971   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3972   SDValue InVec = getValue(I.getOperand(0));
3973   SDValue InVal = getValue(I.getOperand(1));
3974   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3975                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3976   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3977                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3978                            InVec, InVal, InIdx));
3979 }
3980 
3981 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3982   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3983   SDValue InVec = getValue(I.getOperand(0));
3984   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3985                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3986   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3987                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3988                            InVec, InIdx));
3989 }
3990 
3991 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
3992   SDValue Src1 = getValue(I.getOperand(0));
3993   SDValue Src2 = getValue(I.getOperand(1));
3994   ArrayRef<int> Mask;
3995   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
3996     Mask = SVI->getShuffleMask();
3997   else
3998     Mask = cast<ConstantExpr>(I).getShuffleMask();
3999   SDLoc DL = getCurSDLoc();
4000   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4001   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4002   EVT SrcVT = Src1.getValueType();
4003 
4004   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4005       VT.isScalableVector()) {
4006     // Canonical splat form of first element of first input vector.
4007     SDValue FirstElt =
4008         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4009                     DAG.getVectorIdxConstant(0, DL));
4010     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4011     return;
4012   }
4013 
4014   // For now, we only handle splats for scalable vectors.
4015   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4016   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4017   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4018 
4019   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4020   unsigned MaskNumElts = Mask.size();
4021 
4022   if (SrcNumElts == MaskNumElts) {
4023     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4024     return;
4025   }
4026 
4027   // Normalize the shuffle vector since mask and vector length don't match.
4028   if (SrcNumElts < MaskNumElts) {
4029     // Mask is longer than the source vectors. We can use concatenate vector to
4030     // make the mask and vectors lengths match.
4031 
4032     if (MaskNumElts % SrcNumElts == 0) {
4033       // Mask length is a multiple of the source vector length.
4034       // Check if the shuffle is some kind of concatenation of the input
4035       // vectors.
4036       unsigned NumConcat = MaskNumElts / SrcNumElts;
4037       bool IsConcat = true;
4038       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4039       for (unsigned i = 0; i != MaskNumElts; ++i) {
4040         int Idx = Mask[i];
4041         if (Idx < 0)
4042           continue;
4043         // Ensure the indices in each SrcVT sized piece are sequential and that
4044         // the same source is used for the whole piece.
4045         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4046             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4047              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4048           IsConcat = false;
4049           break;
4050         }
4051         // Remember which source this index came from.
4052         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4053       }
4054 
4055       // The shuffle is concatenating multiple vectors together. Just emit
4056       // a CONCAT_VECTORS operation.
4057       if (IsConcat) {
4058         SmallVector<SDValue, 8> ConcatOps;
4059         for (auto Src : ConcatSrcs) {
4060           if (Src < 0)
4061             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4062           else if (Src == 0)
4063             ConcatOps.push_back(Src1);
4064           else
4065             ConcatOps.push_back(Src2);
4066         }
4067         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4068         return;
4069       }
4070     }
4071 
4072     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4073     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4074     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4075                                     PaddedMaskNumElts);
4076 
4077     // Pad both vectors with undefs to make them the same length as the mask.
4078     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4079 
4080     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4081     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4082     MOps1[0] = Src1;
4083     MOps2[0] = Src2;
4084 
4085     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4086     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4087 
4088     // Readjust mask for new input vector length.
4089     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4090     for (unsigned i = 0; i != MaskNumElts; ++i) {
4091       int Idx = Mask[i];
4092       if (Idx >= (int)SrcNumElts)
4093         Idx -= SrcNumElts - PaddedMaskNumElts;
4094       MappedOps[i] = Idx;
4095     }
4096 
4097     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4098 
4099     // If the concatenated vector was padded, extract a subvector with the
4100     // correct number of elements.
4101     if (MaskNumElts != PaddedMaskNumElts)
4102       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4103                            DAG.getVectorIdxConstant(0, DL));
4104 
4105     setValue(&I, Result);
4106     return;
4107   }
4108 
4109   if (SrcNumElts > MaskNumElts) {
4110     // Analyze the access pattern of the vector to see if we can extract
4111     // two subvectors and do the shuffle.
4112     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4113     bool CanExtract = true;
4114     for (int Idx : Mask) {
4115       unsigned Input = 0;
4116       if (Idx < 0)
4117         continue;
4118 
4119       if (Idx >= (int)SrcNumElts) {
4120         Input = 1;
4121         Idx -= SrcNumElts;
4122       }
4123 
4124       // If all the indices come from the same MaskNumElts sized portion of
4125       // the sources we can use extract. Also make sure the extract wouldn't
4126       // extract past the end of the source.
4127       int NewStartIdx = alignDown(Idx, MaskNumElts);
4128       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4129           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4130         CanExtract = false;
4131       // Make sure we always update StartIdx as we use it to track if all
4132       // elements are undef.
4133       StartIdx[Input] = NewStartIdx;
4134     }
4135 
4136     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4137       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4138       return;
4139     }
4140     if (CanExtract) {
4141       // Extract appropriate subvector and generate a vector shuffle
4142       for (unsigned Input = 0; Input < 2; ++Input) {
4143         SDValue &Src = Input == 0 ? Src1 : Src2;
4144         if (StartIdx[Input] < 0)
4145           Src = DAG.getUNDEF(VT);
4146         else {
4147           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4148                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4149         }
4150       }
4151 
4152       // Calculate new mask.
4153       SmallVector<int, 8> MappedOps(Mask);
4154       for (int &Idx : MappedOps) {
4155         if (Idx >= (int)SrcNumElts)
4156           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4157         else if (Idx >= 0)
4158           Idx -= StartIdx[0];
4159       }
4160 
4161       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4162       return;
4163     }
4164   }
4165 
4166   // We can't use either concat vectors or extract subvectors so fall back to
4167   // replacing the shuffle with extract and build vector.
4168   // to insert and build vector.
4169   EVT EltVT = VT.getVectorElementType();
4170   SmallVector<SDValue,8> Ops;
4171   for (int Idx : Mask) {
4172     SDValue Res;
4173 
4174     if (Idx < 0) {
4175       Res = DAG.getUNDEF(EltVT);
4176     } else {
4177       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4178       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4179 
4180       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4181                         DAG.getVectorIdxConstant(Idx, DL));
4182     }
4183 
4184     Ops.push_back(Res);
4185   }
4186 
4187   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4188 }
4189 
4190 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4191   ArrayRef<unsigned> Indices = I.getIndices();
4192   const Value *Op0 = I.getOperand(0);
4193   const Value *Op1 = I.getOperand(1);
4194   Type *AggTy = I.getType();
4195   Type *ValTy = Op1->getType();
4196   bool IntoUndef = isa<UndefValue>(Op0);
4197   bool FromUndef = isa<UndefValue>(Op1);
4198 
4199   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4200 
4201   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4202   SmallVector<EVT, 4> AggValueVTs;
4203   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4204   SmallVector<EVT, 4> ValValueVTs;
4205   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4206 
4207   unsigned NumAggValues = AggValueVTs.size();
4208   unsigned NumValValues = ValValueVTs.size();
4209   SmallVector<SDValue, 4> Values(NumAggValues);
4210 
4211   // Ignore an insertvalue that produces an empty object
4212   if (!NumAggValues) {
4213     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4214     return;
4215   }
4216 
4217   SDValue Agg = getValue(Op0);
4218   unsigned i = 0;
4219   // Copy the beginning value(s) from the original aggregate.
4220   for (; i != LinearIndex; ++i)
4221     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4222                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4223   // Copy values from the inserted value(s).
4224   if (NumValValues) {
4225     SDValue Val = getValue(Op1);
4226     for (; i != LinearIndex + NumValValues; ++i)
4227       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4228                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4229   }
4230   // Copy remaining value(s) from the original aggregate.
4231   for (; i != NumAggValues; ++i)
4232     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4233                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4234 
4235   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4236                            DAG.getVTList(AggValueVTs), Values));
4237 }
4238 
4239 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4240   ArrayRef<unsigned> Indices = I.getIndices();
4241   const Value *Op0 = I.getOperand(0);
4242   Type *AggTy = Op0->getType();
4243   Type *ValTy = I.getType();
4244   bool OutOfUndef = isa<UndefValue>(Op0);
4245 
4246   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4247 
4248   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4249   SmallVector<EVT, 4> ValValueVTs;
4250   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4251 
4252   unsigned NumValValues = ValValueVTs.size();
4253 
4254   // Ignore a extractvalue that produces an empty object
4255   if (!NumValValues) {
4256     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4257     return;
4258   }
4259 
4260   SmallVector<SDValue, 4> Values(NumValValues);
4261 
4262   SDValue Agg = getValue(Op0);
4263   // Copy out the selected value(s).
4264   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4265     Values[i - LinearIndex] =
4266       OutOfUndef ?
4267         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4268         SDValue(Agg.getNode(), Agg.getResNo() + i);
4269 
4270   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4271                            DAG.getVTList(ValValueVTs), Values));
4272 }
4273 
4274 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4275   Value *Op0 = I.getOperand(0);
4276   // Note that the pointer operand may be a vector of pointers. Take the scalar
4277   // element which holds a pointer.
4278   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4279   SDValue N = getValue(Op0);
4280   SDLoc dl = getCurSDLoc();
4281   auto &TLI = DAG.getTargetLoweringInfo();
4282 
4283   // Normalize Vector GEP - all scalar operands should be converted to the
4284   // splat vector.
4285   bool IsVectorGEP = I.getType()->isVectorTy();
4286   ElementCount VectorElementCount =
4287       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4288                   : ElementCount::getFixed(0);
4289 
4290   if (IsVectorGEP && !N.getValueType().isVector()) {
4291     LLVMContext &Context = *DAG.getContext();
4292     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4293     N = DAG.getSplat(VT, dl, N);
4294   }
4295 
4296   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4297        GTI != E; ++GTI) {
4298     const Value *Idx = GTI.getOperand();
4299     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4300       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4301       if (Field) {
4302         // N = N + Offset
4303         uint64_t Offset =
4304             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4305 
4306         // In an inbounds GEP with an offset that is nonnegative even when
4307         // interpreted as signed, assume there is no unsigned overflow.
4308         SDNodeFlags Flags;
4309         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4310           Flags.setNoUnsignedWrap(true);
4311 
4312         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4313                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4314       }
4315     } else {
4316       // IdxSize is the width of the arithmetic according to IR semantics.
4317       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4318       // (and fix up the result later).
4319       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4320       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4321       TypeSize ElementSize =
4322           GTI.getSequentialElementStride(DAG.getDataLayout());
4323       // We intentionally mask away the high bits here; ElementSize may not
4324       // fit in IdxTy.
4325       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4326       bool ElementScalable = ElementSize.isScalable();
4327 
4328       // If this is a scalar constant or a splat vector of constants,
4329       // handle it quickly.
4330       const auto *C = dyn_cast<Constant>(Idx);
4331       if (C && isa<VectorType>(C->getType()))
4332         C = C->getSplatValue();
4333 
4334       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4335       if (CI && CI->isZero())
4336         continue;
4337       if (CI && !ElementScalable) {
4338         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4339         LLVMContext &Context = *DAG.getContext();
4340         SDValue OffsVal;
4341         if (IsVectorGEP)
4342           OffsVal = DAG.getConstant(
4343               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4344         else
4345           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4346 
4347         // In an inbounds GEP with an offset that is nonnegative even when
4348         // interpreted as signed, assume there is no unsigned overflow.
4349         SDNodeFlags Flags;
4350         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4351           Flags.setNoUnsignedWrap(true);
4352 
4353         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4354 
4355         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4356         continue;
4357       }
4358 
4359       // N = N + Idx * ElementMul;
4360       SDValue IdxN = getValue(Idx);
4361 
4362       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4363         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4364                                   VectorElementCount);
4365         IdxN = DAG.getSplat(VT, dl, IdxN);
4366       }
4367 
4368       // If the index is smaller or larger than intptr_t, truncate or extend
4369       // it.
4370       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4371 
4372       if (ElementScalable) {
4373         EVT VScaleTy = N.getValueType().getScalarType();
4374         SDValue VScale = DAG.getNode(
4375             ISD::VSCALE, dl, VScaleTy,
4376             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4377         if (IsVectorGEP)
4378           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4379         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4380       } else {
4381         // If this is a multiply by a power of two, turn it into a shl
4382         // immediately.  This is a very common case.
4383         if (ElementMul != 1) {
4384           if (ElementMul.isPowerOf2()) {
4385             unsigned Amt = ElementMul.logBase2();
4386             IdxN = DAG.getNode(ISD::SHL, dl,
4387                                N.getValueType(), IdxN,
4388                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4389           } else {
4390             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4391                                             IdxN.getValueType());
4392             IdxN = DAG.getNode(ISD::MUL, dl,
4393                                N.getValueType(), IdxN, Scale);
4394           }
4395         }
4396       }
4397 
4398       N = DAG.getNode(ISD::ADD, dl,
4399                       N.getValueType(), N, IdxN);
4400     }
4401   }
4402 
4403   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4404   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4405   if (IsVectorGEP) {
4406     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4407     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4408   }
4409 
4410   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4411     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4412 
4413   setValue(&I, N);
4414 }
4415 
4416 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4417   // If this is a fixed sized alloca in the entry block of the function,
4418   // allocate it statically on the stack.
4419   if (FuncInfo.StaticAllocaMap.count(&I))
4420     return;   // getValue will auto-populate this.
4421 
4422   SDLoc dl = getCurSDLoc();
4423   Type *Ty = I.getAllocatedType();
4424   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4425   auto &DL = DAG.getDataLayout();
4426   TypeSize TySize = DL.getTypeAllocSize(Ty);
4427   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4428 
4429   SDValue AllocSize = getValue(I.getArraySize());
4430 
4431   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4432   if (AllocSize.getValueType() != IntPtr)
4433     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4434 
4435   if (TySize.isScalable())
4436     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4437                             DAG.getVScale(dl, IntPtr,
4438                                           APInt(IntPtr.getScalarSizeInBits(),
4439                                                 TySize.getKnownMinValue())));
4440   else {
4441     SDValue TySizeValue =
4442         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4443     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4444                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4445   }
4446 
4447   // Handle alignment.  If the requested alignment is less than or equal to
4448   // the stack alignment, ignore it.  If the size is greater than or equal to
4449   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4450   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4451   if (*Alignment <= StackAlign)
4452     Alignment = std::nullopt;
4453 
4454   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4455   // Round the size of the allocation up to the stack alignment size
4456   // by add SA-1 to the size. This doesn't overflow because we're computing
4457   // an address inside an alloca.
4458   SDNodeFlags Flags;
4459   Flags.setNoUnsignedWrap(true);
4460   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4461                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4462 
4463   // Mask out the low bits for alignment purposes.
4464   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4465                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4466 
4467   SDValue Ops[] = {
4468       getRoot(), AllocSize,
4469       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4470   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4471   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4472   setValue(&I, DSA);
4473   DAG.setRoot(DSA.getValue(1));
4474 
4475   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4476 }
4477 
4478 static const MDNode *getRangeMetadata(const Instruction &I) {
4479   // If !noundef is not present, then !range violation results in a poison
4480   // value rather than immediate undefined behavior. In theory, transferring
4481   // these annotations to SDAG is fine, but in practice there are key SDAG
4482   // transforms that are known not to be poison-safe, such as folding logical
4483   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4484   // also present.
4485   if (!I.hasMetadata(LLVMContext::MD_noundef))
4486     return nullptr;
4487   return I.getMetadata(LLVMContext::MD_range);
4488 }
4489 
4490 static std::optional<ConstantRange> getRange(const Instruction &I) {
4491   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4492     // see comment in getRangeMetadata about this check
4493     if (CB->hasRetAttr(Attribute::NoUndef))
4494       return CB->getRange();
4495   }
4496   if (const MDNode *Range = getRangeMetadata(I))
4497     return getConstantRangeFromMetadata(*Range);
4498   return std::nullopt;
4499 }
4500 
4501 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4502   if (I.isAtomic())
4503     return visitAtomicLoad(I);
4504 
4505   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4506   const Value *SV = I.getOperand(0);
4507   if (TLI.supportSwiftError()) {
4508     // Swifterror values can come from either a function parameter with
4509     // swifterror attribute or an alloca with swifterror attribute.
4510     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4511       if (Arg->hasSwiftErrorAttr())
4512         return visitLoadFromSwiftError(I);
4513     }
4514 
4515     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4516       if (Alloca->isSwiftError())
4517         return visitLoadFromSwiftError(I);
4518     }
4519   }
4520 
4521   SDValue Ptr = getValue(SV);
4522 
4523   Type *Ty = I.getType();
4524   SmallVector<EVT, 4> ValueVTs, MemVTs;
4525   SmallVector<TypeSize, 4> Offsets;
4526   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4527   unsigned NumValues = ValueVTs.size();
4528   if (NumValues == 0)
4529     return;
4530 
4531   Align Alignment = I.getAlign();
4532   AAMDNodes AAInfo = I.getAAMetadata();
4533   const MDNode *Ranges = getRangeMetadata(I);
4534   bool isVolatile = I.isVolatile();
4535   MachineMemOperand::Flags MMOFlags =
4536       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4537 
4538   SDValue Root;
4539   bool ConstantMemory = false;
4540   if (isVolatile)
4541     // Serialize volatile loads with other side effects.
4542     Root = getRoot();
4543   else if (NumValues > MaxParallelChains)
4544     Root = getMemoryRoot();
4545   else if (AA &&
4546            AA->pointsToConstantMemory(MemoryLocation(
4547                SV,
4548                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4549                AAInfo))) {
4550     // Do not serialize (non-volatile) loads of constant memory with anything.
4551     Root = DAG.getEntryNode();
4552     ConstantMemory = true;
4553     MMOFlags |= MachineMemOperand::MOInvariant;
4554   } else {
4555     // Do not serialize non-volatile loads against each other.
4556     Root = DAG.getRoot();
4557   }
4558 
4559   SDLoc dl = getCurSDLoc();
4560 
4561   if (isVolatile)
4562     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4563 
4564   SmallVector<SDValue, 4> Values(NumValues);
4565   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4566 
4567   unsigned ChainI = 0;
4568   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4569     // Serializing loads here may result in excessive register pressure, and
4570     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4571     // could recover a bit by hoisting nodes upward in the chain by recognizing
4572     // they are side-effect free or do not alias. The optimizer should really
4573     // avoid this case by converting large object/array copies to llvm.memcpy
4574     // (MaxParallelChains should always remain as failsafe).
4575     if (ChainI == MaxParallelChains) {
4576       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4577       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4578                                   ArrayRef(Chains.data(), ChainI));
4579       Root = Chain;
4580       ChainI = 0;
4581     }
4582 
4583     // TODO: MachinePointerInfo only supports a fixed length offset.
4584     MachinePointerInfo PtrInfo =
4585         !Offsets[i].isScalable() || Offsets[i].isZero()
4586             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4587             : MachinePointerInfo();
4588 
4589     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4590     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4591                             MMOFlags, AAInfo, Ranges);
4592     Chains[ChainI] = L.getValue(1);
4593 
4594     if (MemVTs[i] != ValueVTs[i])
4595       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4596 
4597     Values[i] = L;
4598   }
4599 
4600   if (!ConstantMemory) {
4601     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4602                                 ArrayRef(Chains.data(), ChainI));
4603     if (isVolatile)
4604       DAG.setRoot(Chain);
4605     else
4606       PendingLoads.push_back(Chain);
4607   }
4608 
4609   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4610                            DAG.getVTList(ValueVTs), Values));
4611 }
4612 
4613 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4614   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4615          "call visitStoreToSwiftError when backend supports swifterror");
4616 
4617   SmallVector<EVT, 4> ValueVTs;
4618   SmallVector<uint64_t, 4> Offsets;
4619   const Value *SrcV = I.getOperand(0);
4620   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4621                   SrcV->getType(), ValueVTs, &Offsets, 0);
4622   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4623          "expect a single EVT for swifterror");
4624 
4625   SDValue Src = getValue(SrcV);
4626   // Create a virtual register, then update the virtual register.
4627   Register VReg =
4628       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4629   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4630   // Chain can be getRoot or getControlRoot.
4631   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4632                                       SDValue(Src.getNode(), Src.getResNo()));
4633   DAG.setRoot(CopyNode);
4634 }
4635 
4636 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4637   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4638          "call visitLoadFromSwiftError when backend supports swifterror");
4639 
4640   assert(!I.isVolatile() &&
4641          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4642          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4643          "Support volatile, non temporal, invariant for load_from_swift_error");
4644 
4645   const Value *SV = I.getOperand(0);
4646   Type *Ty = I.getType();
4647   assert(
4648       (!AA ||
4649        !AA->pointsToConstantMemory(MemoryLocation(
4650            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4651            I.getAAMetadata()))) &&
4652       "load_from_swift_error should not be constant memory");
4653 
4654   SmallVector<EVT, 4> ValueVTs;
4655   SmallVector<uint64_t, 4> Offsets;
4656   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4657                   ValueVTs, &Offsets, 0);
4658   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4659          "expect a single EVT for swifterror");
4660 
4661   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4662   SDValue L = DAG.getCopyFromReg(
4663       getRoot(), getCurSDLoc(),
4664       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4665 
4666   setValue(&I, L);
4667 }
4668 
4669 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4670   if (I.isAtomic())
4671     return visitAtomicStore(I);
4672 
4673   const Value *SrcV = I.getOperand(0);
4674   const Value *PtrV = I.getOperand(1);
4675 
4676   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4677   if (TLI.supportSwiftError()) {
4678     // Swifterror values can come from either a function parameter with
4679     // swifterror attribute or an alloca with swifterror attribute.
4680     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4681       if (Arg->hasSwiftErrorAttr())
4682         return visitStoreToSwiftError(I);
4683     }
4684 
4685     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4686       if (Alloca->isSwiftError())
4687         return visitStoreToSwiftError(I);
4688     }
4689   }
4690 
4691   SmallVector<EVT, 4> ValueVTs, MemVTs;
4692   SmallVector<TypeSize, 4> Offsets;
4693   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4694                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4695   unsigned NumValues = ValueVTs.size();
4696   if (NumValues == 0)
4697     return;
4698 
4699   // Get the lowered operands. Note that we do this after
4700   // checking if NumResults is zero, because with zero results
4701   // the operands won't have values in the map.
4702   SDValue Src = getValue(SrcV);
4703   SDValue Ptr = getValue(PtrV);
4704 
4705   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4706   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4707   SDLoc dl = getCurSDLoc();
4708   Align Alignment = I.getAlign();
4709   AAMDNodes AAInfo = I.getAAMetadata();
4710 
4711   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4712 
4713   unsigned ChainI = 0;
4714   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4715     // See visitLoad comments.
4716     if (ChainI == MaxParallelChains) {
4717       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4718                                   ArrayRef(Chains.data(), ChainI));
4719       Root = Chain;
4720       ChainI = 0;
4721     }
4722 
4723     // TODO: MachinePointerInfo only supports a fixed length offset.
4724     MachinePointerInfo PtrInfo =
4725         !Offsets[i].isScalable() || Offsets[i].isZero()
4726             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4727             : MachinePointerInfo();
4728 
4729     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4730     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4731     if (MemVTs[i] != ValueVTs[i])
4732       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4733     SDValue St =
4734         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4735     Chains[ChainI] = St;
4736   }
4737 
4738   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4739                                   ArrayRef(Chains.data(), ChainI));
4740   setValue(&I, StoreNode);
4741   DAG.setRoot(StoreNode);
4742 }
4743 
4744 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4745                                            bool IsCompressing) {
4746   SDLoc sdl = getCurSDLoc();
4747 
4748   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4749                                Align &Alignment) {
4750     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4751     Src0 = I.getArgOperand(0);
4752     Ptr = I.getArgOperand(1);
4753     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4754     Mask = I.getArgOperand(3);
4755   };
4756   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4757                                     Align &Alignment) {
4758     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4759     Src0 = I.getArgOperand(0);
4760     Ptr = I.getArgOperand(1);
4761     Mask = I.getArgOperand(2);
4762     Alignment = I.getParamAlign(1).valueOrOne();
4763   };
4764 
4765   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4766   Align Alignment;
4767   if (IsCompressing)
4768     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4769   else
4770     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4771 
4772   SDValue Ptr = getValue(PtrOperand);
4773   SDValue Src0 = getValue(Src0Operand);
4774   SDValue Mask = getValue(MaskOperand);
4775   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4776 
4777   EVT VT = Src0.getValueType();
4778 
4779   auto MMOFlags = MachineMemOperand::MOStore;
4780   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4781     MMOFlags |= MachineMemOperand::MONonTemporal;
4782 
4783   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4784       MachinePointerInfo(PtrOperand), MMOFlags,
4785       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4786   SDValue StoreNode =
4787       DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask, VT, MMO,
4788                          ISD::UNINDEXED, false /* Truncating */, IsCompressing);
4789   DAG.setRoot(StoreNode);
4790   setValue(&I, StoreNode);
4791 }
4792 
4793 // Get a uniform base for the Gather/Scatter intrinsic.
4794 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4795 // We try to represent it as a base pointer + vector of indices.
4796 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4797 // The first operand of the GEP may be a single pointer or a vector of pointers
4798 // Example:
4799 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4800 //  or
4801 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4802 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4803 //
4804 // When the first GEP operand is a single pointer - it is the uniform base we
4805 // are looking for. If first operand of the GEP is a splat vector - we
4806 // extract the splat value and use it as a uniform base.
4807 // In all other cases the function returns 'false'.
4808 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4809                            ISD::MemIndexType &IndexType, SDValue &Scale,
4810                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4811                            uint64_t ElemSize) {
4812   SelectionDAG& DAG = SDB->DAG;
4813   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4814   const DataLayout &DL = DAG.getDataLayout();
4815 
4816   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4817 
4818   // Handle splat constant pointer.
4819   if (auto *C = dyn_cast<Constant>(Ptr)) {
4820     C = C->getSplatValue();
4821     if (!C)
4822       return false;
4823 
4824     Base = SDB->getValue(C);
4825 
4826     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4827     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4828     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4829     IndexType = ISD::SIGNED_SCALED;
4830     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4831     return true;
4832   }
4833 
4834   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4835   if (!GEP || GEP->getParent() != CurBB)
4836     return false;
4837 
4838   if (GEP->getNumOperands() != 2)
4839     return false;
4840 
4841   const Value *BasePtr = GEP->getPointerOperand();
4842   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4843 
4844   // Make sure the base is scalar and the index is a vector.
4845   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4846     return false;
4847 
4848   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4849   if (ScaleVal.isScalable())
4850     return false;
4851 
4852   // Target may not support the required addressing mode.
4853   if (ScaleVal != 1 &&
4854       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4855     return false;
4856 
4857   Base = SDB->getValue(BasePtr);
4858   Index = SDB->getValue(IndexVal);
4859   IndexType = ISD::SIGNED_SCALED;
4860 
4861   Scale =
4862       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4863   return true;
4864 }
4865 
4866 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4867   SDLoc sdl = getCurSDLoc();
4868 
4869   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4870   const Value *Ptr = I.getArgOperand(1);
4871   SDValue Src0 = getValue(I.getArgOperand(0));
4872   SDValue Mask = getValue(I.getArgOperand(3));
4873   EVT VT = Src0.getValueType();
4874   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4875                         ->getMaybeAlignValue()
4876                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4878 
4879   SDValue Base;
4880   SDValue Index;
4881   ISD::MemIndexType IndexType;
4882   SDValue Scale;
4883   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4884                                     I.getParent(), VT.getScalarStoreSize());
4885 
4886   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4887   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4888       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4889       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4890   if (!UniformBase) {
4891     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4892     Index = getValue(Ptr);
4893     IndexType = ISD::SIGNED_SCALED;
4894     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4895   }
4896 
4897   EVT IdxVT = Index.getValueType();
4898   EVT EltTy = IdxVT.getVectorElementType();
4899   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4900     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4901     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4902   }
4903 
4904   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4905   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4906                                          Ops, MMO, IndexType, false);
4907   DAG.setRoot(Scatter);
4908   setValue(&I, Scatter);
4909 }
4910 
4911 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4912   SDLoc sdl = getCurSDLoc();
4913 
4914   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4915                               Align &Alignment) {
4916     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4917     Ptr = I.getArgOperand(0);
4918     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4919     Mask = I.getArgOperand(2);
4920     Src0 = I.getArgOperand(3);
4921   };
4922   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4923                                  Align &Alignment) {
4924     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4925     Ptr = I.getArgOperand(0);
4926     Alignment = I.getParamAlign(0).valueOrOne();
4927     Mask = I.getArgOperand(1);
4928     Src0 = I.getArgOperand(2);
4929   };
4930 
4931   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4932   Align Alignment;
4933   if (IsExpanding)
4934     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4935   else
4936     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4937 
4938   SDValue Ptr = getValue(PtrOperand);
4939   SDValue Src0 = getValue(Src0Operand);
4940   SDValue Mask = getValue(MaskOperand);
4941   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4942 
4943   EVT VT = Src0.getValueType();
4944   AAMDNodes AAInfo = I.getAAMetadata();
4945   const MDNode *Ranges = getRangeMetadata(I);
4946 
4947   // Do not serialize masked loads of constant memory with anything.
4948   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4949   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4950 
4951   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4952 
4953   auto MMOFlags = MachineMemOperand::MOLoad;
4954   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4955     MMOFlags |= MachineMemOperand::MONonTemporal;
4956 
4957   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4958       MachinePointerInfo(PtrOperand), MMOFlags,
4959       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4960 
4961   SDValue Load =
4962       DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4963                         ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4964   if (AddToChain)
4965     PendingLoads.push_back(Load.getValue(1));
4966   setValue(&I, Load);
4967 }
4968 
4969 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4970   SDLoc sdl = getCurSDLoc();
4971 
4972   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
4973   const Value *Ptr = I.getArgOperand(0);
4974   SDValue Src0 = getValue(I.getArgOperand(3));
4975   SDValue Mask = getValue(I.getArgOperand(2));
4976 
4977   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4978   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4979   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
4980                         ->getMaybeAlignValue()
4981                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4982 
4983   const MDNode *Ranges = getRangeMetadata(I);
4984 
4985   SDValue Root = DAG.getRoot();
4986   SDValue Base;
4987   SDValue Index;
4988   ISD::MemIndexType IndexType;
4989   SDValue Scale;
4990   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4991                                     I.getParent(), VT.getScalarStoreSize());
4992   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4993   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4994       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
4995       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
4996       Ranges);
4997 
4998   if (!UniformBase) {
4999     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5000     Index = getValue(Ptr);
5001     IndexType = ISD::SIGNED_SCALED;
5002     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5003   }
5004 
5005   EVT IdxVT = Index.getValueType();
5006   EVT EltTy = IdxVT.getVectorElementType();
5007   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5008     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5009     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5010   }
5011 
5012   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5013   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5014                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5015 
5016   PendingLoads.push_back(Gather.getValue(1));
5017   setValue(&I, Gather);
5018 }
5019 
5020 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5021   SDLoc dl = getCurSDLoc();
5022   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5023   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5024   SyncScope::ID SSID = I.getSyncScopeID();
5025 
5026   SDValue InChain = getRoot();
5027 
5028   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5029   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5030 
5031   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5032   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5033 
5034   MachineFunction &MF = DAG.getMachineFunction();
5035   MachineMemOperand *MMO = MF.getMachineMemOperand(
5036       MachinePointerInfo(I.getPointerOperand()), Flags,
5037       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5038       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5039 
5040   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5041                                    dl, MemVT, VTs, InChain,
5042                                    getValue(I.getPointerOperand()),
5043                                    getValue(I.getCompareOperand()),
5044                                    getValue(I.getNewValOperand()), MMO);
5045 
5046   SDValue OutChain = L.getValue(2);
5047 
5048   setValue(&I, L);
5049   DAG.setRoot(OutChain);
5050 }
5051 
5052 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5053   SDLoc dl = getCurSDLoc();
5054   ISD::NodeType NT;
5055   switch (I.getOperation()) {
5056   default: llvm_unreachable("Unknown atomicrmw operation");
5057   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5058   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5059   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5060   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5061   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5062   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5063   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5064   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5065   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5066   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5067   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5068   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5069   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5070   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5071   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5072   case AtomicRMWInst::UIncWrap:
5073     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5074     break;
5075   case AtomicRMWInst::UDecWrap:
5076     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5077     break;
5078   }
5079   AtomicOrdering Ordering = I.getOrdering();
5080   SyncScope::ID SSID = I.getSyncScopeID();
5081 
5082   SDValue InChain = getRoot();
5083 
5084   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5085   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5086   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5087 
5088   MachineFunction &MF = DAG.getMachineFunction();
5089   MachineMemOperand *MMO = MF.getMachineMemOperand(
5090       MachinePointerInfo(I.getPointerOperand()), Flags,
5091       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5092       AAMDNodes(), nullptr, SSID, Ordering);
5093 
5094   SDValue L =
5095     DAG.getAtomic(NT, dl, MemVT, InChain,
5096                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5097                   MMO);
5098 
5099   SDValue OutChain = L.getValue(1);
5100 
5101   setValue(&I, L);
5102   DAG.setRoot(OutChain);
5103 }
5104 
5105 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5106   SDLoc dl = getCurSDLoc();
5107   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5108   SDValue Ops[3];
5109   Ops[0] = getRoot();
5110   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5111                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5112   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5113                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5114   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5115   setValue(&I, N);
5116   DAG.setRoot(N);
5117 }
5118 
5119 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5120   SDLoc dl = getCurSDLoc();
5121   AtomicOrdering Order = I.getOrdering();
5122   SyncScope::ID SSID = I.getSyncScopeID();
5123 
5124   SDValue InChain = getRoot();
5125 
5126   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5127   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5128   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5129 
5130   if (!TLI.supportsUnalignedAtomics() &&
5131       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5132     report_fatal_error("Cannot generate unaligned atomic load");
5133 
5134   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5135 
5136   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5137       MachinePointerInfo(I.getPointerOperand()), Flags,
5138       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5139       nullptr, SSID, Order);
5140 
5141   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5142 
5143   SDValue Ptr = getValue(I.getPointerOperand());
5144   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5145                             Ptr, MMO);
5146 
5147   SDValue OutChain = L.getValue(1);
5148   if (MemVT != VT)
5149     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5150 
5151   setValue(&I, L);
5152   DAG.setRoot(OutChain);
5153 }
5154 
5155 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5156   SDLoc dl = getCurSDLoc();
5157 
5158   AtomicOrdering Ordering = I.getOrdering();
5159   SyncScope::ID SSID = I.getSyncScopeID();
5160 
5161   SDValue InChain = getRoot();
5162 
5163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5164   EVT MemVT =
5165       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5166 
5167   if (!TLI.supportsUnalignedAtomics() &&
5168       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5169     report_fatal_error("Cannot generate unaligned atomic store");
5170 
5171   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5172 
5173   MachineFunction &MF = DAG.getMachineFunction();
5174   MachineMemOperand *MMO = MF.getMachineMemOperand(
5175       MachinePointerInfo(I.getPointerOperand()), Flags,
5176       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5177       nullptr, SSID, Ordering);
5178 
5179   SDValue Val = getValue(I.getValueOperand());
5180   if (Val.getValueType() != MemVT)
5181     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5182   SDValue Ptr = getValue(I.getPointerOperand());
5183 
5184   SDValue OutChain =
5185       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5186 
5187   setValue(&I, OutChain);
5188   DAG.setRoot(OutChain);
5189 }
5190 
5191 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5192 /// node.
5193 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5194                                                unsigned Intrinsic) {
5195   // Ignore the callsite's attributes. A specific call site may be marked with
5196   // readnone, but the lowering code will expect the chain based on the
5197   // definition.
5198   const Function *F = I.getCalledFunction();
5199   bool HasChain = !F->doesNotAccessMemory();
5200   bool OnlyLoad = HasChain && F->onlyReadsMemory();
5201 
5202   // Build the operand list.
5203   SmallVector<SDValue, 8> Ops;
5204   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5205     if (OnlyLoad) {
5206       // We don't need to serialize loads against other loads.
5207       Ops.push_back(DAG.getRoot());
5208     } else {
5209       Ops.push_back(getRoot());
5210     }
5211   }
5212 
5213   // Info is set by getTgtMemIntrinsic
5214   TargetLowering::IntrinsicInfo Info;
5215   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5216   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5217                                                DAG.getMachineFunction(),
5218                                                Intrinsic);
5219 
5220   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5221   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5222       Info.opc == ISD::INTRINSIC_W_CHAIN)
5223     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5224                                         TLI.getPointerTy(DAG.getDataLayout())));
5225 
5226   // Add all operands of the call to the operand list.
5227   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5228     const Value *Arg = I.getArgOperand(i);
5229     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5230       Ops.push_back(getValue(Arg));
5231       continue;
5232     }
5233 
5234     // Use TargetConstant instead of a regular constant for immarg.
5235     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5236     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5237       assert(CI->getBitWidth() <= 64 &&
5238              "large intrinsic immediates not handled");
5239       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5240     } else {
5241       Ops.push_back(
5242           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5243     }
5244   }
5245 
5246   SmallVector<EVT, 4> ValueVTs;
5247   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5248 
5249   if (HasChain)
5250     ValueVTs.push_back(MVT::Other);
5251 
5252   SDVTList VTs = DAG.getVTList(ValueVTs);
5253 
5254   // Propagate fast-math-flags from IR to node(s).
5255   SDNodeFlags Flags;
5256   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5257     Flags.copyFMF(*FPMO);
5258   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5259 
5260   // Create the node.
5261   SDValue Result;
5262 
5263   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5264     auto *Token = Bundle->Inputs[0].get();
5265     SDValue ConvControlToken = getValue(Token);
5266     assert(Ops.back().getValueType() != MVT::Glue &&
5267            "Did not expected another glue node here.");
5268     ConvControlToken =
5269         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5270     Ops.push_back(ConvControlToken);
5271   }
5272 
5273   // In some cases, custom collection of operands from CallInst I may be needed.
5274   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5275   if (IsTgtIntrinsic) {
5276     // This is target intrinsic that touches memory
5277     //
5278     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5279     //       didn't yield anything useful.
5280     MachinePointerInfo MPI;
5281     if (Info.ptrVal)
5282       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5283     else if (Info.fallbackAddressSpace)
5284       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5285     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5286                                      Info.memVT, MPI, Info.align, Info.flags,
5287                                      Info.size, I.getAAMetadata());
5288   } else if (!HasChain) {
5289     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5290   } else if (!I.getType()->isVoidTy()) {
5291     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5292   } else {
5293     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5294   }
5295 
5296   if (HasChain) {
5297     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5298     if (OnlyLoad)
5299       PendingLoads.push_back(Chain);
5300     else
5301       DAG.setRoot(Chain);
5302   }
5303 
5304   if (!I.getType()->isVoidTy()) {
5305     if (!isa<VectorType>(I.getType()))
5306       Result = lowerRangeToAssertZExt(DAG, I, Result);
5307 
5308     MaybeAlign Alignment = I.getRetAlign();
5309 
5310     // Insert `assertalign` node if there's an alignment.
5311     if (InsertAssertAlign && Alignment) {
5312       Result =
5313           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5314     }
5315   }
5316 
5317   setValue(&I, Result);
5318 }
5319 
5320 /// GetSignificand - Get the significand and build it into a floating-point
5321 /// number with exponent of 1:
5322 ///
5323 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5324 ///
5325 /// where Op is the hexadecimal representation of floating point value.
5326 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5327   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5328                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5329   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5330                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5331   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5332 }
5333 
5334 /// GetExponent - Get the exponent:
5335 ///
5336 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5337 ///
5338 /// where Op is the hexadecimal representation of floating point value.
5339 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5340                            const TargetLowering &TLI, const SDLoc &dl) {
5341   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5342                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5343   SDValue t1 = DAG.getNode(
5344       ISD::SRL, dl, MVT::i32, t0,
5345       DAG.getConstant(23, dl,
5346                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5347   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5348                            DAG.getConstant(127, dl, MVT::i32));
5349   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5350 }
5351 
5352 /// getF32Constant - Get 32-bit floating point constant.
5353 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5354                               const SDLoc &dl) {
5355   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5356                            MVT::f32);
5357 }
5358 
5359 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5360                                        SelectionDAG &DAG) {
5361   // TODO: What fast-math-flags should be set on the floating-point nodes?
5362 
5363   //   IntegerPartOfX = ((int32_t)(t0);
5364   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5365 
5366   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5367   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5368   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5369 
5370   //   IntegerPartOfX <<= 23;
5371   IntegerPartOfX =
5372       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5373                   DAG.getConstant(23, dl,
5374                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5375                                       MVT::i32, DAG.getDataLayout())));
5376 
5377   SDValue TwoToFractionalPartOfX;
5378   if (LimitFloatPrecision <= 6) {
5379     // For floating-point precision of 6:
5380     //
5381     //   TwoToFractionalPartOfX =
5382     //     0.997535578f +
5383     //       (0.735607626f + 0.252464424f * x) * x;
5384     //
5385     // error 0.0144103317, which is 6 bits
5386     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5387                              getF32Constant(DAG, 0x3e814304, dl));
5388     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5389                              getF32Constant(DAG, 0x3f3c50c8, dl));
5390     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5391     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5392                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5393   } else if (LimitFloatPrecision <= 12) {
5394     // For floating-point precision of 12:
5395     //
5396     //   TwoToFractionalPartOfX =
5397     //     0.999892986f +
5398     //       (0.696457318f +
5399     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5400     //
5401     // error 0.000107046256, which is 13 to 14 bits
5402     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5403                              getF32Constant(DAG, 0x3da235e3, dl));
5404     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5405                              getF32Constant(DAG, 0x3e65b8f3, dl));
5406     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5407     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5408                              getF32Constant(DAG, 0x3f324b07, dl));
5409     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5410     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5411                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5412   } else { // LimitFloatPrecision <= 18
5413     // For floating-point precision of 18:
5414     //
5415     //   TwoToFractionalPartOfX =
5416     //     0.999999982f +
5417     //       (0.693148872f +
5418     //         (0.240227044f +
5419     //           (0.554906021e-1f +
5420     //             (0.961591928e-2f +
5421     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5422     // error 2.47208000*10^(-7), which is better than 18 bits
5423     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5424                              getF32Constant(DAG, 0x3924b03e, dl));
5425     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5426                              getF32Constant(DAG, 0x3ab24b87, dl));
5427     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5428     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5429                              getF32Constant(DAG, 0x3c1d8c17, dl));
5430     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5431     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5432                              getF32Constant(DAG, 0x3d634a1d, dl));
5433     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5434     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5435                              getF32Constant(DAG, 0x3e75fe14, dl));
5436     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5437     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5438                               getF32Constant(DAG, 0x3f317234, dl));
5439     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5440     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5441                                          getF32Constant(DAG, 0x3f800000, dl));
5442   }
5443 
5444   // Add the exponent into the result in integer domain.
5445   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5446   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5447                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5448 }
5449 
5450 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5451 /// limited-precision mode.
5452 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5453                          const TargetLowering &TLI, SDNodeFlags Flags) {
5454   if (Op.getValueType() == MVT::f32 &&
5455       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5456 
5457     // Put the exponent in the right bit position for later addition to the
5458     // final result:
5459     //
5460     // t0 = Op * log2(e)
5461 
5462     // TODO: What fast-math-flags should be set here?
5463     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5464                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5465     return getLimitedPrecisionExp2(t0, dl, DAG);
5466   }
5467 
5468   // No special expansion.
5469   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5470 }
5471 
5472 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5473 /// limited-precision mode.
5474 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5475                          const TargetLowering &TLI, SDNodeFlags Flags) {
5476   // TODO: What fast-math-flags should be set on the floating-point nodes?
5477 
5478   if (Op.getValueType() == MVT::f32 &&
5479       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5480     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5481 
5482     // Scale the exponent by log(2).
5483     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5484     SDValue LogOfExponent =
5485         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5486                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5487 
5488     // Get the significand and build it into a floating-point number with
5489     // exponent of 1.
5490     SDValue X = GetSignificand(DAG, Op1, dl);
5491 
5492     SDValue LogOfMantissa;
5493     if (LimitFloatPrecision <= 6) {
5494       // For floating-point precision of 6:
5495       //
5496       //   LogofMantissa =
5497       //     -1.1609546f +
5498       //       (1.4034025f - 0.23903021f * x) * x;
5499       //
5500       // error 0.0034276066, which is better than 8 bits
5501       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5502                                getF32Constant(DAG, 0xbe74c456, dl));
5503       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5504                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5505       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5506       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5507                                   getF32Constant(DAG, 0x3f949a29, dl));
5508     } else if (LimitFloatPrecision <= 12) {
5509       // For floating-point precision of 12:
5510       //
5511       //   LogOfMantissa =
5512       //     -1.7417939f +
5513       //       (2.8212026f +
5514       //         (-1.4699568f +
5515       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5516       //
5517       // error 0.000061011436, which is 14 bits
5518       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5519                                getF32Constant(DAG, 0xbd67b6d6, dl));
5520       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5521                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5522       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5523       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5524                                getF32Constant(DAG, 0x3fbc278b, dl));
5525       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5526       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5527                                getF32Constant(DAG, 0x40348e95, dl));
5528       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5529       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5530                                   getF32Constant(DAG, 0x3fdef31a, dl));
5531     } else { // LimitFloatPrecision <= 18
5532       // For floating-point precision of 18:
5533       //
5534       //   LogOfMantissa =
5535       //     -2.1072184f +
5536       //       (4.2372794f +
5537       //         (-3.7029485f +
5538       //           (2.2781945f +
5539       //             (-0.87823314f +
5540       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5541       //
5542       // error 0.0000023660568, which is better than 18 bits
5543       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5544                                getF32Constant(DAG, 0xbc91e5ac, dl));
5545       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5546                                getF32Constant(DAG, 0x3e4350aa, dl));
5547       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5548       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5549                                getF32Constant(DAG, 0x3f60d3e3, dl));
5550       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5551       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5552                                getF32Constant(DAG, 0x4011cdf0, dl));
5553       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5554       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5555                                getF32Constant(DAG, 0x406cfd1c, dl));
5556       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5557       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5558                                getF32Constant(DAG, 0x408797cb, dl));
5559       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5560       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5561                                   getF32Constant(DAG, 0x4006dcab, dl));
5562     }
5563 
5564     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5565   }
5566 
5567   // No special expansion.
5568   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5569 }
5570 
5571 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5572 /// limited-precision mode.
5573 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5574                           const TargetLowering &TLI, SDNodeFlags Flags) {
5575   // TODO: What fast-math-flags should be set on the floating-point nodes?
5576 
5577   if (Op.getValueType() == MVT::f32 &&
5578       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5579     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5580 
5581     // Get the exponent.
5582     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5583 
5584     // Get the significand and build it into a floating-point number with
5585     // exponent of 1.
5586     SDValue X = GetSignificand(DAG, Op1, dl);
5587 
5588     // Different possible minimax approximations of significand in
5589     // floating-point for various degrees of accuracy over [1,2].
5590     SDValue Log2ofMantissa;
5591     if (LimitFloatPrecision <= 6) {
5592       // For floating-point precision of 6:
5593       //
5594       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5595       //
5596       // error 0.0049451742, which is more than 7 bits
5597       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5598                                getF32Constant(DAG, 0xbeb08fe0, dl));
5599       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5600                                getF32Constant(DAG, 0x40019463, dl));
5601       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5602       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5603                                    getF32Constant(DAG, 0x3fd6633d, dl));
5604     } else if (LimitFloatPrecision <= 12) {
5605       // For floating-point precision of 12:
5606       //
5607       //   Log2ofMantissa =
5608       //     -2.51285454f +
5609       //       (4.07009056f +
5610       //         (-2.12067489f +
5611       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5612       //
5613       // error 0.0000876136000, which is better than 13 bits
5614       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5615                                getF32Constant(DAG, 0xbda7262e, dl));
5616       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5617                                getF32Constant(DAG, 0x3f25280b, dl));
5618       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5619       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5620                                getF32Constant(DAG, 0x4007b923, dl));
5621       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5622       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5623                                getF32Constant(DAG, 0x40823e2f, dl));
5624       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5625       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5626                                    getF32Constant(DAG, 0x4020d29c, dl));
5627     } else { // LimitFloatPrecision <= 18
5628       // For floating-point precision of 18:
5629       //
5630       //   Log2ofMantissa =
5631       //     -3.0400495f +
5632       //       (6.1129976f +
5633       //         (-5.3420409f +
5634       //           (3.2865683f +
5635       //             (-1.2669343f +
5636       //               (0.27515199f -
5637       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5638       //
5639       // error 0.0000018516, which is better than 18 bits
5640       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5641                                getF32Constant(DAG, 0xbcd2769e, dl));
5642       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5643                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5644       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5645       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5646                                getF32Constant(DAG, 0x3fa22ae7, dl));
5647       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5648       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5649                                getF32Constant(DAG, 0x40525723, dl));
5650       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5651       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5652                                getF32Constant(DAG, 0x40aaf200, dl));
5653       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5654       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5655                                getF32Constant(DAG, 0x40c39dad, dl));
5656       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5657       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5658                                    getF32Constant(DAG, 0x4042902c, dl));
5659     }
5660 
5661     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5662   }
5663 
5664   // No special expansion.
5665   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5666 }
5667 
5668 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5669 /// limited-precision mode.
5670 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5671                            const TargetLowering &TLI, SDNodeFlags Flags) {
5672   // TODO: What fast-math-flags should be set on the floating-point nodes?
5673 
5674   if (Op.getValueType() == MVT::f32 &&
5675       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5676     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5677 
5678     // Scale the exponent by log10(2) [0.30102999f].
5679     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5680     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5681                                         getF32Constant(DAG, 0x3e9a209a, dl));
5682 
5683     // Get the significand and build it into a floating-point number with
5684     // exponent of 1.
5685     SDValue X = GetSignificand(DAG, Op1, dl);
5686 
5687     SDValue Log10ofMantissa;
5688     if (LimitFloatPrecision <= 6) {
5689       // For floating-point precision of 6:
5690       //
5691       //   Log10ofMantissa =
5692       //     -0.50419619f +
5693       //       (0.60948995f - 0.10380950f * x) * x;
5694       //
5695       // error 0.0014886165, which is 6 bits
5696       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5697                                getF32Constant(DAG, 0xbdd49a13, dl));
5698       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5699                                getF32Constant(DAG, 0x3f1c0789, dl));
5700       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5701       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5702                                     getF32Constant(DAG, 0x3f011300, dl));
5703     } else if (LimitFloatPrecision <= 12) {
5704       // For floating-point precision of 12:
5705       //
5706       //   Log10ofMantissa =
5707       //     -0.64831180f +
5708       //       (0.91751397f +
5709       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5710       //
5711       // error 0.00019228036, which is better than 12 bits
5712       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5713                                getF32Constant(DAG, 0x3d431f31, dl));
5714       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5715                                getF32Constant(DAG, 0x3ea21fb2, dl));
5716       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5717       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5718                                getF32Constant(DAG, 0x3f6ae232, dl));
5719       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5720       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5721                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5722     } else { // LimitFloatPrecision <= 18
5723       // For floating-point precision of 18:
5724       //
5725       //   Log10ofMantissa =
5726       //     -0.84299375f +
5727       //       (1.5327582f +
5728       //         (-1.0688956f +
5729       //           (0.49102474f +
5730       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5731       //
5732       // error 0.0000037995730, which is better than 18 bits
5733       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5734                                getF32Constant(DAG, 0x3c5d51ce, dl));
5735       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5736                                getF32Constant(DAG, 0x3e00685a, dl));
5737       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5738       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5739                                getF32Constant(DAG, 0x3efb6798, dl));
5740       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5741       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5742                                getF32Constant(DAG, 0x3f88d192, dl));
5743       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5744       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5745                                getF32Constant(DAG, 0x3fc4316c, dl));
5746       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5747       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5748                                     getF32Constant(DAG, 0x3f57ce70, dl));
5749     }
5750 
5751     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5752   }
5753 
5754   // No special expansion.
5755   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5756 }
5757 
5758 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5759 /// limited-precision mode.
5760 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5761                           const TargetLowering &TLI, SDNodeFlags Flags) {
5762   if (Op.getValueType() == MVT::f32 &&
5763       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5764     return getLimitedPrecisionExp2(Op, dl, DAG);
5765 
5766   // No special expansion.
5767   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5768 }
5769 
5770 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5771 /// limited-precision mode with x == 10.0f.
5772 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5773                          SelectionDAG &DAG, const TargetLowering &TLI,
5774                          SDNodeFlags Flags) {
5775   bool IsExp10 = false;
5776   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5777       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5778     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5779       APFloat Ten(10.0f);
5780       IsExp10 = LHSC->isExactlyValue(Ten);
5781     }
5782   }
5783 
5784   // TODO: What fast-math-flags should be set on the FMUL node?
5785   if (IsExp10) {
5786     // Put the exponent in the right bit position for later addition to the
5787     // final result:
5788     //
5789     //   #define LOG2OF10 3.3219281f
5790     //   t0 = Op * LOG2OF10;
5791     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5792                              getF32Constant(DAG, 0x40549a78, dl));
5793     return getLimitedPrecisionExp2(t0, dl, DAG);
5794   }
5795 
5796   // No special expansion.
5797   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5798 }
5799 
5800 /// ExpandPowI - Expand a llvm.powi intrinsic.
5801 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5802                           SelectionDAG &DAG) {
5803   // If RHS is a constant, we can expand this out to a multiplication tree if
5804   // it's beneficial on the target, otherwise we end up lowering to a call to
5805   // __powidf2 (for example).
5806   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5807     unsigned Val = RHSC->getSExtValue();
5808 
5809     // powi(x, 0) -> 1.0
5810     if (Val == 0)
5811       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5812 
5813     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5814             Val, DAG.shouldOptForSize())) {
5815       // Get the exponent as a positive value.
5816       if ((int)Val < 0)
5817         Val = -Val;
5818       // We use the simple binary decomposition method to generate the multiply
5819       // sequence.  There are more optimal ways to do this (for example,
5820       // powi(x,15) generates one more multiply than it should), but this has
5821       // the benefit of being both really simple and much better than a libcall.
5822       SDValue Res; // Logically starts equal to 1.0
5823       SDValue CurSquare = LHS;
5824       // TODO: Intrinsics should have fast-math-flags that propagate to these
5825       // nodes.
5826       while (Val) {
5827         if (Val & 1) {
5828           if (Res.getNode())
5829             Res =
5830                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5831           else
5832             Res = CurSquare; // 1.0*CurSquare.
5833         }
5834 
5835         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5836                                 CurSquare, CurSquare);
5837         Val >>= 1;
5838       }
5839 
5840       // If the original was negative, invert the result, producing 1/(x*x*x).
5841       if (RHSC->getSExtValue() < 0)
5842         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5843                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5844       return Res;
5845     }
5846   }
5847 
5848   // Otherwise, expand to a libcall.
5849   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5850 }
5851 
5852 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5853                             SDValue LHS, SDValue RHS, SDValue Scale,
5854                             SelectionDAG &DAG, const TargetLowering &TLI) {
5855   EVT VT = LHS.getValueType();
5856   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5857   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5858   LLVMContext &Ctx = *DAG.getContext();
5859 
5860   // If the type is legal but the operation isn't, this node might survive all
5861   // the way to operation legalization. If we end up there and we do not have
5862   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5863   // node.
5864 
5865   // Coax the legalizer into expanding the node during type legalization instead
5866   // by bumping the size by one bit. This will force it to Promote, enabling the
5867   // early expansion and avoiding the need to expand later.
5868 
5869   // We don't have to do this if Scale is 0; that can always be expanded, unless
5870   // it's a saturating signed operation. Those can experience true integer
5871   // division overflow, a case which we must avoid.
5872 
5873   // FIXME: We wouldn't have to do this (or any of the early
5874   // expansion/promotion) if it was possible to expand a libcall of an
5875   // illegal type during operation legalization. But it's not, so things
5876   // get a bit hacky.
5877   unsigned ScaleInt = Scale->getAsZExtVal();
5878   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5879       (TLI.isTypeLegal(VT) ||
5880        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5881     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5882         Opcode, VT, ScaleInt);
5883     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5884       EVT PromVT;
5885       if (VT.isScalarInteger())
5886         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5887       else if (VT.isVector()) {
5888         PromVT = VT.getVectorElementType();
5889         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5890         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5891       } else
5892         llvm_unreachable("Wrong VT for DIVFIX?");
5893       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5894       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5895       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5896       // For saturating operations, we need to shift up the LHS to get the
5897       // proper saturation width, and then shift down again afterwards.
5898       if (Saturating)
5899         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5900                           DAG.getConstant(1, DL, ShiftTy));
5901       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5902       if (Saturating)
5903         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5904                           DAG.getConstant(1, DL, ShiftTy));
5905       return DAG.getZExtOrTrunc(Res, DL, VT);
5906     }
5907   }
5908 
5909   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5910 }
5911 
5912 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5913 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5914 static void
5915 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5916                      const SDValue &N) {
5917   switch (N.getOpcode()) {
5918   case ISD::CopyFromReg: {
5919     SDValue Op = N.getOperand(1);
5920     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5921                       Op.getValueType().getSizeInBits());
5922     return;
5923   }
5924   case ISD::BITCAST:
5925   case ISD::AssertZext:
5926   case ISD::AssertSext:
5927   case ISD::TRUNCATE:
5928     getUnderlyingArgRegs(Regs, N.getOperand(0));
5929     return;
5930   case ISD::BUILD_PAIR:
5931   case ISD::BUILD_VECTOR:
5932   case ISD::CONCAT_VECTORS:
5933     for (SDValue Op : N->op_values())
5934       getUnderlyingArgRegs(Regs, Op);
5935     return;
5936   default:
5937     return;
5938   }
5939 }
5940 
5941 /// If the DbgValueInst is a dbg_value of a function argument, create the
5942 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5943 /// instruction selection, they will be inserted to the entry BB.
5944 /// We don't currently support this for variadic dbg_values, as they shouldn't
5945 /// appear for function arguments or in the prologue.
5946 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5947     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5948     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5949   const Argument *Arg = dyn_cast<Argument>(V);
5950   if (!Arg)
5951     return false;
5952 
5953   MachineFunction &MF = DAG.getMachineFunction();
5954   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5955 
5956   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5957   // we've been asked to pursue.
5958   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5959                               bool Indirect) {
5960     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5961       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5962       // pointing at the VReg, which will be patched up later.
5963       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5964       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5965           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5966           /* isKill */ false, /* isDead */ false,
5967           /* isUndef */ false, /* isEarlyClobber */ false,
5968           /* SubReg */ 0, /* isDebug */ true)});
5969 
5970       auto *NewDIExpr = FragExpr;
5971       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
5972       // the DIExpression.
5973       if (Indirect)
5974         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
5975       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
5976       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
5977       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
5978     } else {
5979       // Create a completely standard DBG_VALUE.
5980       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
5981       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
5982     }
5983   };
5984 
5985   if (Kind == FuncArgumentDbgValueKind::Value) {
5986     // ArgDbgValues are hoisted to the beginning of the entry block. So we
5987     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
5988     // the entry block.
5989     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
5990     if (!IsInEntryBlock)
5991       return false;
5992 
5993     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
5994     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
5995     // variable that also is a param.
5996     //
5997     // Although, if we are at the top of the entry block already, we can still
5998     // emit using ArgDbgValue. This might catch some situations when the
5999     // dbg.value refers to an argument that isn't used in the entry block, so
6000     // any CopyToReg node would be optimized out and the only way to express
6001     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6002     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6003     // we should only emit as ArgDbgValue if the Variable is an argument to the
6004     // current function, and the dbg.value intrinsic is found in the entry
6005     // block.
6006     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6007         !DL->getInlinedAt();
6008     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6009     if (!IsInPrologue && !VariableIsFunctionInputArg)
6010       return false;
6011 
6012     // Here we assume that a function argument on IR level only can be used to
6013     // describe one input parameter on source level. If we for example have
6014     // source code like this
6015     //
6016     //    struct A { long x, y; };
6017     //    void foo(struct A a, long b) {
6018     //      ...
6019     //      b = a.x;
6020     //      ...
6021     //    }
6022     //
6023     // and IR like this
6024     //
6025     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6026     //  entry:
6027     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6028     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6029     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6030     //    ...
6031     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6032     //    ...
6033     //
6034     // then the last dbg.value is describing a parameter "b" using a value that
6035     // is an argument. But since we already has used %a1 to describe a parameter
6036     // we should not handle that last dbg.value here (that would result in an
6037     // incorrect hoisting of the DBG_VALUE to the function entry).
6038     // Notice that we allow one dbg.value per IR level argument, to accommodate
6039     // for the situation with fragments above.
6040     // If there is no node for the value being handled, we return true to skip
6041     // the normal generation of debug info, as it would kill existing debug
6042     // info for the parameter in case of duplicates.
6043     if (VariableIsFunctionInputArg) {
6044       unsigned ArgNo = Arg->getArgNo();
6045       if (ArgNo >= FuncInfo.DescribedArgs.size())
6046         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6047       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6048         return !NodeMap[V].getNode();
6049       FuncInfo.DescribedArgs.set(ArgNo);
6050     }
6051   }
6052 
6053   bool IsIndirect = false;
6054   std::optional<MachineOperand> Op;
6055   // Some arguments' frame index is recorded during argument lowering.
6056   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6057   if (FI != std::numeric_limits<int>::max())
6058     Op = MachineOperand::CreateFI(FI);
6059 
6060   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
6061   if (!Op && N.getNode()) {
6062     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6063     Register Reg;
6064     if (ArgRegsAndSizes.size() == 1)
6065       Reg = ArgRegsAndSizes.front().first;
6066 
6067     if (Reg && Reg.isVirtual()) {
6068       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6069       Register PR = RegInfo.getLiveInPhysReg(Reg);
6070       if (PR)
6071         Reg = PR;
6072     }
6073     if (Reg) {
6074       Op = MachineOperand::CreateReg(Reg, false);
6075       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6076     }
6077   }
6078 
6079   if (!Op && N.getNode()) {
6080     // Check if frame index is available.
6081     SDValue LCandidate = peekThroughBitcasts(N);
6082     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6083       if (FrameIndexSDNode *FINode =
6084           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6085         Op = MachineOperand::CreateFI(FINode->getIndex());
6086   }
6087 
6088   if (!Op) {
6089     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6090     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
6091                                          SplitRegs) {
6092       unsigned Offset = 0;
6093       for (const auto &RegAndSize : SplitRegs) {
6094         // If the expression is already a fragment, the current register
6095         // offset+size might extend beyond the fragment. In this case, only
6096         // the register bits that are inside the fragment are relevant.
6097         int RegFragmentSizeInBits = RegAndSize.second;
6098         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6099           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6100           // The register is entirely outside the expression fragment,
6101           // so is irrelevant for debug info.
6102           if (Offset >= ExprFragmentSizeInBits)
6103             break;
6104           // The register is partially outside the expression fragment, only
6105           // the low bits within the fragment are relevant for debug info.
6106           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6107             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6108           }
6109         }
6110 
6111         auto FragmentExpr = DIExpression::createFragmentExpression(
6112             Expr, Offset, RegFragmentSizeInBits);
6113         Offset += RegAndSize.second;
6114         // If a valid fragment expression cannot be created, the variable's
6115         // correct value cannot be determined and so it is set as Undef.
6116         if (!FragmentExpr) {
6117           SDDbgValue *SDV = DAG.getConstantDbgValue(
6118               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6119           DAG.AddDbgValue(SDV, false);
6120           continue;
6121         }
6122         MachineInstr *NewMI =
6123             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6124                              Kind != FuncArgumentDbgValueKind::Value);
6125         FuncInfo.ArgDbgValues.push_back(NewMI);
6126       }
6127     };
6128 
6129     // Check if ValueMap has reg number.
6130     DenseMap<const Value *, Register>::const_iterator
6131       VMI = FuncInfo.ValueMap.find(V);
6132     if (VMI != FuncInfo.ValueMap.end()) {
6133       const auto &TLI = DAG.getTargetLoweringInfo();
6134       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6135                        V->getType(), std::nullopt);
6136       if (RFV.occupiesMultipleRegs()) {
6137         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6138         return true;
6139       }
6140 
6141       Op = MachineOperand::CreateReg(VMI->second, false);
6142       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6143     } else if (ArgRegsAndSizes.size() > 1) {
6144       // This was split due to the calling convention, and no virtual register
6145       // mapping exists for the value.
6146       splitMultiRegDbgValue(ArgRegsAndSizes);
6147       return true;
6148     }
6149   }
6150 
6151   if (!Op)
6152     return false;
6153 
6154   assert(Variable->isValidLocationForIntrinsic(DL) &&
6155          "Expected inlined-at fields to agree");
6156   MachineInstr *NewMI = nullptr;
6157 
6158   if (Op->isReg())
6159     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6160   else
6161     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6162                     Variable, Expr);
6163 
6164   // Otherwise, use ArgDbgValues.
6165   FuncInfo.ArgDbgValues.push_back(NewMI);
6166   return true;
6167 }
6168 
6169 /// Return the appropriate SDDbgValue based on N.
6170 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6171                                              DILocalVariable *Variable,
6172                                              DIExpression *Expr,
6173                                              const DebugLoc &dl,
6174                                              unsigned DbgSDNodeOrder) {
6175   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6176     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6177     // stack slot locations.
6178     //
6179     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6180     // debug values here after optimization:
6181     //
6182     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6183     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6184     //
6185     // Both describe the direct values of their associated variables.
6186     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6187                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6188   }
6189   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6190                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6191 }
6192 
6193 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6194   switch (Intrinsic) {
6195   case Intrinsic::smul_fix:
6196     return ISD::SMULFIX;
6197   case Intrinsic::umul_fix:
6198     return ISD::UMULFIX;
6199   case Intrinsic::smul_fix_sat:
6200     return ISD::SMULFIXSAT;
6201   case Intrinsic::umul_fix_sat:
6202     return ISD::UMULFIXSAT;
6203   case Intrinsic::sdiv_fix:
6204     return ISD::SDIVFIX;
6205   case Intrinsic::udiv_fix:
6206     return ISD::UDIVFIX;
6207   case Intrinsic::sdiv_fix_sat:
6208     return ISD::SDIVFIXSAT;
6209   case Intrinsic::udiv_fix_sat:
6210     return ISD::UDIVFIXSAT;
6211   default:
6212     llvm_unreachable("Unhandled fixed point intrinsic");
6213   }
6214 }
6215 
6216 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6217                                            const char *FunctionName) {
6218   assert(FunctionName && "FunctionName must not be nullptr");
6219   SDValue Callee = DAG.getExternalSymbol(
6220       FunctionName,
6221       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6222   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6223 }
6224 
6225 /// Given a @llvm.call.preallocated.setup, return the corresponding
6226 /// preallocated call.
6227 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6228   assert(cast<CallBase>(PreallocatedSetup)
6229                  ->getCalledFunction()
6230                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6231          "expected call_preallocated_setup Value");
6232   for (const auto *U : PreallocatedSetup->users()) {
6233     auto *UseCall = cast<CallBase>(U);
6234     const Function *Fn = UseCall->getCalledFunction();
6235     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6236       return UseCall;
6237     }
6238   }
6239   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6240 }
6241 
6242 /// If DI is a debug value with an EntryValue expression, lower it using the
6243 /// corresponding physical register of the associated Argument value
6244 /// (guaranteed to exist by the verifier).
6245 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6246     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6247     DIExpression *Expr, DebugLoc DbgLoc) {
6248   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6249     return false;
6250 
6251   // These properties are guaranteed by the verifier.
6252   const Argument *Arg = cast<Argument>(Values[0]);
6253   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6254 
6255   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6256   if (ArgIt == FuncInfo.ValueMap.end()) {
6257     LLVM_DEBUG(
6258         dbgs() << "Dropping dbg.value: expression is entry_value but "
6259                   "couldn't find an associated register for the Argument\n");
6260     return true;
6261   }
6262   Register ArgVReg = ArgIt->getSecond();
6263 
6264   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6265     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6266       SDDbgValue *SDV = DAG.getVRegDbgValue(
6267           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6268       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6269       return true;
6270     }
6271   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6272                        "couldn't find a physical register\n");
6273   return true;
6274 }
6275 
6276 /// Lower the call to the specified intrinsic function.
6277 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6278                                                   unsigned Intrinsic) {
6279   SDLoc sdl = getCurSDLoc();
6280   switch (Intrinsic) {
6281   case Intrinsic::experimental_convergence_anchor:
6282     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6283     break;
6284   case Intrinsic::experimental_convergence_entry:
6285     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6286     break;
6287   case Intrinsic::experimental_convergence_loop: {
6288     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6289     auto *Token = Bundle->Inputs[0].get();
6290     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6291                              getValue(Token)));
6292     break;
6293   }
6294   }
6295 }
6296 
6297 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6298                                                unsigned IntrinsicID) {
6299   // For now, we're only lowering an 'add' histogram.
6300   // We can add others later, e.g. saturating adds, min/max.
6301   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6302          "Tried to lower unsupported histogram type");
6303   SDLoc sdl = getCurSDLoc();
6304   Value *Ptr = I.getOperand(0);
6305   SDValue Inc = getValue(I.getOperand(1));
6306   SDValue Mask = getValue(I.getOperand(2));
6307 
6308   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6309   DataLayout TargetDL = DAG.getDataLayout();
6310   EVT VT = Inc.getValueType();
6311   Align Alignment = DAG.getEVTAlign(VT);
6312 
6313   const MDNode *Ranges = getRangeMetadata(I);
6314 
6315   SDValue Root = DAG.getRoot();
6316   SDValue Base;
6317   SDValue Index;
6318   ISD::MemIndexType IndexType;
6319   SDValue Scale;
6320   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6321                                     I.getParent(), VT.getScalarStoreSize());
6322 
6323   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6324 
6325   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6326       MachinePointerInfo(AS),
6327       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6328       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6329 
6330   if (!UniformBase) {
6331     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6332     Index = getValue(Ptr);
6333     IndexType = ISD::SIGNED_SCALED;
6334     Scale =
6335         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6336   }
6337 
6338   EVT IdxVT = Index.getValueType();
6339   EVT EltTy = IdxVT.getVectorElementType();
6340   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6341     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6342     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6343   }
6344 
6345   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6346 
6347   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6348   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6349                                              Ops, MMO, IndexType);
6350 
6351   setValue(&I, Histogram);
6352   DAG.setRoot(Histogram);
6353 }
6354 
6355 /// Lower the call to the specified intrinsic function.
6356 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6357                                              unsigned Intrinsic) {
6358   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6359   SDLoc sdl = getCurSDLoc();
6360   DebugLoc dl = getCurDebugLoc();
6361   SDValue Res;
6362 
6363   SDNodeFlags Flags;
6364   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6365     Flags.copyFMF(*FPOp);
6366 
6367   switch (Intrinsic) {
6368   default:
6369     // By default, turn this into a target intrinsic node.
6370     visitTargetIntrinsic(I, Intrinsic);
6371     return;
6372   case Intrinsic::vscale: {
6373     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6374     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6375     return;
6376   }
6377   case Intrinsic::vastart:  visitVAStart(I); return;
6378   case Intrinsic::vaend:    visitVAEnd(I); return;
6379   case Intrinsic::vacopy:   visitVACopy(I); return;
6380   case Intrinsic::returnaddress:
6381     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6382                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6383                              getValue(I.getArgOperand(0))));
6384     return;
6385   case Intrinsic::addressofreturnaddress:
6386     setValue(&I,
6387              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6388                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6389     return;
6390   case Intrinsic::sponentry:
6391     setValue(&I,
6392              DAG.getNode(ISD::SPONENTRY, sdl,
6393                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6394     return;
6395   case Intrinsic::frameaddress:
6396     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6397                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6398                              getValue(I.getArgOperand(0))));
6399     return;
6400   case Intrinsic::read_volatile_register:
6401   case Intrinsic::read_register: {
6402     Value *Reg = I.getArgOperand(0);
6403     SDValue Chain = getRoot();
6404     SDValue RegName =
6405         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6406     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6407     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6408       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6409     setValue(&I, Res);
6410     DAG.setRoot(Res.getValue(1));
6411     return;
6412   }
6413   case Intrinsic::write_register: {
6414     Value *Reg = I.getArgOperand(0);
6415     Value *RegValue = I.getArgOperand(1);
6416     SDValue Chain = getRoot();
6417     SDValue RegName =
6418         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6419     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6420                             RegName, getValue(RegValue)));
6421     return;
6422   }
6423   case Intrinsic::memcpy: {
6424     const auto &MCI = cast<MemCpyInst>(I);
6425     SDValue Op1 = getValue(I.getArgOperand(0));
6426     SDValue Op2 = getValue(I.getArgOperand(1));
6427     SDValue Op3 = getValue(I.getArgOperand(2));
6428     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6429     Align DstAlign = MCI.getDestAlign().valueOrOne();
6430     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6431     Align Alignment = std::min(DstAlign, SrcAlign);
6432     bool isVol = MCI.isVolatile();
6433     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6434     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6435     // node.
6436     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6437     SDValue MC = DAG.getMemcpy(
6438         Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6439         /* AlwaysInline */ false, isTC, MachinePointerInfo(I.getArgOperand(0)),
6440         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6441     updateDAGForMaybeTailCall(MC);
6442     return;
6443   }
6444   case Intrinsic::memcpy_inline: {
6445     const auto &MCI = cast<MemCpyInlineInst>(I);
6446     SDValue Dst = getValue(I.getArgOperand(0));
6447     SDValue Src = getValue(I.getArgOperand(1));
6448     SDValue Size = getValue(I.getArgOperand(2));
6449     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6450     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6451     Align DstAlign = MCI.getDestAlign().valueOrOne();
6452     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6453     Align Alignment = std::min(DstAlign, SrcAlign);
6454     bool isVol = MCI.isVolatile();
6455     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6456     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6457     // node.
6458     SDValue MC = DAG.getMemcpy(
6459         getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6460         /* AlwaysInline */ true, isTC, MachinePointerInfo(I.getArgOperand(0)),
6461         MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata(), AA);
6462     updateDAGForMaybeTailCall(MC);
6463     return;
6464   }
6465   case Intrinsic::memset: {
6466     const auto &MSI = cast<MemSetInst>(I);
6467     SDValue Op1 = getValue(I.getArgOperand(0));
6468     SDValue Op2 = getValue(I.getArgOperand(1));
6469     SDValue Op3 = getValue(I.getArgOperand(2));
6470     // @llvm.memset defines 0 and 1 to both mean no alignment.
6471     Align Alignment = MSI.getDestAlign().valueOrOne();
6472     bool isVol = MSI.isVolatile();
6473     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6474     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6475     SDValue MS = DAG.getMemset(
6476         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6477         isTC, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6478     updateDAGForMaybeTailCall(MS);
6479     return;
6480   }
6481   case Intrinsic::memset_inline: {
6482     const auto &MSII = cast<MemSetInlineInst>(I);
6483     SDValue Dst = getValue(I.getArgOperand(0));
6484     SDValue Value = getValue(I.getArgOperand(1));
6485     SDValue Size = getValue(I.getArgOperand(2));
6486     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6487     // @llvm.memset defines 0 and 1 to both mean no alignment.
6488     Align DstAlign = MSII.getDestAlign().valueOrOne();
6489     bool isVol = MSII.isVolatile();
6490     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6491     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6492     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6493                                /* AlwaysInline */ true, isTC,
6494                                MachinePointerInfo(I.getArgOperand(0)),
6495                                I.getAAMetadata());
6496     updateDAGForMaybeTailCall(MC);
6497     return;
6498   }
6499   case Intrinsic::memmove: {
6500     const auto &MMI = cast<MemMoveInst>(I);
6501     SDValue Op1 = getValue(I.getArgOperand(0));
6502     SDValue Op2 = getValue(I.getArgOperand(1));
6503     SDValue Op3 = getValue(I.getArgOperand(2));
6504     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6505     Align DstAlign = MMI.getDestAlign().valueOrOne();
6506     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6507     Align Alignment = std::min(DstAlign, SrcAlign);
6508     bool isVol = MMI.isVolatile();
6509     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6510     // FIXME: Support passing different dest/src alignments to the memmove DAG
6511     // node.
6512     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6513     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6514                                 isTC, MachinePointerInfo(I.getArgOperand(0)),
6515                                 MachinePointerInfo(I.getArgOperand(1)),
6516                                 I.getAAMetadata(), AA);
6517     updateDAGForMaybeTailCall(MM);
6518     return;
6519   }
6520   case Intrinsic::memcpy_element_unordered_atomic: {
6521     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6522     SDValue Dst = getValue(MI.getRawDest());
6523     SDValue Src = getValue(MI.getRawSource());
6524     SDValue Length = getValue(MI.getLength());
6525 
6526     Type *LengthTy = MI.getLength()->getType();
6527     unsigned ElemSz = MI.getElementSizeInBytes();
6528     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6529     SDValue MC =
6530         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6531                             isTC, MachinePointerInfo(MI.getRawDest()),
6532                             MachinePointerInfo(MI.getRawSource()));
6533     updateDAGForMaybeTailCall(MC);
6534     return;
6535   }
6536   case Intrinsic::memmove_element_unordered_atomic: {
6537     auto &MI = cast<AtomicMemMoveInst>(I);
6538     SDValue Dst = getValue(MI.getRawDest());
6539     SDValue Src = getValue(MI.getRawSource());
6540     SDValue Length = getValue(MI.getLength());
6541 
6542     Type *LengthTy = MI.getLength()->getType();
6543     unsigned ElemSz = MI.getElementSizeInBytes();
6544     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6545     SDValue MC =
6546         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6547                              isTC, MachinePointerInfo(MI.getRawDest()),
6548                              MachinePointerInfo(MI.getRawSource()));
6549     updateDAGForMaybeTailCall(MC);
6550     return;
6551   }
6552   case Intrinsic::memset_element_unordered_atomic: {
6553     auto &MI = cast<AtomicMemSetInst>(I);
6554     SDValue Dst = getValue(MI.getRawDest());
6555     SDValue Val = getValue(MI.getValue());
6556     SDValue Length = getValue(MI.getLength());
6557 
6558     Type *LengthTy = MI.getLength()->getType();
6559     unsigned ElemSz = MI.getElementSizeInBytes();
6560     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6561     SDValue MC =
6562         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6563                             isTC, MachinePointerInfo(MI.getRawDest()));
6564     updateDAGForMaybeTailCall(MC);
6565     return;
6566   }
6567   case Intrinsic::call_preallocated_setup: {
6568     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6569     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6570     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6571                               getRoot(), SrcValue);
6572     setValue(&I, Res);
6573     DAG.setRoot(Res);
6574     return;
6575   }
6576   case Intrinsic::call_preallocated_arg: {
6577     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6578     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6579     SDValue Ops[3];
6580     Ops[0] = getRoot();
6581     Ops[1] = SrcValue;
6582     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6583                                    MVT::i32); // arg index
6584     SDValue Res = DAG.getNode(
6585         ISD::PREALLOCATED_ARG, sdl,
6586         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6587     setValue(&I, Res);
6588     DAG.setRoot(Res.getValue(1));
6589     return;
6590   }
6591   case Intrinsic::dbg_declare: {
6592     const auto &DI = cast<DbgDeclareInst>(I);
6593     // Debug intrinsics are handled separately in assignment tracking mode.
6594     // Some intrinsics are handled right after Argument lowering.
6595     if (AssignmentTrackingEnabled ||
6596         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6597       return;
6598     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6599     DILocalVariable *Variable = DI.getVariable();
6600     DIExpression *Expression = DI.getExpression();
6601     dropDanglingDebugInfo(Variable, Expression);
6602     // Assume dbg.declare can not currently use DIArgList, i.e.
6603     // it is non-variadic.
6604     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6605     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6606                        DI.getDebugLoc());
6607     return;
6608   }
6609   case Intrinsic::dbg_label: {
6610     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6611     DILabel *Label = DI.getLabel();
6612     assert(Label && "Missing label");
6613 
6614     SDDbgLabel *SDV;
6615     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6616     DAG.AddDbgLabel(SDV);
6617     return;
6618   }
6619   case Intrinsic::dbg_assign: {
6620     // Debug intrinsics are handled separately in assignment tracking mode.
6621     if (AssignmentTrackingEnabled)
6622       return;
6623     // If assignment tracking hasn't been enabled then fall through and treat
6624     // the dbg.assign as a dbg.value.
6625     [[fallthrough]];
6626   }
6627   case Intrinsic::dbg_value: {
6628     // Debug intrinsics are handled separately in assignment tracking mode.
6629     if (AssignmentTrackingEnabled)
6630       return;
6631     const DbgValueInst &DI = cast<DbgValueInst>(I);
6632     assert(DI.getVariable() && "Missing variable");
6633 
6634     DILocalVariable *Variable = DI.getVariable();
6635     DIExpression *Expression = DI.getExpression();
6636     dropDanglingDebugInfo(Variable, Expression);
6637 
6638     if (DI.isKillLocation()) {
6639       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6640       return;
6641     }
6642 
6643     SmallVector<Value *, 4> Values(DI.getValues());
6644     if (Values.empty())
6645       return;
6646 
6647     bool IsVariadic = DI.hasArgList();
6648     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6649                           SDNodeOrder, IsVariadic))
6650       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6651                            DI.getDebugLoc(), SDNodeOrder);
6652     return;
6653   }
6654 
6655   case Intrinsic::eh_typeid_for: {
6656     // Find the type id for the given typeinfo.
6657     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6658     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6659     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6660     setValue(&I, Res);
6661     return;
6662   }
6663 
6664   case Intrinsic::eh_return_i32:
6665   case Intrinsic::eh_return_i64:
6666     DAG.getMachineFunction().setCallsEHReturn(true);
6667     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6668                             MVT::Other,
6669                             getControlRoot(),
6670                             getValue(I.getArgOperand(0)),
6671                             getValue(I.getArgOperand(1))));
6672     return;
6673   case Intrinsic::eh_unwind_init:
6674     DAG.getMachineFunction().setCallsUnwindInit(true);
6675     return;
6676   case Intrinsic::eh_dwarf_cfa:
6677     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6678                              TLI.getPointerTy(DAG.getDataLayout()),
6679                              getValue(I.getArgOperand(0))));
6680     return;
6681   case Intrinsic::eh_sjlj_callsite: {
6682     MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
6683     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6684     assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
6685 
6686     MMI.setCurrentCallSite(CI->getZExtValue());
6687     return;
6688   }
6689   case Intrinsic::eh_sjlj_functioncontext: {
6690     // Get and store the index of the function context.
6691     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6692     AllocaInst *FnCtx =
6693       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6694     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6695     MFI.setFunctionContextIndex(FI);
6696     return;
6697   }
6698   case Intrinsic::eh_sjlj_setjmp: {
6699     SDValue Ops[2];
6700     Ops[0] = getRoot();
6701     Ops[1] = getValue(I.getArgOperand(0));
6702     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6703                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6704     setValue(&I, Op.getValue(0));
6705     DAG.setRoot(Op.getValue(1));
6706     return;
6707   }
6708   case Intrinsic::eh_sjlj_longjmp:
6709     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6710                             getRoot(), getValue(I.getArgOperand(0))));
6711     return;
6712   case Intrinsic::eh_sjlj_setup_dispatch:
6713     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6714                             getRoot()));
6715     return;
6716   case Intrinsic::masked_gather:
6717     visitMaskedGather(I);
6718     return;
6719   case Intrinsic::masked_load:
6720     visitMaskedLoad(I);
6721     return;
6722   case Intrinsic::masked_scatter:
6723     visitMaskedScatter(I);
6724     return;
6725   case Intrinsic::masked_store:
6726     visitMaskedStore(I);
6727     return;
6728   case Intrinsic::masked_expandload:
6729     visitMaskedLoad(I, true /* IsExpanding */);
6730     return;
6731   case Intrinsic::masked_compressstore:
6732     visitMaskedStore(I, true /* IsCompressing */);
6733     return;
6734   case Intrinsic::powi:
6735     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6736                             getValue(I.getArgOperand(1)), DAG));
6737     return;
6738   case Intrinsic::log:
6739     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6740     return;
6741   case Intrinsic::log2:
6742     setValue(&I,
6743              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6744     return;
6745   case Intrinsic::log10:
6746     setValue(&I,
6747              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6748     return;
6749   case Intrinsic::exp:
6750     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6751     return;
6752   case Intrinsic::exp2:
6753     setValue(&I,
6754              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6755     return;
6756   case Intrinsic::pow:
6757     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6758                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6759     return;
6760   case Intrinsic::sqrt:
6761   case Intrinsic::fabs:
6762   case Intrinsic::sin:
6763   case Intrinsic::cos:
6764   case Intrinsic::tan:
6765   case Intrinsic::exp10:
6766   case Intrinsic::floor:
6767   case Intrinsic::ceil:
6768   case Intrinsic::trunc:
6769   case Intrinsic::rint:
6770   case Intrinsic::nearbyint:
6771   case Intrinsic::round:
6772   case Intrinsic::roundeven:
6773   case Intrinsic::canonicalize: {
6774     unsigned Opcode;
6775     // clang-format off
6776     switch (Intrinsic) {
6777     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6778     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6779     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6780     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6781     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6782     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6783     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6784     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6785     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6786     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6787     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6788     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6789     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6790     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6791     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6792     }
6793     // clang-format on
6794 
6795     setValue(&I, DAG.getNode(Opcode, sdl,
6796                              getValue(I.getArgOperand(0)).getValueType(),
6797                              getValue(I.getArgOperand(0)), Flags));
6798     return;
6799   }
6800   case Intrinsic::lround:
6801   case Intrinsic::llround:
6802   case Intrinsic::lrint:
6803   case Intrinsic::llrint: {
6804     unsigned Opcode;
6805     // clang-format off
6806     switch (Intrinsic) {
6807     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6808     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6809     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6810     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6811     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6812     }
6813     // clang-format on
6814 
6815     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6816     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6817                              getValue(I.getArgOperand(0))));
6818     return;
6819   }
6820   case Intrinsic::minnum:
6821     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6822                              getValue(I.getArgOperand(0)).getValueType(),
6823                              getValue(I.getArgOperand(0)),
6824                              getValue(I.getArgOperand(1)), Flags));
6825     return;
6826   case Intrinsic::maxnum:
6827     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6828                              getValue(I.getArgOperand(0)).getValueType(),
6829                              getValue(I.getArgOperand(0)),
6830                              getValue(I.getArgOperand(1)), Flags));
6831     return;
6832   case Intrinsic::minimum:
6833     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6834                              getValue(I.getArgOperand(0)).getValueType(),
6835                              getValue(I.getArgOperand(0)),
6836                              getValue(I.getArgOperand(1)), Flags));
6837     return;
6838   case Intrinsic::maximum:
6839     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6840                              getValue(I.getArgOperand(0)).getValueType(),
6841                              getValue(I.getArgOperand(0)),
6842                              getValue(I.getArgOperand(1)), Flags));
6843     return;
6844   case Intrinsic::minimumnum:
6845     setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
6846                              getValue(I.getArgOperand(0)).getValueType(),
6847                              getValue(I.getArgOperand(0)),
6848                              getValue(I.getArgOperand(1)), Flags));
6849     return;
6850   case Intrinsic::maximumnum:
6851     setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
6852                              getValue(I.getArgOperand(0)).getValueType(),
6853                              getValue(I.getArgOperand(0)),
6854                              getValue(I.getArgOperand(1)), Flags));
6855     return;
6856   case Intrinsic::copysign:
6857     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6858                              getValue(I.getArgOperand(0)).getValueType(),
6859                              getValue(I.getArgOperand(0)),
6860                              getValue(I.getArgOperand(1)), Flags));
6861     return;
6862   case Intrinsic::ldexp:
6863     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6864                              getValue(I.getArgOperand(0)).getValueType(),
6865                              getValue(I.getArgOperand(0)),
6866                              getValue(I.getArgOperand(1)), Flags));
6867     return;
6868   case Intrinsic::frexp: {
6869     SmallVector<EVT, 2> ValueVTs;
6870     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6871     SDVTList VTs = DAG.getVTList(ValueVTs);
6872     setValue(&I,
6873              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6874     return;
6875   }
6876   case Intrinsic::arithmetic_fence: {
6877     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6878                              getValue(I.getArgOperand(0)).getValueType(),
6879                              getValue(I.getArgOperand(0)), Flags));
6880     return;
6881   }
6882   case Intrinsic::fma:
6883     setValue(&I, DAG.getNode(
6884                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6885                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6886                      getValue(I.getArgOperand(2)), Flags));
6887     return;
6888 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6889   case Intrinsic::INTRINSIC:
6890 #include "llvm/IR/ConstrainedOps.def"
6891     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6892     return;
6893 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6894 #include "llvm/IR/VPIntrinsics.def"
6895     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6896     return;
6897   case Intrinsic::fptrunc_round: {
6898     // Get the last argument, the metadata and convert it to an integer in the
6899     // call
6900     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6901     std::optional<RoundingMode> RoundMode =
6902         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6903 
6904     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6905 
6906     // Propagate fast-math-flags from IR to node(s).
6907     SDNodeFlags Flags;
6908     Flags.copyFMF(*cast<FPMathOperator>(&I));
6909     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6910 
6911     SDValue Result;
6912     Result = DAG.getNode(
6913         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6914         DAG.getTargetConstant((int)*RoundMode, sdl,
6915                               TLI.getPointerTy(DAG.getDataLayout())));
6916     setValue(&I, Result);
6917 
6918     return;
6919   }
6920   case Intrinsic::fmuladd: {
6921     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6922     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6923         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6924       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6925                                getValue(I.getArgOperand(0)).getValueType(),
6926                                getValue(I.getArgOperand(0)),
6927                                getValue(I.getArgOperand(1)),
6928                                getValue(I.getArgOperand(2)), Flags));
6929     } else {
6930       // TODO: Intrinsic calls should have fast-math-flags.
6931       SDValue Mul = DAG.getNode(
6932           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6933           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6934       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6935                                 getValue(I.getArgOperand(0)).getValueType(),
6936                                 Mul, getValue(I.getArgOperand(2)), Flags);
6937       setValue(&I, Add);
6938     }
6939     return;
6940   }
6941   case Intrinsic::convert_to_fp16:
6942     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6943                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6944                                          getValue(I.getArgOperand(0)),
6945                                          DAG.getTargetConstant(0, sdl,
6946                                                                MVT::i32))));
6947     return;
6948   case Intrinsic::convert_from_fp16:
6949     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6950                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6951                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6952                                          getValue(I.getArgOperand(0)))));
6953     return;
6954   case Intrinsic::fptosi_sat: {
6955     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6956     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6957                              getValue(I.getArgOperand(0)),
6958                              DAG.getValueType(VT.getScalarType())));
6959     return;
6960   }
6961   case Intrinsic::fptoui_sat: {
6962     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6963     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6964                              getValue(I.getArgOperand(0)),
6965                              DAG.getValueType(VT.getScalarType())));
6966     return;
6967   }
6968   case Intrinsic::set_rounding:
6969     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6970                       {getRoot(), getValue(I.getArgOperand(0))});
6971     setValue(&I, Res);
6972     DAG.setRoot(Res.getValue(0));
6973     return;
6974   case Intrinsic::is_fpclass: {
6975     const DataLayout DLayout = DAG.getDataLayout();
6976     EVT DestVT = TLI.getValueType(DLayout, I.getType());
6977     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
6978     FPClassTest Test = static_cast<FPClassTest>(
6979         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
6980     MachineFunction &MF = DAG.getMachineFunction();
6981     const Function &F = MF.getFunction();
6982     SDValue Op = getValue(I.getArgOperand(0));
6983     SDNodeFlags Flags;
6984     Flags.setNoFPExcept(
6985         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
6986     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
6987     // expansion can use illegal types. Making expansion early allows
6988     // legalizing these types prior to selection.
6989     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
6990       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
6991       setValue(&I, Result);
6992       return;
6993     }
6994 
6995     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
6996     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
6997     setValue(&I, V);
6998     return;
6999   }
7000   case Intrinsic::get_fpenv: {
7001     const DataLayout DLayout = DAG.getDataLayout();
7002     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7003     Align TempAlign = DAG.getEVTAlign(EnvVT);
7004     SDValue Chain = getRoot();
7005     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7006     // and temporary storage in stack.
7007     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7008       Res = DAG.getNode(
7009           ISD::GET_FPENV, sdl,
7010           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7011                         MVT::Other),
7012           Chain);
7013     } else {
7014       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7015       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7016       auto MPI =
7017           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7018       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7019           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7020           TempAlign);
7021       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7022       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7023     }
7024     setValue(&I, Res);
7025     DAG.setRoot(Res.getValue(1));
7026     return;
7027   }
7028   case Intrinsic::set_fpenv: {
7029     const DataLayout DLayout = DAG.getDataLayout();
7030     SDValue Env = getValue(I.getArgOperand(0));
7031     EVT EnvVT = Env.getValueType();
7032     Align TempAlign = DAG.getEVTAlign(EnvVT);
7033     SDValue Chain = getRoot();
7034     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7035     // environment from memory.
7036     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7037       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7038     } else {
7039       // Allocate space in stack, copy environment bits into it and use this
7040       // memory in SET_FPENV_MEM.
7041       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7042       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7043       auto MPI =
7044           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7045       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7046                            MachineMemOperand::MOStore);
7047       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7048           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7049           TempAlign);
7050       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7051     }
7052     DAG.setRoot(Chain);
7053     return;
7054   }
7055   case Intrinsic::reset_fpenv:
7056     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7057     return;
7058   case Intrinsic::get_fpmode:
7059     Res = DAG.getNode(
7060         ISD::GET_FPMODE, sdl,
7061         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7062                       MVT::Other),
7063         DAG.getRoot());
7064     setValue(&I, Res);
7065     DAG.setRoot(Res.getValue(1));
7066     return;
7067   case Intrinsic::set_fpmode:
7068     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7069                       getValue(I.getArgOperand(0)));
7070     DAG.setRoot(Res);
7071     return;
7072   case Intrinsic::reset_fpmode: {
7073     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7074     DAG.setRoot(Res);
7075     return;
7076   }
7077   case Intrinsic::pcmarker: {
7078     SDValue Tmp = getValue(I.getArgOperand(0));
7079     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7080     return;
7081   }
7082   case Intrinsic::readcyclecounter: {
7083     SDValue Op = getRoot();
7084     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7085                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7086     setValue(&I, Res);
7087     DAG.setRoot(Res.getValue(1));
7088     return;
7089   }
7090   case Intrinsic::readsteadycounter: {
7091     SDValue Op = getRoot();
7092     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7093                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7094     setValue(&I, Res);
7095     DAG.setRoot(Res.getValue(1));
7096     return;
7097   }
7098   case Intrinsic::bitreverse:
7099     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7100                              getValue(I.getArgOperand(0)).getValueType(),
7101                              getValue(I.getArgOperand(0))));
7102     return;
7103   case Intrinsic::bswap:
7104     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7105                              getValue(I.getArgOperand(0)).getValueType(),
7106                              getValue(I.getArgOperand(0))));
7107     return;
7108   case Intrinsic::cttz: {
7109     SDValue Arg = getValue(I.getArgOperand(0));
7110     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7111     EVT Ty = Arg.getValueType();
7112     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7113                              sdl, Ty, Arg));
7114     return;
7115   }
7116   case Intrinsic::ctlz: {
7117     SDValue Arg = getValue(I.getArgOperand(0));
7118     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7119     EVT Ty = Arg.getValueType();
7120     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7121                              sdl, Ty, Arg));
7122     return;
7123   }
7124   case Intrinsic::ctpop: {
7125     SDValue Arg = getValue(I.getArgOperand(0));
7126     EVT Ty = Arg.getValueType();
7127     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7128     return;
7129   }
7130   case Intrinsic::fshl:
7131   case Intrinsic::fshr: {
7132     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7133     SDValue X = getValue(I.getArgOperand(0));
7134     SDValue Y = getValue(I.getArgOperand(1));
7135     SDValue Z = getValue(I.getArgOperand(2));
7136     EVT VT = X.getValueType();
7137 
7138     if (X == Y) {
7139       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7140       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7141     } else {
7142       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7143       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7144     }
7145     return;
7146   }
7147   case Intrinsic::sadd_sat: {
7148     SDValue Op1 = getValue(I.getArgOperand(0));
7149     SDValue Op2 = getValue(I.getArgOperand(1));
7150     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7151     return;
7152   }
7153   case Intrinsic::uadd_sat: {
7154     SDValue Op1 = getValue(I.getArgOperand(0));
7155     SDValue Op2 = getValue(I.getArgOperand(1));
7156     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7157     return;
7158   }
7159   case Intrinsic::ssub_sat: {
7160     SDValue Op1 = getValue(I.getArgOperand(0));
7161     SDValue Op2 = getValue(I.getArgOperand(1));
7162     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7163     return;
7164   }
7165   case Intrinsic::usub_sat: {
7166     SDValue Op1 = getValue(I.getArgOperand(0));
7167     SDValue Op2 = getValue(I.getArgOperand(1));
7168     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7169     return;
7170   }
7171   case Intrinsic::sshl_sat: {
7172     SDValue Op1 = getValue(I.getArgOperand(0));
7173     SDValue Op2 = getValue(I.getArgOperand(1));
7174     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7175     return;
7176   }
7177   case Intrinsic::ushl_sat: {
7178     SDValue Op1 = getValue(I.getArgOperand(0));
7179     SDValue Op2 = getValue(I.getArgOperand(1));
7180     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7181     return;
7182   }
7183   case Intrinsic::smul_fix:
7184   case Intrinsic::umul_fix:
7185   case Intrinsic::smul_fix_sat:
7186   case Intrinsic::umul_fix_sat: {
7187     SDValue Op1 = getValue(I.getArgOperand(0));
7188     SDValue Op2 = getValue(I.getArgOperand(1));
7189     SDValue Op3 = getValue(I.getArgOperand(2));
7190     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7191                              Op1.getValueType(), Op1, Op2, Op3));
7192     return;
7193   }
7194   case Intrinsic::sdiv_fix:
7195   case Intrinsic::udiv_fix:
7196   case Intrinsic::sdiv_fix_sat:
7197   case Intrinsic::udiv_fix_sat: {
7198     SDValue Op1 = getValue(I.getArgOperand(0));
7199     SDValue Op2 = getValue(I.getArgOperand(1));
7200     SDValue Op3 = getValue(I.getArgOperand(2));
7201     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7202                               Op1, Op2, Op3, DAG, TLI));
7203     return;
7204   }
7205   case Intrinsic::smax: {
7206     SDValue Op1 = getValue(I.getArgOperand(0));
7207     SDValue Op2 = getValue(I.getArgOperand(1));
7208     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7209     return;
7210   }
7211   case Intrinsic::smin: {
7212     SDValue Op1 = getValue(I.getArgOperand(0));
7213     SDValue Op2 = getValue(I.getArgOperand(1));
7214     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7215     return;
7216   }
7217   case Intrinsic::umax: {
7218     SDValue Op1 = getValue(I.getArgOperand(0));
7219     SDValue Op2 = getValue(I.getArgOperand(1));
7220     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7221     return;
7222   }
7223   case Intrinsic::umin: {
7224     SDValue Op1 = getValue(I.getArgOperand(0));
7225     SDValue Op2 = getValue(I.getArgOperand(1));
7226     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7227     return;
7228   }
7229   case Intrinsic::abs: {
7230     // TODO: Preserve "int min is poison" arg in SDAG?
7231     SDValue Op1 = getValue(I.getArgOperand(0));
7232     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7233     return;
7234   }
7235   case Intrinsic::scmp: {
7236     SDValue Op1 = getValue(I.getArgOperand(0));
7237     SDValue Op2 = getValue(I.getArgOperand(1));
7238     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7239     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7240     break;
7241   }
7242   case Intrinsic::ucmp: {
7243     SDValue Op1 = getValue(I.getArgOperand(0));
7244     SDValue Op2 = getValue(I.getArgOperand(1));
7245     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7246     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7247     break;
7248   }
7249   case Intrinsic::stacksave: {
7250     SDValue Op = getRoot();
7251     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7252     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7253     setValue(&I, Res);
7254     DAG.setRoot(Res.getValue(1));
7255     return;
7256   }
7257   case Intrinsic::stackrestore:
7258     Res = getValue(I.getArgOperand(0));
7259     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7260     return;
7261   case Intrinsic::get_dynamic_area_offset: {
7262     SDValue Op = getRoot();
7263     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7264     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7265     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7266     // target.
7267     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7268       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7269                          " intrinsic!");
7270     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7271                       Op);
7272     DAG.setRoot(Op);
7273     setValue(&I, Res);
7274     return;
7275   }
7276   case Intrinsic::stackguard: {
7277     MachineFunction &MF = DAG.getMachineFunction();
7278     const Module &M = *MF.getFunction().getParent();
7279     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7280     SDValue Chain = getRoot();
7281     if (TLI.useLoadStackGuardNode()) {
7282       Res = getLoadStackGuard(DAG, sdl, Chain);
7283       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7284     } else {
7285       const Value *Global = TLI.getSDagStackGuard(M);
7286       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7287       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7288                         MachinePointerInfo(Global, 0), Align,
7289                         MachineMemOperand::MOVolatile);
7290     }
7291     if (TLI.useStackGuardXorFP())
7292       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7293     DAG.setRoot(Chain);
7294     setValue(&I, Res);
7295     return;
7296   }
7297   case Intrinsic::stackprotector: {
7298     // Emit code into the DAG to store the stack guard onto the stack.
7299     MachineFunction &MF = DAG.getMachineFunction();
7300     MachineFrameInfo &MFI = MF.getFrameInfo();
7301     SDValue Src, Chain = getRoot();
7302 
7303     if (TLI.useLoadStackGuardNode())
7304       Src = getLoadStackGuard(DAG, sdl, Chain);
7305     else
7306       Src = getValue(I.getArgOperand(0));   // The guard's value.
7307 
7308     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7309 
7310     int FI = FuncInfo.StaticAllocaMap[Slot];
7311     MFI.setStackProtectorIndex(FI);
7312     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7313 
7314     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7315 
7316     // Store the stack protector onto the stack.
7317     Res = DAG.getStore(
7318         Chain, sdl, Src, FIN,
7319         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7320         MaybeAlign(), MachineMemOperand::MOVolatile);
7321     setValue(&I, Res);
7322     DAG.setRoot(Res);
7323     return;
7324   }
7325   case Intrinsic::objectsize:
7326     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7327 
7328   case Intrinsic::is_constant:
7329     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7330 
7331   case Intrinsic::annotation:
7332   case Intrinsic::ptr_annotation:
7333   case Intrinsic::launder_invariant_group:
7334   case Intrinsic::strip_invariant_group:
7335     // Drop the intrinsic, but forward the value
7336     setValue(&I, getValue(I.getOperand(0)));
7337     return;
7338 
7339   case Intrinsic::assume:
7340   case Intrinsic::experimental_noalias_scope_decl:
7341   case Intrinsic::var_annotation:
7342   case Intrinsic::sideeffect:
7343     // Discard annotate attributes, noalias scope declarations, assumptions, and
7344     // artificial side-effects.
7345     return;
7346 
7347   case Intrinsic::codeview_annotation: {
7348     // Emit a label associated with this metadata.
7349     MachineFunction &MF = DAG.getMachineFunction();
7350     MCSymbol *Label =
7351         MF.getMMI().getContext().createTempSymbol("annotation", true);
7352     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7353     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7354     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7355     DAG.setRoot(Res);
7356     return;
7357   }
7358 
7359   case Intrinsic::init_trampoline: {
7360     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7361 
7362     SDValue Ops[6];
7363     Ops[0] = getRoot();
7364     Ops[1] = getValue(I.getArgOperand(0));
7365     Ops[2] = getValue(I.getArgOperand(1));
7366     Ops[3] = getValue(I.getArgOperand(2));
7367     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7368     Ops[5] = DAG.getSrcValue(F);
7369 
7370     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7371 
7372     DAG.setRoot(Res);
7373     return;
7374   }
7375   case Intrinsic::adjust_trampoline:
7376     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7377                              TLI.getPointerTy(DAG.getDataLayout()),
7378                              getValue(I.getArgOperand(0))));
7379     return;
7380   case Intrinsic::gcroot: {
7381     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7382            "only valid in functions with gc specified, enforced by Verifier");
7383     assert(GFI && "implied by previous");
7384     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7385     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7386 
7387     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7388     GFI->addStackRoot(FI->getIndex(), TypeMap);
7389     return;
7390   }
7391   case Intrinsic::gcread:
7392   case Intrinsic::gcwrite:
7393     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7394   case Intrinsic::get_rounding:
7395     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7396     setValue(&I, Res);
7397     DAG.setRoot(Res.getValue(1));
7398     return;
7399 
7400   case Intrinsic::expect:
7401     // Just replace __builtin_expect(exp, c) with EXP.
7402     setValue(&I, getValue(I.getArgOperand(0)));
7403     return;
7404 
7405   case Intrinsic::ubsantrap:
7406   case Intrinsic::debugtrap:
7407   case Intrinsic::trap: {
7408     StringRef TrapFuncName =
7409         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7410     if (TrapFuncName.empty()) {
7411       switch (Intrinsic) {
7412       case Intrinsic::trap:
7413         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7414         break;
7415       case Intrinsic::debugtrap:
7416         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7417         break;
7418       case Intrinsic::ubsantrap:
7419         DAG.setRoot(DAG.getNode(
7420             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7421             DAG.getTargetConstant(
7422                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7423                 MVT::i32)));
7424         break;
7425       default: llvm_unreachable("unknown trap intrinsic");
7426       }
7427       return;
7428     }
7429     TargetLowering::ArgListTy Args;
7430     if (Intrinsic == Intrinsic::ubsantrap) {
7431       Args.push_back(TargetLoweringBase::ArgListEntry());
7432       Args[0].Val = I.getArgOperand(0);
7433       Args[0].Node = getValue(Args[0].Val);
7434       Args[0].Ty = Args[0].Val->getType();
7435     }
7436 
7437     TargetLowering::CallLoweringInfo CLI(DAG);
7438     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7439         CallingConv::C, I.getType(),
7440         DAG.getExternalSymbol(TrapFuncName.data(),
7441                               TLI.getPointerTy(DAG.getDataLayout())),
7442         std::move(Args));
7443 
7444     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7445     DAG.setRoot(Result.second);
7446     return;
7447   }
7448 
7449   case Intrinsic::allow_runtime_check:
7450   case Intrinsic::allow_ubsan_check:
7451     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7452     return;
7453 
7454   case Intrinsic::uadd_with_overflow:
7455   case Intrinsic::sadd_with_overflow:
7456   case Intrinsic::usub_with_overflow:
7457   case Intrinsic::ssub_with_overflow:
7458   case Intrinsic::umul_with_overflow:
7459   case Intrinsic::smul_with_overflow: {
7460     ISD::NodeType Op;
7461     switch (Intrinsic) {
7462     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7463     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7464     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7465     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7466     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7467     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7468     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7469     }
7470     SDValue Op1 = getValue(I.getArgOperand(0));
7471     SDValue Op2 = getValue(I.getArgOperand(1));
7472 
7473     EVT ResultVT = Op1.getValueType();
7474     EVT OverflowVT = MVT::i1;
7475     if (ResultVT.isVector())
7476       OverflowVT = EVT::getVectorVT(
7477           *Context, OverflowVT, ResultVT.getVectorElementCount());
7478 
7479     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7480     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7481     return;
7482   }
7483   case Intrinsic::prefetch: {
7484     SDValue Ops[5];
7485     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7486     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7487     Ops[0] = DAG.getRoot();
7488     Ops[1] = getValue(I.getArgOperand(0));
7489     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7490                                    MVT::i32);
7491     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7492                                    MVT::i32);
7493     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7494                                    MVT::i32);
7495     SDValue Result = DAG.getMemIntrinsicNode(
7496         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7497         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7498         /* align */ std::nullopt, Flags);
7499 
7500     // Chain the prefetch in parallel with any pending loads, to stay out of
7501     // the way of later optimizations.
7502     PendingLoads.push_back(Result);
7503     Result = getRoot();
7504     DAG.setRoot(Result);
7505     return;
7506   }
7507   case Intrinsic::lifetime_start:
7508   case Intrinsic::lifetime_end: {
7509     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7510     // Stack coloring is not enabled in O0, discard region information.
7511     if (TM.getOptLevel() == CodeGenOptLevel::None)
7512       return;
7513 
7514     const int64_t ObjectSize =
7515         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7516     Value *const ObjectPtr = I.getArgOperand(1);
7517     SmallVector<const Value *, 4> Allocas;
7518     getUnderlyingObjects(ObjectPtr, Allocas);
7519 
7520     for (const Value *Alloca : Allocas) {
7521       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7522 
7523       // Could not find an Alloca.
7524       if (!LifetimeObject)
7525         continue;
7526 
7527       // First check that the Alloca is static, otherwise it won't have a
7528       // valid frame index.
7529       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7530       if (SI == FuncInfo.StaticAllocaMap.end())
7531         return;
7532 
7533       const int FrameIndex = SI->second;
7534       int64_t Offset;
7535       if (GetPointerBaseWithConstantOffset(
7536               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7537         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7538       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7539                                 Offset);
7540       DAG.setRoot(Res);
7541     }
7542     return;
7543   }
7544   case Intrinsic::pseudoprobe: {
7545     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7546     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7547     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7548     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7549     DAG.setRoot(Res);
7550     return;
7551   }
7552   case Intrinsic::invariant_start:
7553     // Discard region information.
7554     setValue(&I,
7555              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7556     return;
7557   case Intrinsic::invariant_end:
7558     // Discard region information.
7559     return;
7560   case Intrinsic::clear_cache: {
7561     SDValue InputChain = DAG.getRoot();
7562     SDValue StartVal = getValue(I.getArgOperand(0));
7563     SDValue EndVal = getValue(I.getArgOperand(1));
7564     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7565                       {InputChain, StartVal, EndVal});
7566     setValue(&I, Res);
7567     DAG.setRoot(Res);
7568     return;
7569   }
7570   case Intrinsic::donothing:
7571   case Intrinsic::seh_try_begin:
7572   case Intrinsic::seh_scope_begin:
7573   case Intrinsic::seh_try_end:
7574   case Intrinsic::seh_scope_end:
7575     // ignore
7576     return;
7577   case Intrinsic::experimental_stackmap:
7578     visitStackmap(I);
7579     return;
7580   case Intrinsic::experimental_patchpoint_void:
7581   case Intrinsic::experimental_patchpoint:
7582     visitPatchpoint(I);
7583     return;
7584   case Intrinsic::experimental_gc_statepoint:
7585     LowerStatepoint(cast<GCStatepointInst>(I));
7586     return;
7587   case Intrinsic::experimental_gc_result:
7588     visitGCResult(cast<GCResultInst>(I));
7589     return;
7590   case Intrinsic::experimental_gc_relocate:
7591     visitGCRelocate(cast<GCRelocateInst>(I));
7592     return;
7593   case Intrinsic::instrprof_cover:
7594     llvm_unreachable("instrprof failed to lower a cover");
7595   case Intrinsic::instrprof_increment:
7596     llvm_unreachable("instrprof failed to lower an increment");
7597   case Intrinsic::instrprof_timestamp:
7598     llvm_unreachable("instrprof failed to lower a timestamp");
7599   case Intrinsic::instrprof_value_profile:
7600     llvm_unreachable("instrprof failed to lower a value profiling call");
7601   case Intrinsic::instrprof_mcdc_parameters:
7602     llvm_unreachable("instrprof failed to lower mcdc parameters");
7603   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7604     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7605   case Intrinsic::localescape: {
7606     MachineFunction &MF = DAG.getMachineFunction();
7607     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7608 
7609     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7610     // is the same on all targets.
7611     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7612       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7613       if (isa<ConstantPointerNull>(Arg))
7614         continue; // Skip null pointers. They represent a hole in index space.
7615       AllocaInst *Slot = cast<AllocaInst>(Arg);
7616       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7617              "can only escape static allocas");
7618       int FI = FuncInfo.StaticAllocaMap[Slot];
7619       MCSymbol *FrameAllocSym =
7620           MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7621               GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7622       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7623               TII->get(TargetOpcode::LOCAL_ESCAPE))
7624           .addSym(FrameAllocSym)
7625           .addFrameIndex(FI);
7626     }
7627 
7628     return;
7629   }
7630 
7631   case Intrinsic::localrecover: {
7632     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7633     MachineFunction &MF = DAG.getMachineFunction();
7634 
7635     // Get the symbol that defines the frame offset.
7636     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7637     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7638     unsigned IdxVal =
7639         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7640     MCSymbol *FrameAllocSym =
7641         MF.getMMI().getContext().getOrCreateFrameAllocSymbol(
7642             GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7643 
7644     Value *FP = I.getArgOperand(1);
7645     SDValue FPVal = getValue(FP);
7646     EVT PtrVT = FPVal.getValueType();
7647 
7648     // Create a MCSymbol for the label to avoid any target lowering
7649     // that would make this PC relative.
7650     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7651     SDValue OffsetVal =
7652         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7653 
7654     // Add the offset to the FP.
7655     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7656     setValue(&I, Add);
7657 
7658     return;
7659   }
7660 
7661   case Intrinsic::eh_exceptionpointer:
7662   case Intrinsic::eh_exceptioncode: {
7663     // Get the exception pointer vreg, copy from it, and resize it to fit.
7664     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7665     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7666     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7667     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7668     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7669     if (Intrinsic == Intrinsic::eh_exceptioncode)
7670       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7671     setValue(&I, N);
7672     return;
7673   }
7674   case Intrinsic::xray_customevent: {
7675     // Here we want to make sure that the intrinsic behaves as if it has a
7676     // specific calling convention.
7677     const auto &Triple = DAG.getTarget().getTargetTriple();
7678     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7679       return;
7680 
7681     SmallVector<SDValue, 8> Ops;
7682 
7683     // We want to say that we always want the arguments in registers.
7684     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7685     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7686     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7687     SDValue Chain = getRoot();
7688     Ops.push_back(LogEntryVal);
7689     Ops.push_back(StrSizeVal);
7690     Ops.push_back(Chain);
7691 
7692     // We need to enforce the calling convention for the callsite, so that
7693     // argument ordering is enforced correctly, and that register allocation can
7694     // see that some registers may be assumed clobbered and have to preserve
7695     // them across calls to the intrinsic.
7696     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7697                                            sdl, NodeTys, Ops);
7698     SDValue patchableNode = SDValue(MN, 0);
7699     DAG.setRoot(patchableNode);
7700     setValue(&I, patchableNode);
7701     return;
7702   }
7703   case Intrinsic::xray_typedevent: {
7704     // Here we want to make sure that the intrinsic behaves as if it has a
7705     // specific calling convention.
7706     const auto &Triple = DAG.getTarget().getTargetTriple();
7707     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7708       return;
7709 
7710     SmallVector<SDValue, 8> Ops;
7711 
7712     // We want to say that we always want the arguments in registers.
7713     // It's unclear to me how manipulating the selection DAG here forces callers
7714     // to provide arguments in registers instead of on the stack.
7715     SDValue LogTypeId = getValue(I.getArgOperand(0));
7716     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7717     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7718     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7719     SDValue Chain = getRoot();
7720     Ops.push_back(LogTypeId);
7721     Ops.push_back(LogEntryVal);
7722     Ops.push_back(StrSizeVal);
7723     Ops.push_back(Chain);
7724 
7725     // We need to enforce the calling convention for the callsite, so that
7726     // argument ordering is enforced correctly, and that register allocation can
7727     // see that some registers may be assumed clobbered and have to preserve
7728     // them across calls to the intrinsic.
7729     MachineSDNode *MN = DAG.getMachineNode(
7730         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7731     SDValue patchableNode = SDValue(MN, 0);
7732     DAG.setRoot(patchableNode);
7733     setValue(&I, patchableNode);
7734     return;
7735   }
7736   case Intrinsic::experimental_deoptimize:
7737     LowerDeoptimizeCall(&I);
7738     return;
7739   case Intrinsic::experimental_stepvector:
7740     visitStepVector(I);
7741     return;
7742   case Intrinsic::vector_reduce_fadd:
7743   case Intrinsic::vector_reduce_fmul:
7744   case Intrinsic::vector_reduce_add:
7745   case Intrinsic::vector_reduce_mul:
7746   case Intrinsic::vector_reduce_and:
7747   case Intrinsic::vector_reduce_or:
7748   case Intrinsic::vector_reduce_xor:
7749   case Intrinsic::vector_reduce_smax:
7750   case Intrinsic::vector_reduce_smin:
7751   case Intrinsic::vector_reduce_umax:
7752   case Intrinsic::vector_reduce_umin:
7753   case Intrinsic::vector_reduce_fmax:
7754   case Intrinsic::vector_reduce_fmin:
7755   case Intrinsic::vector_reduce_fmaximum:
7756   case Intrinsic::vector_reduce_fminimum:
7757     visitVectorReduce(I, Intrinsic);
7758     return;
7759 
7760   case Intrinsic::icall_branch_funnel: {
7761     SmallVector<SDValue, 16> Ops;
7762     Ops.push_back(getValue(I.getArgOperand(0)));
7763 
7764     int64_t Offset;
7765     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7766         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7767     if (!Base)
7768       report_fatal_error(
7769           "llvm.icall.branch.funnel operand must be a GlobalValue");
7770     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7771 
7772     struct BranchFunnelTarget {
7773       int64_t Offset;
7774       SDValue Target;
7775     };
7776     SmallVector<BranchFunnelTarget, 8> Targets;
7777 
7778     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7779       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7780           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7781       if (ElemBase != Base)
7782         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7783                            "to the same GlobalValue");
7784 
7785       SDValue Val = getValue(I.getArgOperand(Op + 1));
7786       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7787       if (!GA)
7788         report_fatal_error(
7789             "llvm.icall.branch.funnel operand must be a GlobalValue");
7790       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7791                                      GA->getGlobal(), sdl, Val.getValueType(),
7792                                      GA->getOffset())});
7793     }
7794     llvm::sort(Targets,
7795                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7796                  return T1.Offset < T2.Offset;
7797                });
7798 
7799     for (auto &T : Targets) {
7800       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7801       Ops.push_back(T.Target);
7802     }
7803 
7804     Ops.push_back(DAG.getRoot()); // Chain
7805     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7806                                  MVT::Other, Ops),
7807               0);
7808     DAG.setRoot(N);
7809     setValue(&I, N);
7810     HasTailCall = true;
7811     return;
7812   }
7813 
7814   case Intrinsic::wasm_landingpad_index:
7815     // Information this intrinsic contained has been transferred to
7816     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7817     // delete it now.
7818     return;
7819 
7820   case Intrinsic::aarch64_settag:
7821   case Intrinsic::aarch64_settag_zero: {
7822     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7823     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7824     SDValue Val = TSI.EmitTargetCodeForSetTag(
7825         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7826         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7827         ZeroMemory);
7828     DAG.setRoot(Val);
7829     setValue(&I, Val);
7830     return;
7831   }
7832   case Intrinsic::amdgcn_cs_chain: {
7833     assert(I.arg_size() == 5 && "Additional args not supported yet");
7834     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7835            "Non-zero flags not supported yet");
7836 
7837     // At this point we don't care if it's amdgpu_cs_chain or
7838     // amdgpu_cs_chain_preserve.
7839     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7840 
7841     Type *RetTy = I.getType();
7842     assert(RetTy->isVoidTy() && "Should not return");
7843 
7844     SDValue Callee = getValue(I.getOperand(0));
7845 
7846     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7847     // We'll also tack the value of the EXEC mask at the end.
7848     TargetLowering::ArgListTy Args;
7849     Args.reserve(3);
7850 
7851     for (unsigned Idx : {2, 3, 1}) {
7852       TargetLowering::ArgListEntry Arg;
7853       Arg.Node = getValue(I.getOperand(Idx));
7854       Arg.Ty = I.getOperand(Idx)->getType();
7855       Arg.setAttributes(&I, Idx);
7856       Args.push_back(Arg);
7857     }
7858 
7859     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7860     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7861     Args[2].IsInReg = true; // EXEC should be inreg
7862 
7863     TargetLowering::CallLoweringInfo CLI(DAG);
7864     CLI.setDebugLoc(getCurSDLoc())
7865         .setChain(getRoot())
7866         .setCallee(CC, RetTy, Callee, std::move(Args))
7867         .setNoReturn(true)
7868         .setTailCall(true)
7869         .setConvergent(I.isConvergent());
7870     CLI.CB = &I;
7871     std::pair<SDValue, SDValue> Result =
7872         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7873     (void)Result;
7874     assert(!Result.first.getNode() && !Result.second.getNode() &&
7875            "Should've lowered as tail call");
7876 
7877     HasTailCall = true;
7878     return;
7879   }
7880   case Intrinsic::ptrmask: {
7881     SDValue Ptr = getValue(I.getOperand(0));
7882     SDValue Mask = getValue(I.getOperand(1));
7883 
7884     // On arm64_32, pointers are 32 bits when stored in memory, but
7885     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
7886     // match the index type, but the pointer is 64 bits, so the the mask must be
7887     // zero-extended up to 64 bits to match the pointer.
7888     EVT PtrVT =
7889         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7890     EVT MemVT =
7891         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7892     assert(PtrVT == Ptr.getValueType());
7893     assert(MemVT == Mask.getValueType());
7894     if (MemVT != PtrVT)
7895       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
7896 
7897     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7898     return;
7899   }
7900   case Intrinsic::threadlocal_address: {
7901     setValue(&I, getValue(I.getOperand(0)));
7902     return;
7903   }
7904   case Intrinsic::get_active_lane_mask: {
7905     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7906     SDValue Index = getValue(I.getOperand(0));
7907     EVT ElementVT = Index.getValueType();
7908 
7909     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7910       visitTargetIntrinsic(I, Intrinsic);
7911       return;
7912     }
7913 
7914     SDValue TripCount = getValue(I.getOperand(1));
7915     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7916                                  CCVT.getVectorElementCount());
7917 
7918     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7919     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7920     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7921     SDValue VectorInduction = DAG.getNode(
7922         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7923     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7924                                  VectorTripCount, ISD::CondCode::SETULT);
7925     setValue(&I, SetCC);
7926     return;
7927   }
7928   case Intrinsic::experimental_get_vector_length: {
7929     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7930            "Expected positive VF");
7931     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7932     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7933 
7934     SDValue Count = getValue(I.getOperand(0));
7935     EVT CountVT = Count.getValueType();
7936 
7937     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7938       visitTargetIntrinsic(I, Intrinsic);
7939       return;
7940     }
7941 
7942     // Expand to a umin between the trip count and the maximum elements the type
7943     // can hold.
7944     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7945 
7946     // Extend the trip count to at least the result VT.
7947     if (CountVT.bitsLT(VT)) {
7948       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7949       CountVT = VT;
7950     }
7951 
7952     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7953                                          ElementCount::get(VF, IsScalable));
7954 
7955     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7956     // Clip to the result type if needed.
7957     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7958 
7959     setValue(&I, Trunc);
7960     return;
7961   }
7962   case Intrinsic::experimental_cttz_elts: {
7963     auto DL = getCurSDLoc();
7964     SDValue Op = getValue(I.getOperand(0));
7965     EVT OpVT = Op.getValueType();
7966 
7967     if (!TLI.shouldExpandCttzElements(OpVT)) {
7968       visitTargetIntrinsic(I, Intrinsic);
7969       return;
7970     }
7971 
7972     if (OpVT.getScalarType() != MVT::i1) {
7973       // Compare the input vector elements to zero & use to count trailing zeros
7974       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
7975       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
7976                               OpVT.getVectorElementCount());
7977       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
7978     }
7979 
7980     // If the zero-is-poison flag is set, we can assume the upper limit
7981     // of the result is VF-1.
7982     bool ZeroIsPoison =
7983         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
7984     ConstantRange VScaleRange(1, true); // Dummy value.
7985     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
7986       VScaleRange = getVScaleRange(I.getCaller(), 64);
7987     unsigned EltWidth = TLI.getBitWidthForCttzElements(
7988         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
7989 
7990     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
7991 
7992     // Create the new vector type & get the vector length
7993     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
7994                                  OpVT.getVectorElementCount());
7995 
7996     SDValue VL =
7997         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
7998 
7999     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8000     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8001     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8002     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8003     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8004     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8005     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8006 
8007     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8008     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8009 
8010     setValue(&I, Ret);
8011     return;
8012   }
8013   case Intrinsic::vector_insert: {
8014     SDValue Vec = getValue(I.getOperand(0));
8015     SDValue SubVec = getValue(I.getOperand(1));
8016     SDValue Index = getValue(I.getOperand(2));
8017 
8018     // The intrinsic's index type is i64, but the SDNode requires an index type
8019     // suitable for the target. Convert the index as required.
8020     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8021     if (Index.getValueType() != VectorIdxTy)
8022       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8023 
8024     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8025     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8026                              Index));
8027     return;
8028   }
8029   case Intrinsic::vector_extract: {
8030     SDValue Vec = getValue(I.getOperand(0));
8031     SDValue Index = getValue(I.getOperand(1));
8032     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8033 
8034     // The intrinsic's index type is i64, but the SDNode requires an index type
8035     // suitable for the target. Convert the index as required.
8036     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8037     if (Index.getValueType() != VectorIdxTy)
8038       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8039 
8040     setValue(&I,
8041              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8042     return;
8043   }
8044   case Intrinsic::vector_reverse:
8045     visitVectorReverse(I);
8046     return;
8047   case Intrinsic::vector_splice:
8048     visitVectorSplice(I);
8049     return;
8050   case Intrinsic::callbr_landingpad:
8051     visitCallBrLandingPad(I);
8052     return;
8053   case Intrinsic::vector_interleave2:
8054     visitVectorInterleave(I);
8055     return;
8056   case Intrinsic::vector_deinterleave2:
8057     visitVectorDeinterleave(I);
8058     return;
8059   case Intrinsic::experimental_convergence_anchor:
8060   case Intrinsic::experimental_convergence_entry:
8061   case Intrinsic::experimental_convergence_loop:
8062     visitConvergenceControl(I, Intrinsic);
8063     return;
8064   case Intrinsic::experimental_vector_histogram_add: {
8065     visitVectorHistogram(I, Intrinsic);
8066     return;
8067   }
8068   }
8069 }
8070 
8071 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8072     const ConstrainedFPIntrinsic &FPI) {
8073   SDLoc sdl = getCurSDLoc();
8074 
8075   // We do not need to serialize constrained FP intrinsics against
8076   // each other or against (nonvolatile) loads, so they can be
8077   // chained like loads.
8078   SDValue Chain = DAG.getRoot();
8079   SmallVector<SDValue, 4> Opers;
8080   Opers.push_back(Chain);
8081   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8082     Opers.push_back(getValue(FPI.getArgOperand(I)));
8083 
8084   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8085     assert(Result.getNode()->getNumValues() == 2);
8086 
8087     // Push node to the appropriate list so that future instructions can be
8088     // chained up correctly.
8089     SDValue OutChain = Result.getValue(1);
8090     switch (EB) {
8091     case fp::ExceptionBehavior::ebIgnore:
8092       // The only reason why ebIgnore nodes still need to be chained is that
8093       // they might depend on the current rounding mode, and therefore must
8094       // not be moved across instruction that may change that mode.
8095       [[fallthrough]];
8096     case fp::ExceptionBehavior::ebMayTrap:
8097       // These must not be moved across calls or instructions that may change
8098       // floating-point exception masks.
8099       PendingConstrainedFP.push_back(OutChain);
8100       break;
8101     case fp::ExceptionBehavior::ebStrict:
8102       // These must not be moved across calls or instructions that may change
8103       // floating-point exception masks or read floating-point exception flags.
8104       // In addition, they cannot be optimized out even if unused.
8105       PendingConstrainedFPStrict.push_back(OutChain);
8106       break;
8107     }
8108   };
8109 
8110   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8111   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8112   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8113   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8114 
8115   SDNodeFlags Flags;
8116   if (EB == fp::ExceptionBehavior::ebIgnore)
8117     Flags.setNoFPExcept(true);
8118 
8119   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8120     Flags.copyFMF(*FPOp);
8121 
8122   unsigned Opcode;
8123   switch (FPI.getIntrinsicID()) {
8124   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8125 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8126   case Intrinsic::INTRINSIC:                                                   \
8127     Opcode = ISD::STRICT_##DAGN;                                               \
8128     break;
8129 #include "llvm/IR/ConstrainedOps.def"
8130   case Intrinsic::experimental_constrained_fmuladd: {
8131     Opcode = ISD::STRICT_FMA;
8132     // Break fmuladd into fmul and fadd.
8133     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8134         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8135       Opers.pop_back();
8136       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8137       pushOutChain(Mul, EB);
8138       Opcode = ISD::STRICT_FADD;
8139       Opers.clear();
8140       Opers.push_back(Mul.getValue(1));
8141       Opers.push_back(Mul.getValue(0));
8142       Opers.push_back(getValue(FPI.getArgOperand(2)));
8143     }
8144     break;
8145   }
8146   }
8147 
8148   // A few strict DAG nodes carry additional operands that are not
8149   // set up by the default code above.
8150   switch (Opcode) {
8151   default: break;
8152   case ISD::STRICT_FP_ROUND:
8153     Opers.push_back(
8154         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8155     break;
8156   case ISD::STRICT_FSETCC:
8157   case ISD::STRICT_FSETCCS: {
8158     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8159     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8160     if (TM.Options.NoNaNsFPMath)
8161       Condition = getFCmpCodeWithoutNaN(Condition);
8162     Opers.push_back(DAG.getCondCode(Condition));
8163     break;
8164   }
8165   }
8166 
8167   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8168   pushOutChain(Result, EB);
8169 
8170   SDValue FPResult = Result.getValue(0);
8171   setValue(&FPI, FPResult);
8172 }
8173 
8174 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8175   std::optional<unsigned> ResOPC;
8176   switch (VPIntrin.getIntrinsicID()) {
8177   case Intrinsic::vp_ctlz: {
8178     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8179     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8180     break;
8181   }
8182   case Intrinsic::vp_cttz: {
8183     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8184     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8185     break;
8186   }
8187   case Intrinsic::vp_cttz_elts: {
8188     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8189     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8190     break;
8191   }
8192 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8193   case Intrinsic::VPID:                                                        \
8194     ResOPC = ISD::VPSD;                                                        \
8195     break;
8196 #include "llvm/IR/VPIntrinsics.def"
8197   }
8198 
8199   if (!ResOPC)
8200     llvm_unreachable(
8201         "Inconsistency: no SDNode available for this VPIntrinsic!");
8202 
8203   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8204       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8205     if (VPIntrin.getFastMathFlags().allowReassoc())
8206       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8207                                                 : ISD::VP_REDUCE_FMUL;
8208   }
8209 
8210   return *ResOPC;
8211 }
8212 
8213 void SelectionDAGBuilder::visitVPLoad(
8214     const VPIntrinsic &VPIntrin, EVT VT,
8215     const SmallVectorImpl<SDValue> &OpValues) {
8216   SDLoc DL = getCurSDLoc();
8217   Value *PtrOperand = VPIntrin.getArgOperand(0);
8218   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8219   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8220   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8221   SDValue LD;
8222   // Do not serialize variable-length loads of constant memory with
8223   // anything.
8224   if (!Alignment)
8225     Alignment = DAG.getEVTAlign(VT);
8226   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8227   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8228   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8229   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8230       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8231       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8232   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8233                      MMO, false /*IsExpanding */);
8234   if (AddToChain)
8235     PendingLoads.push_back(LD.getValue(1));
8236   setValue(&VPIntrin, LD);
8237 }
8238 
8239 void SelectionDAGBuilder::visitVPGather(
8240     const VPIntrinsic &VPIntrin, EVT VT,
8241     const SmallVectorImpl<SDValue> &OpValues) {
8242   SDLoc DL = getCurSDLoc();
8243   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8244   Value *PtrOperand = VPIntrin.getArgOperand(0);
8245   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8246   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8247   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8248   SDValue LD;
8249   if (!Alignment)
8250     Alignment = DAG.getEVTAlign(VT.getScalarType());
8251   unsigned AS =
8252     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8253   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8254       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8255       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8256   SDValue Base, Index, Scale;
8257   ISD::MemIndexType IndexType;
8258   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8259                                     this, VPIntrin.getParent(),
8260                                     VT.getScalarStoreSize());
8261   if (!UniformBase) {
8262     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8263     Index = getValue(PtrOperand);
8264     IndexType = ISD::SIGNED_SCALED;
8265     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8266   }
8267   EVT IdxVT = Index.getValueType();
8268   EVT EltTy = IdxVT.getVectorElementType();
8269   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8270     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8271     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8272   }
8273   LD = DAG.getGatherVP(
8274       DAG.getVTList(VT, MVT::Other), VT, DL,
8275       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8276       IndexType);
8277   PendingLoads.push_back(LD.getValue(1));
8278   setValue(&VPIntrin, LD);
8279 }
8280 
8281 void SelectionDAGBuilder::visitVPStore(
8282     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8283   SDLoc DL = getCurSDLoc();
8284   Value *PtrOperand = VPIntrin.getArgOperand(1);
8285   EVT VT = OpValues[0].getValueType();
8286   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8287   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8288   SDValue ST;
8289   if (!Alignment)
8290     Alignment = DAG.getEVTAlign(VT);
8291   SDValue Ptr = OpValues[1];
8292   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8293   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8294       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8295       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8296   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8297                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8298                       /* IsTruncating */ false, /*IsCompressing*/ false);
8299   DAG.setRoot(ST);
8300   setValue(&VPIntrin, ST);
8301 }
8302 
8303 void SelectionDAGBuilder::visitVPScatter(
8304     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8305   SDLoc DL = getCurSDLoc();
8306   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8307   Value *PtrOperand = VPIntrin.getArgOperand(1);
8308   EVT VT = OpValues[0].getValueType();
8309   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8310   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8311   SDValue ST;
8312   if (!Alignment)
8313     Alignment = DAG.getEVTAlign(VT.getScalarType());
8314   unsigned AS =
8315       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8316   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8317       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8318       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8319   SDValue Base, Index, Scale;
8320   ISD::MemIndexType IndexType;
8321   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8322                                     this, VPIntrin.getParent(),
8323                                     VT.getScalarStoreSize());
8324   if (!UniformBase) {
8325     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8326     Index = getValue(PtrOperand);
8327     IndexType = ISD::SIGNED_SCALED;
8328     Scale =
8329       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8330   }
8331   EVT IdxVT = Index.getValueType();
8332   EVT EltTy = IdxVT.getVectorElementType();
8333   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8334     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8335     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8336   }
8337   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8338                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8339                          OpValues[2], OpValues[3]},
8340                         MMO, IndexType);
8341   DAG.setRoot(ST);
8342   setValue(&VPIntrin, ST);
8343 }
8344 
8345 void SelectionDAGBuilder::visitVPStridedLoad(
8346     const VPIntrinsic &VPIntrin, EVT VT,
8347     const SmallVectorImpl<SDValue> &OpValues) {
8348   SDLoc DL = getCurSDLoc();
8349   Value *PtrOperand = VPIntrin.getArgOperand(0);
8350   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8351   if (!Alignment)
8352     Alignment = DAG.getEVTAlign(VT.getScalarType());
8353   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8354   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8355   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8356   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8357   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8358   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8359   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8360       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8361       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8362 
8363   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8364                                     OpValues[2], OpValues[3], MMO,
8365                                     false /*IsExpanding*/);
8366 
8367   if (AddToChain)
8368     PendingLoads.push_back(LD.getValue(1));
8369   setValue(&VPIntrin, LD);
8370 }
8371 
8372 void SelectionDAGBuilder::visitVPStridedStore(
8373     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8374   SDLoc DL = getCurSDLoc();
8375   Value *PtrOperand = VPIntrin.getArgOperand(1);
8376   EVT VT = OpValues[0].getValueType();
8377   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8378   if (!Alignment)
8379     Alignment = DAG.getEVTAlign(VT.getScalarType());
8380   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8381   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8382   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8383       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8384       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8385 
8386   SDValue ST = DAG.getStridedStoreVP(
8387       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8388       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8389       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8390       /*IsCompressing*/ false);
8391 
8392   DAG.setRoot(ST);
8393   setValue(&VPIntrin, ST);
8394 }
8395 
8396 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8398   SDLoc DL = getCurSDLoc();
8399 
8400   ISD::CondCode Condition;
8401   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8402   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8403   if (IsFP) {
8404     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8405     // flags, but calls that don't return floating-point types can't be
8406     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8407     Condition = getFCmpCondCode(CondCode);
8408     if (TM.Options.NoNaNsFPMath)
8409       Condition = getFCmpCodeWithoutNaN(Condition);
8410   } else {
8411     Condition = getICmpCondCode(CondCode);
8412   }
8413 
8414   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8415   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8416   // #2 is the condition code
8417   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8418   SDValue EVL = getValue(VPIntrin.getOperand(4));
8419   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8420   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8421          "Unexpected target EVL type");
8422   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8423 
8424   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8425                                                         VPIntrin.getType());
8426   setValue(&VPIntrin,
8427            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8428 }
8429 
8430 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8431     const VPIntrinsic &VPIntrin) {
8432   SDLoc DL = getCurSDLoc();
8433   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8434 
8435   auto IID = VPIntrin.getIntrinsicID();
8436 
8437   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8438     return visitVPCmp(*CmpI);
8439 
8440   SmallVector<EVT, 4> ValueVTs;
8441   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8442   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8443   SDVTList VTs = DAG.getVTList(ValueVTs);
8444 
8445   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8446 
8447   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8448   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8449          "Unexpected target EVL type");
8450 
8451   // Request operands.
8452   SmallVector<SDValue, 7> OpValues;
8453   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8454     auto Op = getValue(VPIntrin.getArgOperand(I));
8455     if (I == EVLParamPos)
8456       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8457     OpValues.push_back(Op);
8458   }
8459 
8460   switch (Opcode) {
8461   default: {
8462     SDNodeFlags SDFlags;
8463     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8464       SDFlags.copyFMF(*FPMO);
8465     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8466     setValue(&VPIntrin, Result);
8467     break;
8468   }
8469   case ISD::VP_LOAD:
8470     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8471     break;
8472   case ISD::VP_GATHER:
8473     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8474     break;
8475   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8476     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8477     break;
8478   case ISD::VP_STORE:
8479     visitVPStore(VPIntrin, OpValues);
8480     break;
8481   case ISD::VP_SCATTER:
8482     visitVPScatter(VPIntrin, OpValues);
8483     break;
8484   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8485     visitVPStridedStore(VPIntrin, OpValues);
8486     break;
8487   case ISD::VP_FMULADD: {
8488     assert(OpValues.size() == 5 && "Unexpected number of operands");
8489     SDNodeFlags SDFlags;
8490     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8491       SDFlags.copyFMF(*FPMO);
8492     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8493         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8494       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8495     } else {
8496       SDValue Mul = DAG.getNode(
8497           ISD::VP_FMUL, DL, VTs,
8498           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8499       SDValue Add =
8500           DAG.getNode(ISD::VP_FADD, DL, VTs,
8501                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8502       setValue(&VPIntrin, Add);
8503     }
8504     break;
8505   }
8506   case ISD::VP_IS_FPCLASS: {
8507     const DataLayout DLayout = DAG.getDataLayout();
8508     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8509     auto Constant = OpValues[1]->getAsZExtVal();
8510     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8511     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8512                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8513     setValue(&VPIntrin, V);
8514     return;
8515   }
8516   case ISD::VP_INTTOPTR: {
8517     SDValue N = OpValues[0];
8518     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8519     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8520     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8521                                OpValues[2]);
8522     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8523                              OpValues[2]);
8524     setValue(&VPIntrin, N);
8525     break;
8526   }
8527   case ISD::VP_PTRTOINT: {
8528     SDValue N = OpValues[0];
8529     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8530                                                           VPIntrin.getType());
8531     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8532                                        VPIntrin.getOperand(0)->getType());
8533     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8534                                OpValues[2]);
8535     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8536                              OpValues[2]);
8537     setValue(&VPIntrin, N);
8538     break;
8539   }
8540   case ISD::VP_ABS:
8541   case ISD::VP_CTLZ:
8542   case ISD::VP_CTLZ_ZERO_UNDEF:
8543   case ISD::VP_CTTZ:
8544   case ISD::VP_CTTZ_ZERO_UNDEF:
8545   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8546   case ISD::VP_CTTZ_ELTS: {
8547     SDValue Result =
8548         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8549     setValue(&VPIntrin, Result);
8550     break;
8551   }
8552   }
8553 }
8554 
8555 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8556                                           const BasicBlock *EHPadBB,
8557                                           MCSymbol *&BeginLabel) {
8558   MachineFunction &MF = DAG.getMachineFunction();
8559   MachineModuleInfo &MMI = MF.getMMI();
8560 
8561   // Insert a label before the invoke call to mark the try range.  This can be
8562   // used to detect deletion of the invoke via the MachineModuleInfo.
8563   BeginLabel = MMI.getContext().createTempSymbol();
8564 
8565   // For SjLj, keep track of which landing pads go with which invokes
8566   // so as to maintain the ordering of pads in the LSDA.
8567   unsigned CallSiteIndex = MMI.getCurrentCallSite();
8568   if (CallSiteIndex) {
8569     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8570     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8571 
8572     // Now that the call site is handled, stop tracking it.
8573     MMI.setCurrentCallSite(0);
8574   }
8575 
8576   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8577 }
8578 
8579 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8580                                         const BasicBlock *EHPadBB,
8581                                         MCSymbol *BeginLabel) {
8582   assert(BeginLabel && "BeginLabel should've been set");
8583 
8584   MachineFunction &MF = DAG.getMachineFunction();
8585   MachineModuleInfo &MMI = MF.getMMI();
8586 
8587   // Insert a label at the end of the invoke call to mark the try range.  This
8588   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8589   MCSymbol *EndLabel = MMI.getContext().createTempSymbol();
8590   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8591 
8592   // Inform MachineModuleInfo of range.
8593   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8594   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8595   // actually use outlined funclets and their LSDA info style.
8596   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8597     assert(II && "II should've been set");
8598     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8599     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8600   } else if (!isScopedEHPersonality(Pers)) {
8601     assert(EHPadBB);
8602     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8603   }
8604 
8605   return Chain;
8606 }
8607 
8608 std::pair<SDValue, SDValue>
8609 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8610                                     const BasicBlock *EHPadBB) {
8611   MCSymbol *BeginLabel = nullptr;
8612 
8613   if (EHPadBB) {
8614     // Both PendingLoads and PendingExports must be flushed here;
8615     // this call might not return.
8616     (void)getRoot();
8617     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8618     CLI.setChain(getRoot());
8619   }
8620 
8621   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8622   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8623 
8624   assert((CLI.IsTailCall || Result.second.getNode()) &&
8625          "Non-null chain expected with non-tail call!");
8626   assert((Result.second.getNode() || !Result.first.getNode()) &&
8627          "Null value expected with tail call!");
8628 
8629   if (!Result.second.getNode()) {
8630     // As a special case, a null chain means that a tail call has been emitted
8631     // and the DAG root is already updated.
8632     HasTailCall = true;
8633 
8634     // Since there's no actual continuation from this block, nothing can be
8635     // relying on us setting vregs for them.
8636     PendingExports.clear();
8637   } else {
8638     DAG.setRoot(Result.second);
8639   }
8640 
8641   if (EHPadBB) {
8642     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8643                            BeginLabel));
8644     Result.second = getRoot();
8645   }
8646 
8647   return Result;
8648 }
8649 
8650 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8651                                       bool isTailCall, bool isMustTailCall,
8652                                       const BasicBlock *EHPadBB,
8653                                       const TargetLowering::PtrAuthInfo *PAI) {
8654   auto &DL = DAG.getDataLayout();
8655   FunctionType *FTy = CB.getFunctionType();
8656   Type *RetTy = CB.getType();
8657 
8658   TargetLowering::ArgListTy Args;
8659   Args.reserve(CB.arg_size());
8660 
8661   const Value *SwiftErrorVal = nullptr;
8662   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8663 
8664   if (isTailCall) {
8665     // Avoid emitting tail calls in functions with the disable-tail-calls
8666     // attribute.
8667     auto *Caller = CB.getParent()->getParent();
8668     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8669         "true" && !isMustTailCall)
8670       isTailCall = false;
8671 
8672     // We can't tail call inside a function with a swifterror argument. Lowering
8673     // does not support this yet. It would have to move into the swifterror
8674     // register before the call.
8675     if (TLI.supportSwiftError() &&
8676         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8677       isTailCall = false;
8678   }
8679 
8680   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8681     TargetLowering::ArgListEntry Entry;
8682     const Value *V = *I;
8683 
8684     // Skip empty types
8685     if (V->getType()->isEmptyTy())
8686       continue;
8687 
8688     SDValue ArgNode = getValue(V);
8689     Entry.Node = ArgNode; Entry.Ty = V->getType();
8690 
8691     Entry.setAttributes(&CB, I - CB.arg_begin());
8692 
8693     // Use swifterror virtual register as input to the call.
8694     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8695       SwiftErrorVal = V;
8696       // We find the virtual register for the actual swifterror argument.
8697       // Instead of using the Value, we use the virtual register instead.
8698       Entry.Node =
8699           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8700                           EVT(TLI.getPointerTy(DL)));
8701     }
8702 
8703     Args.push_back(Entry);
8704 
8705     // If we have an explicit sret argument that is an Instruction, (i.e., it
8706     // might point to function-local memory), we can't meaningfully tail-call.
8707     if (Entry.IsSRet && isa<Instruction>(V))
8708       isTailCall = false;
8709   }
8710 
8711   // If call site has a cfguardtarget operand bundle, create and add an
8712   // additional ArgListEntry.
8713   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8714     TargetLowering::ArgListEntry Entry;
8715     Value *V = Bundle->Inputs[0];
8716     SDValue ArgNode = getValue(V);
8717     Entry.Node = ArgNode;
8718     Entry.Ty = V->getType();
8719     Entry.IsCFGuardTarget = true;
8720     Args.push_back(Entry);
8721   }
8722 
8723   // Check if target-independent constraints permit a tail call here.
8724   // Target-dependent constraints are checked within TLI->LowerCallTo.
8725   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8726     isTailCall = false;
8727 
8728   // Disable tail calls if there is an swifterror argument. Targets have not
8729   // been updated to support tail calls.
8730   if (TLI.supportSwiftError() && SwiftErrorVal)
8731     isTailCall = false;
8732 
8733   ConstantInt *CFIType = nullptr;
8734   if (CB.isIndirectCall()) {
8735     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8736       if (!TLI.supportKCFIBundles())
8737         report_fatal_error(
8738             "Target doesn't support calls with kcfi operand bundles.");
8739       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8740       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8741     }
8742   }
8743 
8744   SDValue ConvControlToken;
8745   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8746     auto *Token = Bundle->Inputs[0].get();
8747     ConvControlToken = getValue(Token);
8748   }
8749 
8750   TargetLowering::CallLoweringInfo CLI(DAG);
8751   CLI.setDebugLoc(getCurSDLoc())
8752       .setChain(getRoot())
8753       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8754       .setTailCall(isTailCall)
8755       .setConvergent(CB.isConvergent())
8756       .setIsPreallocated(
8757           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8758       .setCFIType(CFIType)
8759       .setConvergenceControlToken(ConvControlToken);
8760 
8761   // Set the pointer authentication info if we have it.
8762   if (PAI) {
8763     if (!TLI.supportPtrAuthBundles())
8764       report_fatal_error(
8765           "This target doesn't support calls with ptrauth operand bundles.");
8766     CLI.setPtrAuth(*PAI);
8767   }
8768 
8769   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8770 
8771   if (Result.first.getNode()) {
8772     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8773     setValue(&CB, Result.first);
8774   }
8775 
8776   // The last element of CLI.InVals has the SDValue for swifterror return.
8777   // Here we copy it to a virtual register and update SwiftErrorMap for
8778   // book-keeping.
8779   if (SwiftErrorVal && TLI.supportSwiftError()) {
8780     // Get the last element of InVals.
8781     SDValue Src = CLI.InVals.back();
8782     Register VReg =
8783         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8784     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8785     DAG.setRoot(CopyNode);
8786   }
8787 }
8788 
8789 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8790                              SelectionDAGBuilder &Builder) {
8791   // Check to see if this load can be trivially constant folded, e.g. if the
8792   // input is from a string literal.
8793   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8794     // Cast pointer to the type we really want to load.
8795     Type *LoadTy =
8796         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8797     if (LoadVT.isVector())
8798       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8799 
8800     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8801                                          PointerType::getUnqual(LoadTy));
8802 
8803     if (const Constant *LoadCst =
8804             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8805                                          LoadTy, Builder.DAG.getDataLayout()))
8806       return Builder.getValue(LoadCst);
8807   }
8808 
8809   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8810   // still constant memory, the input chain can be the entry node.
8811   SDValue Root;
8812   bool ConstantMemory = false;
8813 
8814   // Do not serialize (non-volatile) loads of constant memory with anything.
8815   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8816     Root = Builder.DAG.getEntryNode();
8817     ConstantMemory = true;
8818   } else {
8819     // Do not serialize non-volatile loads against each other.
8820     Root = Builder.DAG.getRoot();
8821   }
8822 
8823   SDValue Ptr = Builder.getValue(PtrVal);
8824   SDValue LoadVal =
8825       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8826                           MachinePointerInfo(PtrVal), Align(1));
8827 
8828   if (!ConstantMemory)
8829     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8830   return LoadVal;
8831 }
8832 
8833 /// Record the value for an instruction that produces an integer result,
8834 /// converting the type where necessary.
8835 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8836                                                   SDValue Value,
8837                                                   bool IsSigned) {
8838   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8839                                                     I.getType(), true);
8840   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8841   setValue(&I, Value);
8842 }
8843 
8844 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8845 /// true and lower it. Otherwise return false, and it will be lowered like a
8846 /// normal call.
8847 /// The caller already checked that \p I calls the appropriate LibFunc with a
8848 /// correct prototype.
8849 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8850   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8851   const Value *Size = I.getArgOperand(2);
8852   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8853   if (CSize && CSize->getZExtValue() == 0) {
8854     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8855                                                           I.getType(), true);
8856     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8857     return true;
8858   }
8859 
8860   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8861   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8862       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8863       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8864   if (Res.first.getNode()) {
8865     processIntegerCallValue(I, Res.first, true);
8866     PendingLoads.push_back(Res.second);
8867     return true;
8868   }
8869 
8870   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8871   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8872   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8873     return false;
8874 
8875   // If the target has a fast compare for the given size, it will return a
8876   // preferred load type for that size. Require that the load VT is legal and
8877   // that the target supports unaligned loads of that type. Otherwise, return
8878   // INVALID.
8879   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8880     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8881     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8882     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8883       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8884       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8885       // TODO: Check alignment of src and dest ptrs.
8886       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8887       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8888       if (!TLI.isTypeLegal(LVT) ||
8889           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8890           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8891         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8892     }
8893 
8894     return LVT;
8895   };
8896 
8897   // This turns into unaligned loads. We only do this if the target natively
8898   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8899   // we'll only produce a small number of byte loads.
8900   MVT LoadVT;
8901   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8902   switch (NumBitsToCompare) {
8903   default:
8904     return false;
8905   case 16:
8906     LoadVT = MVT::i16;
8907     break;
8908   case 32:
8909     LoadVT = MVT::i32;
8910     break;
8911   case 64:
8912   case 128:
8913   case 256:
8914     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8915     break;
8916   }
8917 
8918   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8919     return false;
8920 
8921   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8922   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8923 
8924   // Bitcast to a wide integer type if the loads are vectors.
8925   if (LoadVT.isVector()) {
8926     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8927     LoadL = DAG.getBitcast(CmpVT, LoadL);
8928     LoadR = DAG.getBitcast(CmpVT, LoadR);
8929   }
8930 
8931   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8932   processIntegerCallValue(I, Cmp, false);
8933   return true;
8934 }
8935 
8936 /// See if we can lower a memchr call into an optimized form. If so, return
8937 /// true and lower it. Otherwise return false, and it will be lowered like a
8938 /// normal call.
8939 /// The caller already checked that \p I calls the appropriate LibFunc with a
8940 /// correct prototype.
8941 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
8942   const Value *Src = I.getArgOperand(0);
8943   const Value *Char = I.getArgOperand(1);
8944   const Value *Length = I.getArgOperand(2);
8945 
8946   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8947   std::pair<SDValue, SDValue> Res =
8948     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
8949                                 getValue(Src), getValue(Char), getValue(Length),
8950                                 MachinePointerInfo(Src));
8951   if (Res.first.getNode()) {
8952     setValue(&I, Res.first);
8953     PendingLoads.push_back(Res.second);
8954     return true;
8955   }
8956 
8957   return false;
8958 }
8959 
8960 /// See if we can lower a mempcpy call into an optimized form. If so, return
8961 /// true and lower it. Otherwise return false, and it will be lowered like a
8962 /// normal call.
8963 /// The caller already checked that \p I calls the appropriate LibFunc with a
8964 /// correct prototype.
8965 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
8966   SDValue Dst = getValue(I.getArgOperand(0));
8967   SDValue Src = getValue(I.getArgOperand(1));
8968   SDValue Size = getValue(I.getArgOperand(2));
8969 
8970   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
8971   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
8972   // DAG::getMemcpy needs Alignment to be defined.
8973   Align Alignment = std::min(DstAlign, SrcAlign);
8974 
8975   SDLoc sdl = getCurSDLoc();
8976 
8977   // In the mempcpy context we need to pass in a false value for isTailCall
8978   // because the return pointer needs to be adjusted by the size of
8979   // the copied memory.
8980   SDValue Root = getMemoryRoot();
8981   SDValue MC = DAG.getMemcpy(Root, sdl, Dst, Src, Size, Alignment, false, false,
8982                              /*isTailCall=*/false,
8983                              MachinePointerInfo(I.getArgOperand(0)),
8984                              MachinePointerInfo(I.getArgOperand(1)),
8985                              I.getAAMetadata());
8986   assert(MC.getNode() != nullptr &&
8987          "** memcpy should not be lowered as TailCall in mempcpy context **");
8988   DAG.setRoot(MC);
8989 
8990   // Check if Size needs to be truncated or extended.
8991   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
8992 
8993   // Adjust return pointer to point just past the last dst byte.
8994   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
8995                                     Dst, Size);
8996   setValue(&I, DstPlusSize);
8997   return true;
8998 }
8999 
9000 /// See if we can lower a strcpy call into an optimized form.  If so, return
9001 /// true and lower it, otherwise return false and it will be lowered like a
9002 /// normal call.
9003 /// The caller already checked that \p I calls the appropriate LibFunc with a
9004 /// correct prototype.
9005 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9006   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9007 
9008   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9009   std::pair<SDValue, SDValue> Res =
9010     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9011                                 getValue(Arg0), getValue(Arg1),
9012                                 MachinePointerInfo(Arg0),
9013                                 MachinePointerInfo(Arg1), isStpcpy);
9014   if (Res.first.getNode()) {
9015     setValue(&I, Res.first);
9016     DAG.setRoot(Res.second);
9017     return true;
9018   }
9019 
9020   return false;
9021 }
9022 
9023 /// See if we can lower a strcmp call into an optimized form.  If so, return
9024 /// true and lower it, otherwise return false and it will be lowered like a
9025 /// normal call.
9026 /// The caller already checked that \p I calls the appropriate LibFunc with a
9027 /// correct prototype.
9028 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9029   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9030 
9031   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9032   std::pair<SDValue, SDValue> Res =
9033     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9034                                 getValue(Arg0), getValue(Arg1),
9035                                 MachinePointerInfo(Arg0),
9036                                 MachinePointerInfo(Arg1));
9037   if (Res.first.getNode()) {
9038     processIntegerCallValue(I, Res.first, true);
9039     PendingLoads.push_back(Res.second);
9040     return true;
9041   }
9042 
9043   return false;
9044 }
9045 
9046 /// See if we can lower a strlen call into an optimized form.  If so, return
9047 /// true and lower it, otherwise return false and it will be lowered like a
9048 /// normal call.
9049 /// The caller already checked that \p I calls the appropriate LibFunc with a
9050 /// correct prototype.
9051 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9052   const Value *Arg0 = I.getArgOperand(0);
9053 
9054   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9055   std::pair<SDValue, SDValue> Res =
9056     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9057                                 getValue(Arg0), MachinePointerInfo(Arg0));
9058   if (Res.first.getNode()) {
9059     processIntegerCallValue(I, Res.first, false);
9060     PendingLoads.push_back(Res.second);
9061     return true;
9062   }
9063 
9064   return false;
9065 }
9066 
9067 /// See if we can lower a strnlen call into an optimized form.  If so, return
9068 /// true and lower it, otherwise return false and it will be lowered like a
9069 /// normal call.
9070 /// The caller already checked that \p I calls the appropriate LibFunc with a
9071 /// correct prototype.
9072 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9073   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9074 
9075   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9076   std::pair<SDValue, SDValue> Res =
9077     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9078                                  getValue(Arg0), getValue(Arg1),
9079                                  MachinePointerInfo(Arg0));
9080   if (Res.first.getNode()) {
9081     processIntegerCallValue(I, Res.first, false);
9082     PendingLoads.push_back(Res.second);
9083     return true;
9084   }
9085 
9086   return false;
9087 }
9088 
9089 /// See if we can lower a unary floating-point operation into an SDNode with
9090 /// the specified Opcode.  If so, return true and lower it, otherwise return
9091 /// false and it will be lowered like a normal call.
9092 /// The caller already checked that \p I calls the appropriate LibFunc with a
9093 /// correct prototype.
9094 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9095                                               unsigned Opcode) {
9096   // We already checked this call's prototype; verify it doesn't modify errno.
9097   if (!I.onlyReadsMemory())
9098     return false;
9099 
9100   SDNodeFlags Flags;
9101   Flags.copyFMF(cast<FPMathOperator>(I));
9102 
9103   SDValue Tmp = getValue(I.getArgOperand(0));
9104   setValue(&I,
9105            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9106   return true;
9107 }
9108 
9109 /// See if we can lower a binary floating-point operation into an SDNode with
9110 /// the specified Opcode. If so, return true and lower it. Otherwise return
9111 /// false, and it will be lowered like a normal call.
9112 /// The caller already checked that \p I calls the appropriate LibFunc with a
9113 /// correct prototype.
9114 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9115                                                unsigned Opcode) {
9116   // We already checked this call's prototype; verify it doesn't modify errno.
9117   if (!I.onlyReadsMemory())
9118     return false;
9119 
9120   SDNodeFlags Flags;
9121   Flags.copyFMF(cast<FPMathOperator>(I));
9122 
9123   SDValue Tmp0 = getValue(I.getArgOperand(0));
9124   SDValue Tmp1 = getValue(I.getArgOperand(1));
9125   EVT VT = Tmp0.getValueType();
9126   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9127   return true;
9128 }
9129 
9130 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9131   // Handle inline assembly differently.
9132   if (I.isInlineAsm()) {
9133     visitInlineAsm(I);
9134     return;
9135   }
9136 
9137   diagnoseDontCall(I);
9138 
9139   if (Function *F = I.getCalledFunction()) {
9140     if (F->isDeclaration()) {
9141       // Is this an LLVM intrinsic or a target-specific intrinsic?
9142       unsigned IID = F->getIntrinsicID();
9143       if (!IID)
9144         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9145           IID = II->getIntrinsicID(F);
9146 
9147       if (IID) {
9148         visitIntrinsicCall(I, IID);
9149         return;
9150       }
9151     }
9152 
9153     // Check for well-known libc/libm calls.  If the function is internal, it
9154     // can't be a library call.  Don't do the check if marked as nobuiltin for
9155     // some reason or the call site requires strict floating point semantics.
9156     LibFunc Func;
9157     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9158         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9159         LibInfo->hasOptimizedCodeGen(Func)) {
9160       switch (Func) {
9161       default: break;
9162       case LibFunc_bcmp:
9163         if (visitMemCmpBCmpCall(I))
9164           return;
9165         break;
9166       case LibFunc_copysign:
9167       case LibFunc_copysignf:
9168       case LibFunc_copysignl:
9169         // We already checked this call's prototype; verify it doesn't modify
9170         // errno.
9171         if (I.onlyReadsMemory()) {
9172           SDValue LHS = getValue(I.getArgOperand(0));
9173           SDValue RHS = getValue(I.getArgOperand(1));
9174           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9175                                    LHS.getValueType(), LHS, RHS));
9176           return;
9177         }
9178         break;
9179       case LibFunc_fabs:
9180       case LibFunc_fabsf:
9181       case LibFunc_fabsl:
9182         if (visitUnaryFloatCall(I, ISD::FABS))
9183           return;
9184         break;
9185       case LibFunc_fmin:
9186       case LibFunc_fminf:
9187       case LibFunc_fminl:
9188         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9189           return;
9190         break;
9191       case LibFunc_fmax:
9192       case LibFunc_fmaxf:
9193       case LibFunc_fmaxl:
9194         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9195           return;
9196         break;
9197       case LibFunc_fminimum_num:
9198       case LibFunc_fminimum_numf:
9199       case LibFunc_fminimum_numl:
9200         if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM))
9201           return;
9202         break;
9203       case LibFunc_fmaximum_num:
9204       case LibFunc_fmaximum_numf:
9205       case LibFunc_fmaximum_numl:
9206         if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM))
9207           return;
9208         break;
9209       case LibFunc_sin:
9210       case LibFunc_sinf:
9211       case LibFunc_sinl:
9212         if (visitUnaryFloatCall(I, ISD::FSIN))
9213           return;
9214         break;
9215       case LibFunc_cos:
9216       case LibFunc_cosf:
9217       case LibFunc_cosl:
9218         if (visitUnaryFloatCall(I, ISD::FCOS))
9219           return;
9220         break;
9221       case LibFunc_tan:
9222       case LibFunc_tanf:
9223       case LibFunc_tanl:
9224         if (visitUnaryFloatCall(I, ISD::FTAN))
9225           return;
9226         break;
9227       case LibFunc_sqrt:
9228       case LibFunc_sqrtf:
9229       case LibFunc_sqrtl:
9230       case LibFunc_sqrt_finite:
9231       case LibFunc_sqrtf_finite:
9232       case LibFunc_sqrtl_finite:
9233         if (visitUnaryFloatCall(I, ISD::FSQRT))
9234           return;
9235         break;
9236       case LibFunc_floor:
9237       case LibFunc_floorf:
9238       case LibFunc_floorl:
9239         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9240           return;
9241         break;
9242       case LibFunc_nearbyint:
9243       case LibFunc_nearbyintf:
9244       case LibFunc_nearbyintl:
9245         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9246           return;
9247         break;
9248       case LibFunc_ceil:
9249       case LibFunc_ceilf:
9250       case LibFunc_ceill:
9251         if (visitUnaryFloatCall(I, ISD::FCEIL))
9252           return;
9253         break;
9254       case LibFunc_rint:
9255       case LibFunc_rintf:
9256       case LibFunc_rintl:
9257         if (visitUnaryFloatCall(I, ISD::FRINT))
9258           return;
9259         break;
9260       case LibFunc_round:
9261       case LibFunc_roundf:
9262       case LibFunc_roundl:
9263         if (visitUnaryFloatCall(I, ISD::FROUND))
9264           return;
9265         break;
9266       case LibFunc_trunc:
9267       case LibFunc_truncf:
9268       case LibFunc_truncl:
9269         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9270           return;
9271         break;
9272       case LibFunc_log2:
9273       case LibFunc_log2f:
9274       case LibFunc_log2l:
9275         if (visitUnaryFloatCall(I, ISD::FLOG2))
9276           return;
9277         break;
9278       case LibFunc_exp2:
9279       case LibFunc_exp2f:
9280       case LibFunc_exp2l:
9281         if (visitUnaryFloatCall(I, ISD::FEXP2))
9282           return;
9283         break;
9284       case LibFunc_exp10:
9285       case LibFunc_exp10f:
9286       case LibFunc_exp10l:
9287         if (visitUnaryFloatCall(I, ISD::FEXP10))
9288           return;
9289         break;
9290       case LibFunc_ldexp:
9291       case LibFunc_ldexpf:
9292       case LibFunc_ldexpl:
9293         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9294           return;
9295         break;
9296       case LibFunc_memcmp:
9297         if (visitMemCmpBCmpCall(I))
9298           return;
9299         break;
9300       case LibFunc_mempcpy:
9301         if (visitMemPCpyCall(I))
9302           return;
9303         break;
9304       case LibFunc_memchr:
9305         if (visitMemChrCall(I))
9306           return;
9307         break;
9308       case LibFunc_strcpy:
9309         if (visitStrCpyCall(I, false))
9310           return;
9311         break;
9312       case LibFunc_stpcpy:
9313         if (visitStrCpyCall(I, true))
9314           return;
9315         break;
9316       case LibFunc_strcmp:
9317         if (visitStrCmpCall(I))
9318           return;
9319         break;
9320       case LibFunc_strlen:
9321         if (visitStrLenCall(I))
9322           return;
9323         break;
9324       case LibFunc_strnlen:
9325         if (visitStrNLenCall(I))
9326           return;
9327         break;
9328       }
9329     }
9330   }
9331 
9332   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9333     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9334     return;
9335   }
9336 
9337   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9338   // have to do anything here to lower funclet bundles.
9339   // CFGuardTarget bundles are lowered in LowerCallTo.
9340   assert(!I.hasOperandBundlesOtherThan(
9341              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9342               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9343               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9344               LLVMContext::OB_convergencectrl}) &&
9345          "Cannot lower calls with arbitrary operand bundles!");
9346 
9347   SDValue Callee = getValue(I.getCalledOperand());
9348 
9349   if (I.hasDeoptState())
9350     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9351   else
9352     // Check if we can potentially perform a tail call. More detailed checking
9353     // is be done within LowerCallTo, after more information about the call is
9354     // known.
9355     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9356 }
9357 
9358 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9359     const CallBase &CB, const BasicBlock *EHPadBB) {
9360   auto PAB = CB.getOperandBundle("ptrauth");
9361   const Value *CalleeV = CB.getCalledOperand();
9362 
9363   // Gather the call ptrauth data from the operand bundle:
9364   //   [ i32 <key>, i64 <discriminator> ]
9365   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9366   const Value *Discriminator = PAB->Inputs[1];
9367 
9368   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9369   assert(Discriminator->getType()->isIntegerTy(64) &&
9370          "Invalid ptrauth discriminator");
9371 
9372   // Functions should never be ptrauth-called directly.
9373   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9374 
9375   // Otherwise, do an authenticated indirect call.
9376   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9377                                      getValue(Discriminator)};
9378 
9379   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9380               EHPadBB, &PAI);
9381 }
9382 
9383 namespace {
9384 
9385 /// AsmOperandInfo - This contains information for each constraint that we are
9386 /// lowering.
9387 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9388 public:
9389   /// CallOperand - If this is the result output operand or a clobber
9390   /// this is null, otherwise it is the incoming operand to the CallInst.
9391   /// This gets modified as the asm is processed.
9392   SDValue CallOperand;
9393 
9394   /// AssignedRegs - If this is a register or register class operand, this
9395   /// contains the set of register corresponding to the operand.
9396   RegsForValue AssignedRegs;
9397 
9398   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9399     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9400   }
9401 
9402   /// Whether or not this operand accesses memory
9403   bool hasMemory(const TargetLowering &TLI) const {
9404     // Indirect operand accesses access memory.
9405     if (isIndirect)
9406       return true;
9407 
9408     for (const auto &Code : Codes)
9409       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9410         return true;
9411 
9412     return false;
9413   }
9414 };
9415 
9416 
9417 } // end anonymous namespace
9418 
9419 /// Make sure that the output operand \p OpInfo and its corresponding input
9420 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9421 /// out).
9422 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9423                                SDISelAsmOperandInfo &MatchingOpInfo,
9424                                SelectionDAG &DAG) {
9425   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9426     return;
9427 
9428   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9429   const auto &TLI = DAG.getTargetLoweringInfo();
9430 
9431   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9432       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9433                                        OpInfo.ConstraintVT);
9434   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9435       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9436                                        MatchingOpInfo.ConstraintVT);
9437   if ((OpInfo.ConstraintVT.isInteger() !=
9438        MatchingOpInfo.ConstraintVT.isInteger()) ||
9439       (MatchRC.second != InputRC.second)) {
9440     // FIXME: error out in a more elegant fashion
9441     report_fatal_error("Unsupported asm: input constraint"
9442                        " with a matching output constraint of"
9443                        " incompatible type!");
9444   }
9445   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9446 }
9447 
9448 /// Get a direct memory input to behave well as an indirect operand.
9449 /// This may introduce stores, hence the need for a \p Chain.
9450 /// \return The (possibly updated) chain.
9451 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9452                                         SDISelAsmOperandInfo &OpInfo,
9453                                         SelectionDAG &DAG) {
9454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9455 
9456   // If we don't have an indirect input, put it in the constpool if we can,
9457   // otherwise spill it to a stack slot.
9458   // TODO: This isn't quite right. We need to handle these according to
9459   // the addressing mode that the constraint wants. Also, this may take
9460   // an additional register for the computation and we don't want that
9461   // either.
9462 
9463   // If the operand is a float, integer, or vector constant, spill to a
9464   // constant pool entry to get its address.
9465   const Value *OpVal = OpInfo.CallOperandVal;
9466   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9467       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9468     OpInfo.CallOperand = DAG.getConstantPool(
9469         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9470     return Chain;
9471   }
9472 
9473   // Otherwise, create a stack slot and emit a store to it before the asm.
9474   Type *Ty = OpVal->getType();
9475   auto &DL = DAG.getDataLayout();
9476   uint64_t TySize = DL.getTypeAllocSize(Ty);
9477   MachineFunction &MF = DAG.getMachineFunction();
9478   int SSFI = MF.getFrameInfo().CreateStackObject(
9479       TySize, DL.getPrefTypeAlign(Ty), false);
9480   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9481   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9482                             MachinePointerInfo::getFixedStack(MF, SSFI),
9483                             TLI.getMemValueType(DL, Ty));
9484   OpInfo.CallOperand = StackSlot;
9485 
9486   return Chain;
9487 }
9488 
9489 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9490 /// specified operand.  We prefer to assign virtual registers, to allow the
9491 /// register allocator to handle the assignment process.  However, if the asm
9492 /// uses features that we can't model on machineinstrs, we have SDISel do the
9493 /// allocation.  This produces generally horrible, but correct, code.
9494 ///
9495 ///   OpInfo describes the operand
9496 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9497 static std::optional<unsigned>
9498 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9499                      SDISelAsmOperandInfo &OpInfo,
9500                      SDISelAsmOperandInfo &RefOpInfo) {
9501   LLVMContext &Context = *DAG.getContext();
9502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9503 
9504   MachineFunction &MF = DAG.getMachineFunction();
9505   SmallVector<unsigned, 4> Regs;
9506   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9507 
9508   // No work to do for memory/address operands.
9509   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9510       OpInfo.ConstraintType == TargetLowering::C_Address)
9511     return std::nullopt;
9512 
9513   // If this is a constraint for a single physreg, or a constraint for a
9514   // register class, find it.
9515   unsigned AssignedReg;
9516   const TargetRegisterClass *RC;
9517   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9518       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9519   // RC is unset only on failure. Return immediately.
9520   if (!RC)
9521     return std::nullopt;
9522 
9523   // Get the actual register value type.  This is important, because the user
9524   // may have asked for (e.g.) the AX register in i32 type.  We need to
9525   // remember that AX is actually i16 to get the right extension.
9526   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9527 
9528   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9529     // If this is an FP operand in an integer register (or visa versa), or more
9530     // generally if the operand value disagrees with the register class we plan
9531     // to stick it in, fix the operand type.
9532     //
9533     // If this is an input value, the bitcast to the new type is done now.
9534     // Bitcast for output value is done at the end of visitInlineAsm().
9535     if ((OpInfo.Type == InlineAsm::isOutput ||
9536          OpInfo.Type == InlineAsm::isInput) &&
9537         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9538       // Try to convert to the first EVT that the reg class contains.  If the
9539       // types are identical size, use a bitcast to convert (e.g. two differing
9540       // vector types).  Note: output bitcast is done at the end of
9541       // visitInlineAsm().
9542       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9543         // Exclude indirect inputs while they are unsupported because the code
9544         // to perform the load is missing and thus OpInfo.CallOperand still
9545         // refers to the input address rather than the pointed-to value.
9546         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9547           OpInfo.CallOperand =
9548               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9549         OpInfo.ConstraintVT = RegVT;
9550         // If the operand is an FP value and we want it in integer registers,
9551         // use the corresponding integer type. This turns an f64 value into
9552         // i64, which can be passed with two i32 values on a 32-bit machine.
9553       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9554         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9555         if (OpInfo.Type == InlineAsm::isInput)
9556           OpInfo.CallOperand =
9557               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9558         OpInfo.ConstraintVT = VT;
9559       }
9560     }
9561   }
9562 
9563   // No need to allocate a matching input constraint since the constraint it's
9564   // matching to has already been allocated.
9565   if (OpInfo.isMatchingInputConstraint())
9566     return std::nullopt;
9567 
9568   EVT ValueVT = OpInfo.ConstraintVT;
9569   if (OpInfo.ConstraintVT == MVT::Other)
9570     ValueVT = RegVT;
9571 
9572   // Initialize NumRegs.
9573   unsigned NumRegs = 1;
9574   if (OpInfo.ConstraintVT != MVT::Other)
9575     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9576 
9577   // If this is a constraint for a specific physical register, like {r17},
9578   // assign it now.
9579 
9580   // If this associated to a specific register, initialize iterator to correct
9581   // place. If virtual, make sure we have enough registers
9582 
9583   // Initialize iterator if necessary
9584   TargetRegisterClass::iterator I = RC->begin();
9585   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9586 
9587   // Do not check for single registers.
9588   if (AssignedReg) {
9589     I = std::find(I, RC->end(), AssignedReg);
9590     if (I == RC->end()) {
9591       // RC does not contain the selected register, which indicates a
9592       // mismatch between the register and the required type/bitwidth.
9593       return {AssignedReg};
9594     }
9595   }
9596 
9597   for (; NumRegs; --NumRegs, ++I) {
9598     assert(I != RC->end() && "Ran out of registers to allocate!");
9599     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9600     Regs.push_back(R);
9601   }
9602 
9603   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9604   return std::nullopt;
9605 }
9606 
9607 static unsigned
9608 findMatchingInlineAsmOperand(unsigned OperandNo,
9609                              const std::vector<SDValue> &AsmNodeOperands) {
9610   // Scan until we find the definition we already emitted of this operand.
9611   unsigned CurOp = InlineAsm::Op_FirstOperand;
9612   for (; OperandNo; --OperandNo) {
9613     // Advance to the next operand.
9614     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9615     const InlineAsm::Flag F(OpFlag);
9616     assert(
9617         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9618         "Skipped past definitions?");
9619     CurOp += F.getNumOperandRegisters() + 1;
9620   }
9621   return CurOp;
9622 }
9623 
9624 namespace {
9625 
9626 class ExtraFlags {
9627   unsigned Flags = 0;
9628 
9629 public:
9630   explicit ExtraFlags(const CallBase &Call) {
9631     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9632     if (IA->hasSideEffects())
9633       Flags |= InlineAsm::Extra_HasSideEffects;
9634     if (IA->isAlignStack())
9635       Flags |= InlineAsm::Extra_IsAlignStack;
9636     if (Call.isConvergent())
9637       Flags |= InlineAsm::Extra_IsConvergent;
9638     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9639   }
9640 
9641   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9642     // Ideally, we would only check against memory constraints.  However, the
9643     // meaning of an Other constraint can be target-specific and we can't easily
9644     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9645     // for Other constraints as well.
9646     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9647         OpInfo.ConstraintType == TargetLowering::C_Other) {
9648       if (OpInfo.Type == InlineAsm::isInput)
9649         Flags |= InlineAsm::Extra_MayLoad;
9650       else if (OpInfo.Type == InlineAsm::isOutput)
9651         Flags |= InlineAsm::Extra_MayStore;
9652       else if (OpInfo.Type == InlineAsm::isClobber)
9653         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9654     }
9655   }
9656 
9657   unsigned get() const { return Flags; }
9658 };
9659 
9660 } // end anonymous namespace
9661 
9662 static bool isFunction(SDValue Op) {
9663   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9664     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9665       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9666 
9667       // In normal "call dllimport func" instruction (non-inlineasm) it force
9668       // indirect access by specifing call opcode. And usually specially print
9669       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9670       // not do in this way now. (In fact, this is similar with "Data Access"
9671       // action). So here we ignore dllimport function.
9672       if (Fn && !Fn->hasDLLImportStorageClass())
9673         return true;
9674     }
9675   }
9676   return false;
9677 }
9678 
9679 /// visitInlineAsm - Handle a call to an InlineAsm object.
9680 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9681                                          const BasicBlock *EHPadBB) {
9682   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9683 
9684   /// ConstraintOperands - Information about all of the constraints.
9685   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9686 
9687   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9688   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9689       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9690 
9691   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9692   // AsmDialect, MayLoad, MayStore).
9693   bool HasSideEffect = IA->hasSideEffects();
9694   ExtraFlags ExtraInfo(Call);
9695 
9696   for (auto &T : TargetConstraints) {
9697     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9698     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9699 
9700     if (OpInfo.CallOperandVal)
9701       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9702 
9703     if (!HasSideEffect)
9704       HasSideEffect = OpInfo.hasMemory(TLI);
9705 
9706     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9707     // FIXME: Could we compute this on OpInfo rather than T?
9708 
9709     // Compute the constraint code and ConstraintType to use.
9710     TLI.ComputeConstraintToUse(T, SDValue());
9711 
9712     if (T.ConstraintType == TargetLowering::C_Immediate &&
9713         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9714       // We've delayed emitting a diagnostic like the "n" constraint because
9715       // inlining could cause an integer showing up.
9716       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9717                                           "' expects an integer constant "
9718                                           "expression");
9719 
9720     ExtraInfo.update(T);
9721   }
9722 
9723   // We won't need to flush pending loads if this asm doesn't touch
9724   // memory and is nonvolatile.
9725   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9726 
9727   bool EmitEHLabels = isa<InvokeInst>(Call);
9728   if (EmitEHLabels) {
9729     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9730   }
9731   bool IsCallBr = isa<CallBrInst>(Call);
9732 
9733   if (IsCallBr || EmitEHLabels) {
9734     // If this is a callbr or invoke we need to flush pending exports since
9735     // inlineasm_br and invoke are terminators.
9736     // We need to do this before nodes are glued to the inlineasm_br node.
9737     Chain = getControlRoot();
9738   }
9739 
9740   MCSymbol *BeginLabel = nullptr;
9741   if (EmitEHLabels) {
9742     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9743   }
9744 
9745   int OpNo = -1;
9746   SmallVector<StringRef> AsmStrs;
9747   IA->collectAsmStrs(AsmStrs);
9748 
9749   // Second pass over the constraints: compute which constraint option to use.
9750   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9751     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9752       OpNo++;
9753 
9754     // If this is an output operand with a matching input operand, look up the
9755     // matching input. If their types mismatch, e.g. one is an integer, the
9756     // other is floating point, or their sizes are different, flag it as an
9757     // error.
9758     if (OpInfo.hasMatchingInput()) {
9759       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9760       patchMatchingInput(OpInfo, Input, DAG);
9761     }
9762 
9763     // Compute the constraint code and ConstraintType to use.
9764     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9765 
9766     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9767          OpInfo.Type == InlineAsm::isClobber) ||
9768         OpInfo.ConstraintType == TargetLowering::C_Address)
9769       continue;
9770 
9771     // In Linux PIC model, there are 4 cases about value/label addressing:
9772     //
9773     // 1: Function call or Label jmp inside the module.
9774     // 2: Data access (such as global variable, static variable) inside module.
9775     // 3: Function call or Label jmp outside the module.
9776     // 4: Data access (such as global variable) outside the module.
9777     //
9778     // Due to current llvm inline asm architecture designed to not "recognize"
9779     // the asm code, there are quite troubles for us to treat mem addressing
9780     // differently for same value/adress used in different instuctions.
9781     // For example, in pic model, call a func may in plt way or direclty
9782     // pc-related, but lea/mov a function adress may use got.
9783     //
9784     // Here we try to "recognize" function call for the case 1 and case 3 in
9785     // inline asm. And try to adjust the constraint for them.
9786     //
9787     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9788     // label, so here we don't handle jmp function label now, but we need to
9789     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9790     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9791         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9792         TM.getCodeModel() != CodeModel::Large) {
9793       OpInfo.isIndirect = false;
9794       OpInfo.ConstraintType = TargetLowering::C_Address;
9795     }
9796 
9797     // If this is a memory input, and if the operand is not indirect, do what we
9798     // need to provide an address for the memory input.
9799     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9800         !OpInfo.isIndirect) {
9801       assert((OpInfo.isMultipleAlternative ||
9802               (OpInfo.Type == InlineAsm::isInput)) &&
9803              "Can only indirectify direct input operands!");
9804 
9805       // Memory operands really want the address of the value.
9806       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9807 
9808       // There is no longer a Value* corresponding to this operand.
9809       OpInfo.CallOperandVal = nullptr;
9810 
9811       // It is now an indirect operand.
9812       OpInfo.isIndirect = true;
9813     }
9814 
9815   }
9816 
9817   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9818   std::vector<SDValue> AsmNodeOperands;
9819   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9820   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9821       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9822 
9823   // If we have a !srcloc metadata node associated with it, we want to attach
9824   // this to the ultimately generated inline asm machineinstr.  To do this, we
9825   // pass in the third operand as this (potentially null) inline asm MDNode.
9826   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9827   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9828 
9829   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9830   // bits as operand 3.
9831   AsmNodeOperands.push_back(DAG.getTargetConstant(
9832       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9833 
9834   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9835   // this, assign virtual and physical registers for inputs and otput.
9836   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9837     // Assign Registers.
9838     SDISelAsmOperandInfo &RefOpInfo =
9839         OpInfo.isMatchingInputConstraint()
9840             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9841             : OpInfo;
9842     const auto RegError =
9843         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9844     if (RegError) {
9845       const MachineFunction &MF = DAG.getMachineFunction();
9846       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9847       const char *RegName = TRI.getName(*RegError);
9848       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9849                                    "' allocated for constraint '" +
9850                                    Twine(OpInfo.ConstraintCode) +
9851                                    "' does not match required type");
9852       return;
9853     }
9854 
9855     auto DetectWriteToReservedRegister = [&]() {
9856       const MachineFunction &MF = DAG.getMachineFunction();
9857       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9858       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9859         if (Register::isPhysicalRegister(Reg) &&
9860             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9861           const char *RegName = TRI.getName(Reg);
9862           emitInlineAsmError(Call, "write to reserved register '" +
9863                                        Twine(RegName) + "'");
9864           return true;
9865         }
9866       }
9867       return false;
9868     };
9869     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9870             (OpInfo.Type == InlineAsm::isInput &&
9871              !OpInfo.isMatchingInputConstraint())) &&
9872            "Only address as input operand is allowed.");
9873 
9874     switch (OpInfo.Type) {
9875     case InlineAsm::isOutput:
9876       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9877         const InlineAsm::ConstraintCode ConstraintID =
9878             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9879         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9880                "Failed to convert memory constraint code to constraint id.");
9881 
9882         // Add information to the INLINEASM node to know about this output.
9883         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9884         OpFlags.setMemConstraint(ConstraintID);
9885         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9886                                                         MVT::i32));
9887         AsmNodeOperands.push_back(OpInfo.CallOperand);
9888       } else {
9889         // Otherwise, this outputs to a register (directly for C_Register /
9890         // C_RegisterClass, and a target-defined fashion for
9891         // C_Immediate/C_Other). Find a register that we can use.
9892         if (OpInfo.AssignedRegs.Regs.empty()) {
9893           emitInlineAsmError(
9894               Call, "couldn't allocate output register for constraint '" +
9895                         Twine(OpInfo.ConstraintCode) + "'");
9896           return;
9897         }
9898 
9899         if (DetectWriteToReservedRegister())
9900           return;
9901 
9902         // Add information to the INLINEASM node to know that this register is
9903         // set.
9904         OpInfo.AssignedRegs.AddInlineAsmOperands(
9905             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
9906                                   : InlineAsm::Kind::RegDef,
9907             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
9908       }
9909       break;
9910 
9911     case InlineAsm::isInput:
9912     case InlineAsm::isLabel: {
9913       SDValue InOperandVal = OpInfo.CallOperand;
9914 
9915       if (OpInfo.isMatchingInputConstraint()) {
9916         // If this is required to match an output register we have already set,
9917         // just use its register.
9918         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
9919                                                   AsmNodeOperands);
9920         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
9921         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
9922           if (OpInfo.isIndirect) {
9923             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
9924             emitInlineAsmError(Call, "inline asm not supported yet: "
9925                                      "don't know how to handle tied "
9926                                      "indirect register inputs");
9927             return;
9928           }
9929 
9930           SmallVector<unsigned, 4> Regs;
9931           MachineFunction &MF = DAG.getMachineFunction();
9932           MachineRegisterInfo &MRI = MF.getRegInfo();
9933           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9934           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
9935           Register TiedReg = R->getReg();
9936           MVT RegVT = R->getSimpleValueType(0);
9937           const TargetRegisterClass *RC =
9938               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
9939               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
9940                                       : TRI.getMinimalPhysRegClass(TiedReg);
9941           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
9942             Regs.push_back(MRI.createVirtualRegister(RC));
9943 
9944           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
9945 
9946           SDLoc dl = getCurSDLoc();
9947           // Use the produced MatchedRegs object to
9948           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
9949           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
9950                                            OpInfo.getMatchedOperand(), dl, DAG,
9951                                            AsmNodeOperands);
9952           break;
9953         }
9954 
9955         assert(Flag.isMemKind() && "Unknown matching constraint!");
9956         assert(Flag.getNumOperandRegisters() == 1 &&
9957                "Unexpected number of operands");
9958         // Add information to the INLINEASM node to know about this input.
9959         // See InlineAsm.h isUseOperandTiedToDef.
9960         Flag.clearMemConstraint();
9961         Flag.setMatchingOp(OpInfo.getMatchedOperand());
9962         AsmNodeOperands.push_back(DAG.getTargetConstant(
9963             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9964         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
9965         break;
9966       }
9967 
9968       // Treat indirect 'X' constraint as memory.
9969       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
9970           OpInfo.isIndirect)
9971         OpInfo.ConstraintType = TargetLowering::C_Memory;
9972 
9973       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
9974           OpInfo.ConstraintType == TargetLowering::C_Other) {
9975         std::vector<SDValue> Ops;
9976         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
9977                                           Ops, DAG);
9978         if (Ops.empty()) {
9979           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
9980             if (isa<ConstantSDNode>(InOperandVal)) {
9981               emitInlineAsmError(Call, "value out of range for constraint '" +
9982                                            Twine(OpInfo.ConstraintCode) + "'");
9983               return;
9984             }
9985 
9986           emitInlineAsmError(Call,
9987                              "invalid operand for inline asm constraint '" +
9988                                  Twine(OpInfo.ConstraintCode) + "'");
9989           return;
9990         }
9991 
9992         // Add information to the INLINEASM node to know about this input.
9993         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
9994         AsmNodeOperands.push_back(DAG.getTargetConstant(
9995             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9996         llvm::append_range(AsmNodeOperands, Ops);
9997         break;
9998       }
9999 
10000       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10001         assert((OpInfo.isIndirect ||
10002                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10003                "Operand must be indirect to be a mem!");
10004         assert(InOperandVal.getValueType() ==
10005                    TLI.getPointerTy(DAG.getDataLayout()) &&
10006                "Memory operands expect pointer values");
10007 
10008         const InlineAsm::ConstraintCode ConstraintID =
10009             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10010         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10011                "Failed to convert memory constraint code to constraint id.");
10012 
10013         // Add information to the INLINEASM node to know about this input.
10014         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10015         ResOpType.setMemConstraint(ConstraintID);
10016         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10017                                                         getCurSDLoc(),
10018                                                         MVT::i32));
10019         AsmNodeOperands.push_back(InOperandVal);
10020         break;
10021       }
10022 
10023       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10024         const InlineAsm::ConstraintCode ConstraintID =
10025             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10026         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10027                "Failed to convert memory constraint code to constraint id.");
10028 
10029         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10030 
10031         SDValue AsmOp = InOperandVal;
10032         if (isFunction(InOperandVal)) {
10033           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10034           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10035           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10036                                              InOperandVal.getValueType(),
10037                                              GA->getOffset());
10038         }
10039 
10040         // Add information to the INLINEASM node to know about this input.
10041         ResOpType.setMemConstraint(ConstraintID);
10042 
10043         AsmNodeOperands.push_back(
10044             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10045 
10046         AsmNodeOperands.push_back(AsmOp);
10047         break;
10048       }
10049 
10050       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10051           OpInfo.ConstraintType != TargetLowering::C_Register) {
10052         emitInlineAsmError(Call, "unknown asm constraint '" +
10053                                      Twine(OpInfo.ConstraintCode) + "'");
10054         return;
10055       }
10056 
10057       // TODO: Support this.
10058       if (OpInfo.isIndirect) {
10059         emitInlineAsmError(
10060             Call, "Don't know how to handle indirect register inputs yet "
10061                   "for constraint '" +
10062                       Twine(OpInfo.ConstraintCode) + "'");
10063         return;
10064       }
10065 
10066       // Copy the input into the appropriate registers.
10067       if (OpInfo.AssignedRegs.Regs.empty()) {
10068         emitInlineAsmError(Call,
10069                            "couldn't allocate input reg for constraint '" +
10070                                Twine(OpInfo.ConstraintCode) + "'");
10071         return;
10072       }
10073 
10074       if (DetectWriteToReservedRegister())
10075         return;
10076 
10077       SDLoc dl = getCurSDLoc();
10078 
10079       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10080                                         &Call);
10081 
10082       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10083                                                0, dl, DAG, AsmNodeOperands);
10084       break;
10085     }
10086     case InlineAsm::isClobber:
10087       // Add the clobbered value to the operand list, so that the register
10088       // allocator is aware that the physreg got clobbered.
10089       if (!OpInfo.AssignedRegs.Regs.empty())
10090         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10091                                                  false, 0, getCurSDLoc(), DAG,
10092                                                  AsmNodeOperands);
10093       break;
10094     }
10095   }
10096 
10097   // Finish up input operands.  Set the input chain and add the flag last.
10098   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10099   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10100 
10101   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10102   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10103                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10104   Glue = Chain.getValue(1);
10105 
10106   // Do additional work to generate outputs.
10107 
10108   SmallVector<EVT, 1> ResultVTs;
10109   SmallVector<SDValue, 1> ResultValues;
10110   SmallVector<SDValue, 8> OutChains;
10111 
10112   llvm::Type *CallResultType = Call.getType();
10113   ArrayRef<Type *> ResultTypes;
10114   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10115     ResultTypes = StructResult->elements();
10116   else if (!CallResultType->isVoidTy())
10117     ResultTypes = ArrayRef(CallResultType);
10118 
10119   auto CurResultType = ResultTypes.begin();
10120   auto handleRegAssign = [&](SDValue V) {
10121     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10122     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10123     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10124     ++CurResultType;
10125     // If the type of the inline asm call site return value is different but has
10126     // same size as the type of the asm output bitcast it.  One example of this
10127     // is for vectors with different width / number of elements.  This can
10128     // happen for register classes that can contain multiple different value
10129     // types.  The preg or vreg allocated may not have the same VT as was
10130     // expected.
10131     //
10132     // This can also happen for a return value that disagrees with the register
10133     // class it is put in, eg. a double in a general-purpose register on a
10134     // 32-bit machine.
10135     if (ResultVT != V.getValueType() &&
10136         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10137       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10138     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10139              V.getValueType().isInteger()) {
10140       // If a result value was tied to an input value, the computed result
10141       // may have a wider width than the expected result.  Extract the
10142       // relevant portion.
10143       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10144     }
10145     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10146     ResultVTs.push_back(ResultVT);
10147     ResultValues.push_back(V);
10148   };
10149 
10150   // Deal with output operands.
10151   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10152     if (OpInfo.Type == InlineAsm::isOutput) {
10153       SDValue Val;
10154       // Skip trivial output operands.
10155       if (OpInfo.AssignedRegs.Regs.empty())
10156         continue;
10157 
10158       switch (OpInfo.ConstraintType) {
10159       case TargetLowering::C_Register:
10160       case TargetLowering::C_RegisterClass:
10161         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10162                                                   Chain, &Glue, &Call);
10163         break;
10164       case TargetLowering::C_Immediate:
10165       case TargetLowering::C_Other:
10166         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10167                                               OpInfo, DAG);
10168         break;
10169       case TargetLowering::C_Memory:
10170         break; // Already handled.
10171       case TargetLowering::C_Address:
10172         break; // Silence warning.
10173       case TargetLowering::C_Unknown:
10174         assert(false && "Unexpected unknown constraint");
10175       }
10176 
10177       // Indirect output manifest as stores. Record output chains.
10178       if (OpInfo.isIndirect) {
10179         const Value *Ptr = OpInfo.CallOperandVal;
10180         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10181         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10182                                      MachinePointerInfo(Ptr));
10183         OutChains.push_back(Store);
10184       } else {
10185         // generate CopyFromRegs to associated registers.
10186         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10187         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10188           for (const SDValue &V : Val->op_values())
10189             handleRegAssign(V);
10190         } else
10191           handleRegAssign(Val);
10192       }
10193     }
10194   }
10195 
10196   // Set results.
10197   if (!ResultValues.empty()) {
10198     assert(CurResultType == ResultTypes.end() &&
10199            "Mismatch in number of ResultTypes");
10200     assert(ResultValues.size() == ResultTypes.size() &&
10201            "Mismatch in number of output operands in asm result");
10202 
10203     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10204                             DAG.getVTList(ResultVTs), ResultValues);
10205     setValue(&Call, V);
10206   }
10207 
10208   // Collect store chains.
10209   if (!OutChains.empty())
10210     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10211 
10212   if (EmitEHLabels) {
10213     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10214   }
10215 
10216   // Only Update Root if inline assembly has a memory effect.
10217   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10218       EmitEHLabels)
10219     DAG.setRoot(Chain);
10220 }
10221 
10222 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10223                                              const Twine &Message) {
10224   LLVMContext &Ctx = *DAG.getContext();
10225   Ctx.emitError(&Call, Message);
10226 
10227   // Make sure we leave the DAG in a valid state
10228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10229   SmallVector<EVT, 1> ValueVTs;
10230   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10231 
10232   if (ValueVTs.empty())
10233     return;
10234 
10235   SmallVector<SDValue, 1> Ops;
10236   for (unsigned i = 0, e = ValueVTs.size(); i != e; ++i)
10237     Ops.push_back(DAG.getUNDEF(ValueVTs[i]));
10238 
10239   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10240 }
10241 
10242 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10243   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10244                           MVT::Other, getRoot(),
10245                           getValue(I.getArgOperand(0)),
10246                           DAG.getSrcValue(I.getArgOperand(0))));
10247 }
10248 
10249 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10251   const DataLayout &DL = DAG.getDataLayout();
10252   SDValue V = DAG.getVAArg(
10253       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10254       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10255       DL.getABITypeAlign(I.getType()).value());
10256   DAG.setRoot(V.getValue(1));
10257 
10258   if (I.getType()->isPointerTy())
10259     V = DAG.getPtrExtOrTrunc(
10260         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10261   setValue(&I, V);
10262 }
10263 
10264 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10265   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10266                           MVT::Other, getRoot(),
10267                           getValue(I.getArgOperand(0)),
10268                           DAG.getSrcValue(I.getArgOperand(0))));
10269 }
10270 
10271 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10272   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10273                           MVT::Other, getRoot(),
10274                           getValue(I.getArgOperand(0)),
10275                           getValue(I.getArgOperand(1)),
10276                           DAG.getSrcValue(I.getArgOperand(0)),
10277                           DAG.getSrcValue(I.getArgOperand(1))));
10278 }
10279 
10280 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10281                                                     const Instruction &I,
10282                                                     SDValue Op) {
10283   std::optional<ConstantRange> CR = getRange(I);
10284 
10285   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10286     return Op;
10287 
10288   APInt Lo = CR->getUnsignedMin();
10289   if (!Lo.isMinValue())
10290     return Op;
10291 
10292   APInt Hi = CR->getUnsignedMax();
10293   unsigned Bits = std::max(Hi.getActiveBits(),
10294                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10295 
10296   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10297 
10298   SDLoc SL = getCurSDLoc();
10299 
10300   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10301                              DAG.getValueType(SmallVT));
10302   unsigned NumVals = Op.getNode()->getNumValues();
10303   if (NumVals == 1)
10304     return ZExt;
10305 
10306   SmallVector<SDValue, 4> Ops;
10307 
10308   Ops.push_back(ZExt);
10309   for (unsigned I = 1; I != NumVals; ++I)
10310     Ops.push_back(Op.getValue(I));
10311 
10312   return DAG.getMergeValues(Ops, SL);
10313 }
10314 
10315 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10316 /// the call being lowered.
10317 ///
10318 /// This is a helper for lowering intrinsics that follow a target calling
10319 /// convention or require stack pointer adjustment. Only a subset of the
10320 /// intrinsic's operands need to participate in the calling convention.
10321 void SelectionDAGBuilder::populateCallLoweringInfo(
10322     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10323     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10324     AttributeSet RetAttrs, bool IsPatchPoint) {
10325   TargetLowering::ArgListTy Args;
10326   Args.reserve(NumArgs);
10327 
10328   // Populate the argument list.
10329   // Attributes for args start at offset 1, after the return attribute.
10330   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10331        ArgI != ArgE; ++ArgI) {
10332     const Value *V = Call->getOperand(ArgI);
10333 
10334     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10335 
10336     TargetLowering::ArgListEntry Entry;
10337     Entry.Node = getValue(V);
10338     Entry.Ty = V->getType();
10339     Entry.setAttributes(Call, ArgI);
10340     Args.push_back(Entry);
10341   }
10342 
10343   CLI.setDebugLoc(getCurSDLoc())
10344       .setChain(getRoot())
10345       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10346                  RetAttrs)
10347       .setDiscardResult(Call->use_empty())
10348       .setIsPatchPoint(IsPatchPoint)
10349       .setIsPreallocated(
10350           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10351 }
10352 
10353 /// Add a stack map intrinsic call's live variable operands to a stackmap
10354 /// or patchpoint target node's operand list.
10355 ///
10356 /// Constants are converted to TargetConstants purely as an optimization to
10357 /// avoid constant materialization and register allocation.
10358 ///
10359 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10360 /// generate addess computation nodes, and so FinalizeISel can convert the
10361 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10362 /// address materialization and register allocation, but may also be required
10363 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10364 /// alloca in the entry block, then the runtime may assume that the alloca's
10365 /// StackMap location can be read immediately after compilation and that the
10366 /// location is valid at any point during execution (this is similar to the
10367 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10368 /// only available in a register, then the runtime would need to trap when
10369 /// execution reaches the StackMap in order to read the alloca's location.
10370 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10371                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10372                                 SelectionDAGBuilder &Builder) {
10373   SelectionDAG &DAG = Builder.DAG;
10374   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10375     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10376 
10377     // Things on the stack are pointer-typed, meaning that they are already
10378     // legal and can be emitted directly to target nodes.
10379     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10380       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10381     } else {
10382       // Otherwise emit a target independent node to be legalised.
10383       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10384     }
10385   }
10386 }
10387 
10388 /// Lower llvm.experimental.stackmap.
10389 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10390   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10391   //                                  [live variables...])
10392 
10393   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10394 
10395   SDValue Chain, InGlue, Callee;
10396   SmallVector<SDValue, 32> Ops;
10397 
10398   SDLoc DL = getCurSDLoc();
10399   Callee = getValue(CI.getCalledOperand());
10400 
10401   // The stackmap intrinsic only records the live variables (the arguments
10402   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10403   // intrinsic, this won't be lowered to a function call. This means we don't
10404   // have to worry about calling conventions and target specific lowering code.
10405   // Instead we perform the call lowering right here.
10406   //
10407   // chain, flag = CALLSEQ_START(chain, 0, 0)
10408   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10409   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10410   //
10411   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10412   InGlue = Chain.getValue(1);
10413 
10414   // Add the STACKMAP operands, starting with DAG house-keeping.
10415   Ops.push_back(Chain);
10416   Ops.push_back(InGlue);
10417 
10418   // Add the <id>, <numShadowBytes> operands.
10419   //
10420   // These do not require legalisation, and can be emitted directly to target
10421   // constant nodes.
10422   SDValue ID = getValue(CI.getArgOperand(0));
10423   assert(ID.getValueType() == MVT::i64);
10424   SDValue IDConst =
10425       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10426   Ops.push_back(IDConst);
10427 
10428   SDValue Shad = getValue(CI.getArgOperand(1));
10429   assert(Shad.getValueType() == MVT::i32);
10430   SDValue ShadConst =
10431       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10432   Ops.push_back(ShadConst);
10433 
10434   // Add the live variables.
10435   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10436 
10437   // Create the STACKMAP node.
10438   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10439   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10440   InGlue = Chain.getValue(1);
10441 
10442   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10443 
10444   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10445 
10446   // Set the root to the target-lowered call chain.
10447   DAG.setRoot(Chain);
10448 
10449   // Inform the Frame Information that we have a stackmap in this function.
10450   FuncInfo.MF->getFrameInfo().setHasStackMap();
10451 }
10452 
10453 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10454 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10455                                           const BasicBlock *EHPadBB) {
10456   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10457   //                                         i32 <numBytes>,
10458   //                                         i8* <target>,
10459   //                                         i32 <numArgs>,
10460   //                                         [Args...],
10461   //                                         [live variables...])
10462 
10463   CallingConv::ID CC = CB.getCallingConv();
10464   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10465   bool HasDef = !CB.getType()->isVoidTy();
10466   SDLoc dl = getCurSDLoc();
10467   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10468 
10469   // Handle immediate and symbolic callees.
10470   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10471     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10472                                    /*isTarget=*/true);
10473   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10474     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10475                                          SDLoc(SymbolicCallee),
10476                                          SymbolicCallee->getValueType(0));
10477 
10478   // Get the real number of arguments participating in the call <numArgs>
10479   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10480   unsigned NumArgs = NArgVal->getAsZExtVal();
10481 
10482   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10483   // Intrinsics include all meta-operands up to but not including CC.
10484   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10485   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10486          "Not enough arguments provided to the patchpoint intrinsic");
10487 
10488   // For AnyRegCC the arguments are lowered later on manually.
10489   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10490   Type *ReturnTy =
10491       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10492 
10493   TargetLowering::CallLoweringInfo CLI(DAG);
10494   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10495                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10496   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10497 
10498   SDNode *CallEnd = Result.second.getNode();
10499   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10500     CallEnd = CallEnd->getOperand(0).getNode();
10501   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10502     CallEnd = CallEnd->getOperand(0).getNode();
10503 
10504   /// Get a call instruction from the call sequence chain.
10505   /// Tail calls are not allowed.
10506   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10507          "Expected a callseq node.");
10508   SDNode *Call = CallEnd->getOperand(0).getNode();
10509   bool HasGlue = Call->getGluedNode();
10510 
10511   // Replace the target specific call node with the patchable intrinsic.
10512   SmallVector<SDValue, 8> Ops;
10513 
10514   // Push the chain.
10515   Ops.push_back(*(Call->op_begin()));
10516 
10517   // Optionally, push the glue (if any).
10518   if (HasGlue)
10519     Ops.push_back(*(Call->op_end() - 1));
10520 
10521   // Push the register mask info.
10522   if (HasGlue)
10523     Ops.push_back(*(Call->op_end() - 2));
10524   else
10525     Ops.push_back(*(Call->op_end() - 1));
10526 
10527   // Add the <id> and <numBytes> constants.
10528   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10529   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10530   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10531   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10532 
10533   // Add the callee.
10534   Ops.push_back(Callee);
10535 
10536   // Adjust <numArgs> to account for any arguments that have been passed on the
10537   // stack instead.
10538   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10539   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10540   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10541   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10542 
10543   // Add the calling convention
10544   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10545 
10546   // Add the arguments we omitted previously. The register allocator should
10547   // place these in any free register.
10548   if (IsAnyRegCC)
10549     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10550       Ops.push_back(getValue(CB.getArgOperand(i)));
10551 
10552   // Push the arguments from the call instruction.
10553   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10554   Ops.append(Call->op_begin() + 2, e);
10555 
10556   // Push live variables for the stack map.
10557   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10558 
10559   SDVTList NodeTys;
10560   if (IsAnyRegCC && HasDef) {
10561     // Create the return types based on the intrinsic definition
10562     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10563     SmallVector<EVT, 3> ValueVTs;
10564     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10565     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10566 
10567     // There is always a chain and a glue type at the end
10568     ValueVTs.push_back(MVT::Other);
10569     ValueVTs.push_back(MVT::Glue);
10570     NodeTys = DAG.getVTList(ValueVTs);
10571   } else
10572     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10573 
10574   // Replace the target specific call node with a PATCHPOINT node.
10575   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10576 
10577   // Update the NodeMap.
10578   if (HasDef) {
10579     if (IsAnyRegCC)
10580       setValue(&CB, SDValue(PPV.getNode(), 0));
10581     else
10582       setValue(&CB, Result.first);
10583   }
10584 
10585   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10586   // call sequence. Furthermore the location of the chain and glue can change
10587   // when the AnyReg calling convention is used and the intrinsic returns a
10588   // value.
10589   if (IsAnyRegCC && HasDef) {
10590     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10591     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10592     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10593   } else
10594     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10595   DAG.DeleteNode(Call);
10596 
10597   // Inform the Frame Information that we have a patchpoint in this function.
10598   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10599 }
10600 
10601 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10602                                             unsigned Intrinsic) {
10603   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10604   SDValue Op1 = getValue(I.getArgOperand(0));
10605   SDValue Op2;
10606   if (I.arg_size() > 1)
10607     Op2 = getValue(I.getArgOperand(1));
10608   SDLoc dl = getCurSDLoc();
10609   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10610   SDValue Res;
10611   SDNodeFlags SDFlags;
10612   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10613     SDFlags.copyFMF(*FPMO);
10614 
10615   switch (Intrinsic) {
10616   case Intrinsic::vector_reduce_fadd:
10617     if (SDFlags.hasAllowReassociation())
10618       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10619                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10620                         SDFlags);
10621     else
10622       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10623     break;
10624   case Intrinsic::vector_reduce_fmul:
10625     if (SDFlags.hasAllowReassociation())
10626       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10627                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10628                         SDFlags);
10629     else
10630       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10631     break;
10632   case Intrinsic::vector_reduce_add:
10633     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10634     break;
10635   case Intrinsic::vector_reduce_mul:
10636     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10637     break;
10638   case Intrinsic::vector_reduce_and:
10639     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10640     break;
10641   case Intrinsic::vector_reduce_or:
10642     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10643     break;
10644   case Intrinsic::vector_reduce_xor:
10645     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10646     break;
10647   case Intrinsic::vector_reduce_smax:
10648     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10649     break;
10650   case Intrinsic::vector_reduce_smin:
10651     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10652     break;
10653   case Intrinsic::vector_reduce_umax:
10654     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10655     break;
10656   case Intrinsic::vector_reduce_umin:
10657     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10658     break;
10659   case Intrinsic::vector_reduce_fmax:
10660     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10661     break;
10662   case Intrinsic::vector_reduce_fmin:
10663     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10664     break;
10665   case Intrinsic::vector_reduce_fmaximum:
10666     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10667     break;
10668   case Intrinsic::vector_reduce_fminimum:
10669     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10670     break;
10671   case Intrinsic::vector_reduce_fmaximumnum:
10672     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUMNUM, dl, VT, Op1, SDFlags);
10673     break;
10674   case Intrinsic::vector_reduce_fminimumnum:
10675     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUMNUM, dl, VT, Op1, SDFlags);
10676     break;
10677   default:
10678     llvm_unreachable("Unhandled vector reduce intrinsic");
10679   }
10680   setValue(&I, Res);
10681 }
10682 
10683 /// Returns an AttributeList representing the attributes applied to the return
10684 /// value of the given call.
10685 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10686   SmallVector<Attribute::AttrKind, 2> Attrs;
10687   if (CLI.RetSExt)
10688     Attrs.push_back(Attribute::SExt);
10689   if (CLI.RetZExt)
10690     Attrs.push_back(Attribute::ZExt);
10691   if (CLI.IsInReg)
10692     Attrs.push_back(Attribute::InReg);
10693 
10694   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10695                             Attrs);
10696 }
10697 
10698 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10699 /// implementation, which just calls LowerCall.
10700 /// FIXME: When all targets are
10701 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10702 std::pair<SDValue, SDValue>
10703 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10704   // Handle the incoming return values from the call.
10705   CLI.Ins.clear();
10706   Type *OrigRetTy = CLI.RetTy;
10707   SmallVector<EVT, 4> RetTys;
10708   SmallVector<TypeSize, 4> Offsets;
10709   auto &DL = CLI.DAG.getDataLayout();
10710   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10711 
10712   if (CLI.IsPostTypeLegalization) {
10713     // If we are lowering a libcall after legalization, split the return type.
10714     SmallVector<EVT, 4> OldRetTys;
10715     SmallVector<TypeSize, 4> OldOffsets;
10716     RetTys.swap(OldRetTys);
10717     Offsets.swap(OldOffsets);
10718 
10719     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10720       EVT RetVT = OldRetTys[i];
10721       uint64_t Offset = OldOffsets[i];
10722       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10723       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10724       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10725       RetTys.append(NumRegs, RegisterVT);
10726       for (unsigned j = 0; j != NumRegs; ++j)
10727         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10728     }
10729   }
10730 
10731   SmallVector<ISD::OutputArg, 4> Outs;
10732   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10733 
10734   bool CanLowerReturn =
10735       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10736                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10737 
10738   SDValue DemoteStackSlot;
10739   int DemoteStackIdx = -100;
10740   if (!CanLowerReturn) {
10741     // FIXME: equivalent assert?
10742     // assert(!CS.hasInAllocaArgument() &&
10743     //        "sret demotion is incompatible with inalloca");
10744     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10745     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10746     MachineFunction &MF = CLI.DAG.getMachineFunction();
10747     DemoteStackIdx =
10748         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10749     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10750                                               DL.getAllocaAddrSpace());
10751 
10752     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10753     ArgListEntry Entry;
10754     Entry.Node = DemoteStackSlot;
10755     Entry.Ty = StackSlotPtrType;
10756     Entry.IsSExt = false;
10757     Entry.IsZExt = false;
10758     Entry.IsInReg = false;
10759     Entry.IsSRet = true;
10760     Entry.IsNest = false;
10761     Entry.IsByVal = false;
10762     Entry.IsByRef = false;
10763     Entry.IsReturned = false;
10764     Entry.IsSwiftSelf = false;
10765     Entry.IsSwiftAsync = false;
10766     Entry.IsSwiftError = false;
10767     Entry.IsCFGuardTarget = false;
10768     Entry.Alignment = Alignment;
10769     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10770     CLI.NumFixedArgs += 1;
10771     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10772     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10773 
10774     // sret demotion isn't compatible with tail-calls, since the sret argument
10775     // points into the callers stack frame.
10776     CLI.IsTailCall = false;
10777   } else {
10778     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10779         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10780     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10781       ISD::ArgFlagsTy Flags;
10782       if (NeedsRegBlock) {
10783         Flags.setInConsecutiveRegs();
10784         if (I == RetTys.size() - 1)
10785           Flags.setInConsecutiveRegsLast();
10786       }
10787       EVT VT = RetTys[I];
10788       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10789                                                      CLI.CallConv, VT);
10790       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10791                                                        CLI.CallConv, VT);
10792       for (unsigned i = 0; i != NumRegs; ++i) {
10793         ISD::InputArg MyFlags;
10794         MyFlags.Flags = Flags;
10795         MyFlags.VT = RegisterVT;
10796         MyFlags.ArgVT = VT;
10797         MyFlags.Used = CLI.IsReturnValueUsed;
10798         if (CLI.RetTy->isPointerTy()) {
10799           MyFlags.Flags.setPointer();
10800           MyFlags.Flags.setPointerAddrSpace(
10801               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10802         }
10803         if (CLI.RetSExt)
10804           MyFlags.Flags.setSExt();
10805         if (CLI.RetZExt)
10806           MyFlags.Flags.setZExt();
10807         if (CLI.IsInReg)
10808           MyFlags.Flags.setInReg();
10809         CLI.Ins.push_back(MyFlags);
10810       }
10811     }
10812   }
10813 
10814   // We push in swifterror return as the last element of CLI.Ins.
10815   ArgListTy &Args = CLI.getArgs();
10816   if (supportSwiftError()) {
10817     for (const ArgListEntry &Arg : Args) {
10818       if (Arg.IsSwiftError) {
10819         ISD::InputArg MyFlags;
10820         MyFlags.VT = getPointerTy(DL);
10821         MyFlags.ArgVT = EVT(getPointerTy(DL));
10822         MyFlags.Flags.setSwiftError();
10823         CLI.Ins.push_back(MyFlags);
10824       }
10825     }
10826   }
10827 
10828   // Handle all of the outgoing arguments.
10829   CLI.Outs.clear();
10830   CLI.OutVals.clear();
10831   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10832     SmallVector<EVT, 4> ValueVTs;
10833     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10834     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10835     Type *FinalType = Args[i].Ty;
10836     if (Args[i].IsByVal)
10837       FinalType = Args[i].IndirectType;
10838     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10839         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10840     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10841          ++Value) {
10842       EVT VT = ValueVTs[Value];
10843       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10844       SDValue Op = SDValue(Args[i].Node.getNode(),
10845                            Args[i].Node.getResNo() + Value);
10846       ISD::ArgFlagsTy Flags;
10847 
10848       // Certain targets (such as MIPS), may have a different ABI alignment
10849       // for a type depending on the context. Give the target a chance to
10850       // specify the alignment it wants.
10851       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10852       Flags.setOrigAlign(OriginalAlignment);
10853 
10854       if (Args[i].Ty->isPointerTy()) {
10855         Flags.setPointer();
10856         Flags.setPointerAddrSpace(
10857             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10858       }
10859       if (Args[i].IsZExt)
10860         Flags.setZExt();
10861       if (Args[i].IsSExt)
10862         Flags.setSExt();
10863       if (Args[i].IsInReg) {
10864         // If we are using vectorcall calling convention, a structure that is
10865         // passed InReg - is surely an HVA
10866         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10867             isa<StructType>(FinalType)) {
10868           // The first value of a structure is marked
10869           if (0 == Value)
10870             Flags.setHvaStart();
10871           Flags.setHva();
10872         }
10873         // Set InReg Flag
10874         Flags.setInReg();
10875       }
10876       if (Args[i].IsSRet)
10877         Flags.setSRet();
10878       if (Args[i].IsSwiftSelf)
10879         Flags.setSwiftSelf();
10880       if (Args[i].IsSwiftAsync)
10881         Flags.setSwiftAsync();
10882       if (Args[i].IsSwiftError)
10883         Flags.setSwiftError();
10884       if (Args[i].IsCFGuardTarget)
10885         Flags.setCFGuardTarget();
10886       if (Args[i].IsByVal)
10887         Flags.setByVal();
10888       if (Args[i].IsByRef)
10889         Flags.setByRef();
10890       if (Args[i].IsPreallocated) {
10891         Flags.setPreallocated();
10892         // Set the byval flag for CCAssignFn callbacks that don't know about
10893         // preallocated.  This way we can know how many bytes we should've
10894         // allocated and how many bytes a callee cleanup function will pop.  If
10895         // we port preallocated to more targets, we'll have to add custom
10896         // preallocated handling in the various CC lowering callbacks.
10897         Flags.setByVal();
10898       }
10899       if (Args[i].IsInAlloca) {
10900         Flags.setInAlloca();
10901         // Set the byval flag for CCAssignFn callbacks that don't know about
10902         // inalloca.  This way we can know how many bytes we should've allocated
10903         // and how many bytes a callee cleanup function will pop.  If we port
10904         // inalloca to more targets, we'll have to add custom inalloca handling
10905         // in the various CC lowering callbacks.
10906         Flags.setByVal();
10907       }
10908       Align MemAlign;
10909       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
10910         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
10911         Flags.setByValSize(FrameSize);
10912 
10913         // info is not there but there are cases it cannot get right.
10914         if (auto MA = Args[i].Alignment)
10915           MemAlign = *MA;
10916         else
10917           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
10918       } else if (auto MA = Args[i].Alignment) {
10919         MemAlign = *MA;
10920       } else {
10921         MemAlign = OriginalAlignment;
10922       }
10923       Flags.setMemAlign(MemAlign);
10924       if (Args[i].IsNest)
10925         Flags.setNest();
10926       if (NeedsRegBlock)
10927         Flags.setInConsecutiveRegs();
10928 
10929       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10930                                                  CLI.CallConv, VT);
10931       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10932                                                         CLI.CallConv, VT);
10933       SmallVector<SDValue, 4> Parts(NumParts);
10934       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
10935 
10936       if (Args[i].IsSExt)
10937         ExtendKind = ISD::SIGN_EXTEND;
10938       else if (Args[i].IsZExt)
10939         ExtendKind = ISD::ZERO_EXTEND;
10940 
10941       // Conservatively only handle 'returned' on non-vectors that can be lowered,
10942       // for now.
10943       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
10944           CanLowerReturn) {
10945         assert((CLI.RetTy == Args[i].Ty ||
10946                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
10947                  CLI.RetTy->getPointerAddressSpace() ==
10948                      Args[i].Ty->getPointerAddressSpace())) &&
10949                RetTys.size() == NumValues && "unexpected use of 'returned'");
10950         // Before passing 'returned' to the target lowering code, ensure that
10951         // either the register MVT and the actual EVT are the same size or that
10952         // the return value and argument are extended in the same way; in these
10953         // cases it's safe to pass the argument register value unchanged as the
10954         // return register value (although it's at the target's option whether
10955         // to do so)
10956         // TODO: allow code generation to take advantage of partially preserved
10957         // registers rather than clobbering the entire register when the
10958         // parameter extension method is not compatible with the return
10959         // extension method
10960         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
10961             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
10962              CLI.RetZExt == Args[i].IsZExt))
10963           Flags.setReturned();
10964       }
10965 
10966       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
10967                      CLI.CallConv, ExtendKind);
10968 
10969       for (unsigned j = 0; j != NumParts; ++j) {
10970         // if it isn't first piece, alignment must be 1
10971         // For scalable vectors the scalable part is currently handled
10972         // by individual targets, so we just use the known minimum size here.
10973         ISD::OutputArg MyFlags(
10974             Flags, Parts[j].getValueType().getSimpleVT(), VT,
10975             i < CLI.NumFixedArgs, i,
10976             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
10977         if (NumParts > 1 && j == 0)
10978           MyFlags.Flags.setSplit();
10979         else if (j != 0) {
10980           MyFlags.Flags.setOrigAlign(Align(1));
10981           if (j == NumParts - 1)
10982             MyFlags.Flags.setSplitEnd();
10983         }
10984 
10985         CLI.Outs.push_back(MyFlags);
10986         CLI.OutVals.push_back(Parts[j]);
10987       }
10988 
10989       if (NeedsRegBlock && Value == NumValues - 1)
10990         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
10991     }
10992   }
10993 
10994   SmallVector<SDValue, 4> InVals;
10995   CLI.Chain = LowerCall(CLI, InVals);
10996 
10997   // Update CLI.InVals to use outside of this function.
10998   CLI.InVals = InVals;
10999 
11000   // Verify that the target's LowerCall behaved as expected.
11001   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11002          "LowerCall didn't return a valid chain!");
11003   assert((!CLI.IsTailCall || InVals.empty()) &&
11004          "LowerCall emitted a return value for a tail call!");
11005   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11006          "LowerCall didn't emit the correct number of values!");
11007 
11008   // For a tail call, the return value is merely live-out and there aren't
11009   // any nodes in the DAG representing it. Return a special value to
11010   // indicate that a tail call has been emitted and no more Instructions
11011   // should be processed in the current block.
11012   if (CLI.IsTailCall) {
11013     CLI.DAG.setRoot(CLI.Chain);
11014     return std::make_pair(SDValue(), SDValue());
11015   }
11016 
11017 #ifndef NDEBUG
11018   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11019     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11020     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11021            "LowerCall emitted a value with the wrong type!");
11022   }
11023 #endif
11024 
11025   SmallVector<SDValue, 4> ReturnValues;
11026   if (!CanLowerReturn) {
11027     // The instruction result is the result of loading from the
11028     // hidden sret parameter.
11029     SmallVector<EVT, 1> PVTs;
11030     Type *PtrRetTy =
11031         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11032 
11033     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11034     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11035     EVT PtrVT = PVTs[0];
11036 
11037     unsigned NumValues = RetTys.size();
11038     ReturnValues.resize(NumValues);
11039     SmallVector<SDValue, 4> Chains(NumValues);
11040 
11041     // An aggregate return value cannot wrap around the address space, so
11042     // offsets to its parts don't wrap either.
11043     SDNodeFlags Flags;
11044     Flags.setNoUnsignedWrap(true);
11045 
11046     MachineFunction &MF = CLI.DAG.getMachineFunction();
11047     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11048     for (unsigned i = 0; i < NumValues; ++i) {
11049       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11050                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
11051                                                         PtrVT), Flags);
11052       SDValue L = CLI.DAG.getLoad(
11053           RetTys[i], CLI.DL, CLI.Chain, Add,
11054           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11055                                             DemoteStackIdx, Offsets[i]),
11056           HiddenSRetAlign);
11057       ReturnValues[i] = L;
11058       Chains[i] = L.getValue(1);
11059     }
11060 
11061     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11062   } else {
11063     // Collect the legal value parts into potentially illegal values
11064     // that correspond to the original function's return values.
11065     std::optional<ISD::NodeType> AssertOp;
11066     if (CLI.RetSExt)
11067       AssertOp = ISD::AssertSext;
11068     else if (CLI.RetZExt)
11069       AssertOp = ISD::AssertZext;
11070     unsigned CurReg = 0;
11071     for (EVT VT : RetTys) {
11072       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11073                                                      CLI.CallConv, VT);
11074       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11075                                                        CLI.CallConv, VT);
11076 
11077       ReturnValues.push_back(getCopyFromParts(
11078           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11079           CLI.Chain, CLI.CallConv, AssertOp));
11080       CurReg += NumRegs;
11081     }
11082 
11083     // For a function returning void, there is no return value. We can't create
11084     // such a node, so we just return a null return value in that case. In
11085     // that case, nothing will actually look at the value.
11086     if (ReturnValues.empty())
11087       return std::make_pair(SDValue(), CLI.Chain);
11088   }
11089 
11090   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11091                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11092   return std::make_pair(Res, CLI.Chain);
11093 }
11094 
11095 /// Places new result values for the node in Results (their number
11096 /// and types must exactly match those of the original return values of
11097 /// the node), or leaves Results empty, which indicates that the node is not
11098 /// to be custom lowered after all.
11099 void TargetLowering::LowerOperationWrapper(SDNode *N,
11100                                            SmallVectorImpl<SDValue> &Results,
11101                                            SelectionDAG &DAG) const {
11102   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11103 
11104   if (!Res.getNode())
11105     return;
11106 
11107   // If the original node has one result, take the return value from
11108   // LowerOperation as is. It might not be result number 0.
11109   if (N->getNumValues() == 1) {
11110     Results.push_back(Res);
11111     return;
11112   }
11113 
11114   // If the original node has multiple results, then the return node should
11115   // have the same number of results.
11116   assert((N->getNumValues() == Res->getNumValues()) &&
11117       "Lowering returned the wrong number of results!");
11118 
11119   // Places new result values base on N result number.
11120   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11121     Results.push_back(Res.getValue(I));
11122 }
11123 
11124 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11125   llvm_unreachable("LowerOperation not implemented for this target!");
11126 }
11127 
11128 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11129                                                      unsigned Reg,
11130                                                      ISD::NodeType ExtendType) {
11131   SDValue Op = getNonRegisterValue(V);
11132   assert((Op.getOpcode() != ISD::CopyFromReg ||
11133           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11134          "Copy from a reg to the same reg!");
11135   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11136 
11137   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11138   // If this is an InlineAsm we have to match the registers required, not the
11139   // notional registers required by the type.
11140 
11141   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11142                    std::nullopt); // This is not an ABI copy.
11143   SDValue Chain = DAG.getEntryNode();
11144 
11145   if (ExtendType == ISD::ANY_EXTEND) {
11146     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11147     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11148       ExtendType = PreferredExtendIt->second;
11149   }
11150   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11151   PendingExports.push_back(Chain);
11152 }
11153 
11154 #include "llvm/CodeGen/SelectionDAGISel.h"
11155 
11156 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11157 /// entry block, return true.  This includes arguments used by switches, since
11158 /// the switch may expand into multiple basic blocks.
11159 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11160   // With FastISel active, we may be splitting blocks, so force creation
11161   // of virtual registers for all non-dead arguments.
11162   if (FastISel)
11163     return A->use_empty();
11164 
11165   const BasicBlock &Entry = A->getParent()->front();
11166   for (const User *U : A->users())
11167     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11168       return false;  // Use not in entry block.
11169 
11170   return true;
11171 }
11172 
11173 using ArgCopyElisionMapTy =
11174     DenseMap<const Argument *,
11175              std::pair<const AllocaInst *, const StoreInst *>>;
11176 
11177 /// Scan the entry block of the function in FuncInfo for arguments that look
11178 /// like copies into a local alloca. Record any copied arguments in
11179 /// ArgCopyElisionCandidates.
11180 static void
11181 findArgumentCopyElisionCandidates(const DataLayout &DL,
11182                                   FunctionLoweringInfo *FuncInfo,
11183                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11184   // Record the state of every static alloca used in the entry block. Argument
11185   // allocas are all used in the entry block, so we need approximately as many
11186   // entries as we have arguments.
11187   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11188   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11189   unsigned NumArgs = FuncInfo->Fn->arg_size();
11190   StaticAllocas.reserve(NumArgs * 2);
11191 
11192   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11193     if (!V)
11194       return nullptr;
11195     V = V->stripPointerCasts();
11196     const auto *AI = dyn_cast<AllocaInst>(V);
11197     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11198       return nullptr;
11199     auto Iter = StaticAllocas.insert({AI, Unknown});
11200     return &Iter.first->second;
11201   };
11202 
11203   // Look for stores of arguments to static allocas. Look through bitcasts and
11204   // GEPs to handle type coercions, as long as the alloca is fully initialized
11205   // by the store. Any non-store use of an alloca escapes it and any subsequent
11206   // unanalyzed store might write it.
11207   // FIXME: Handle structs initialized with multiple stores.
11208   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11209     // Look for stores, and handle non-store uses conservatively.
11210     const auto *SI = dyn_cast<StoreInst>(&I);
11211     if (!SI) {
11212       // We will look through cast uses, so ignore them completely.
11213       if (I.isCast())
11214         continue;
11215       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11216       // to allocas.
11217       if (I.isDebugOrPseudoInst())
11218         continue;
11219       // This is an unknown instruction. Assume it escapes or writes to all
11220       // static alloca operands.
11221       for (const Use &U : I.operands()) {
11222         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11223           *Info = StaticAllocaInfo::Clobbered;
11224       }
11225       continue;
11226     }
11227 
11228     // If the stored value is a static alloca, mark it as escaped.
11229     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11230       *Info = StaticAllocaInfo::Clobbered;
11231 
11232     // Check if the destination is a static alloca.
11233     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11234     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11235     if (!Info)
11236       continue;
11237     const AllocaInst *AI = cast<AllocaInst>(Dst);
11238 
11239     // Skip allocas that have been initialized or clobbered.
11240     if (*Info != StaticAllocaInfo::Unknown)
11241       continue;
11242 
11243     // Check if the stored value is an argument, and that this store fully
11244     // initializes the alloca.
11245     // If the argument type has padding bits we can't directly forward a pointer
11246     // as the upper bits may contain garbage.
11247     // Don't elide copies from the same argument twice.
11248     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11249     const auto *Arg = dyn_cast<Argument>(Val);
11250     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11251         Arg->getType()->isEmptyTy() ||
11252         DL.getTypeStoreSize(Arg->getType()) !=
11253             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11254         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11255         ArgCopyElisionCandidates.count(Arg)) {
11256       *Info = StaticAllocaInfo::Clobbered;
11257       continue;
11258     }
11259 
11260     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11261                       << '\n');
11262 
11263     // Mark this alloca and store for argument copy elision.
11264     *Info = StaticAllocaInfo::Elidable;
11265     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11266 
11267     // Stop scanning if we've seen all arguments. This will happen early in -O0
11268     // builds, which is useful, because -O0 builds have large entry blocks and
11269     // many allocas.
11270     if (ArgCopyElisionCandidates.size() == NumArgs)
11271       break;
11272   }
11273 }
11274 
11275 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11276 /// ArgVal is a load from a suitable fixed stack object.
11277 static void tryToElideArgumentCopy(
11278     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11279     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11280     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11281     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11282     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11283   // Check if this is a load from a fixed stack object.
11284   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11285   if (!LNode)
11286     return;
11287   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11288   if (!FINode)
11289     return;
11290 
11291   // Check that the fixed stack object is the right size and alignment.
11292   // Look at the alignment that the user wrote on the alloca instead of looking
11293   // at the stack object.
11294   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11295   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11296   const AllocaInst *AI = ArgCopyIter->second.first;
11297   int FixedIndex = FINode->getIndex();
11298   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11299   int OldIndex = AllocaIndex;
11300   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11301   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11302     LLVM_DEBUG(
11303         dbgs() << "  argument copy elision failed due to bad fixed stack "
11304                   "object size\n");
11305     return;
11306   }
11307   Align RequiredAlignment = AI->getAlign();
11308   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11309     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11310                          "greater than stack argument alignment ("
11311                       << DebugStr(RequiredAlignment) << " vs "
11312                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11313     return;
11314   }
11315 
11316   // Perform the elision. Delete the old stack object and replace its only use
11317   // in the variable info map. Mark the stack object as mutable and aliased.
11318   LLVM_DEBUG({
11319     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11320            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11321            << '\n';
11322   });
11323   MFI.RemoveStackObject(OldIndex);
11324   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11325   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11326   AllocaIndex = FixedIndex;
11327   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11328   for (SDValue ArgVal : ArgVals)
11329     Chains.push_back(ArgVal.getValue(1));
11330 
11331   // Avoid emitting code for the store implementing the copy.
11332   const StoreInst *SI = ArgCopyIter->second.second;
11333   ElidedArgCopyInstrs.insert(SI);
11334 
11335   // Check for uses of the argument again so that we can avoid exporting ArgVal
11336   // if it is't used by anything other than the store.
11337   for (const Value *U : Arg.users()) {
11338     if (U != SI) {
11339       ArgHasUses = true;
11340       break;
11341     }
11342   }
11343 }
11344 
11345 void SelectionDAGISel::LowerArguments(const Function &F) {
11346   SelectionDAG &DAG = SDB->DAG;
11347   SDLoc dl = SDB->getCurSDLoc();
11348   const DataLayout &DL = DAG.getDataLayout();
11349   SmallVector<ISD::InputArg, 16> Ins;
11350 
11351   // In Naked functions we aren't going to save any registers.
11352   if (F.hasFnAttribute(Attribute::Naked))
11353     return;
11354 
11355   if (!FuncInfo->CanLowerReturn) {
11356     // Put in an sret pointer parameter before all the other parameters.
11357     SmallVector<EVT, 1> ValueVTs;
11358     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11359                     PointerType::get(F.getContext(),
11360                                      DAG.getDataLayout().getAllocaAddrSpace()),
11361                     ValueVTs);
11362 
11363     // NOTE: Assuming that a pointer will never break down to more than one VT
11364     // or one register.
11365     ISD::ArgFlagsTy Flags;
11366     Flags.setSRet();
11367     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11368     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11369                          ISD::InputArg::NoArgIndex, 0);
11370     Ins.push_back(RetArg);
11371   }
11372 
11373   // Look for stores of arguments to static allocas. Mark such arguments with a
11374   // flag to ask the target to give us the memory location of that argument if
11375   // available.
11376   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11377   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11378                                     ArgCopyElisionCandidates);
11379 
11380   // Set up the incoming argument description vector.
11381   for (const Argument &Arg : F.args()) {
11382     unsigned ArgNo = Arg.getArgNo();
11383     SmallVector<EVT, 4> ValueVTs;
11384     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11385     bool isArgValueUsed = !Arg.use_empty();
11386     unsigned PartBase = 0;
11387     Type *FinalType = Arg.getType();
11388     if (Arg.hasAttribute(Attribute::ByVal))
11389       FinalType = Arg.getParamByValType();
11390     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11391         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11392     for (unsigned Value = 0, NumValues = ValueVTs.size();
11393          Value != NumValues; ++Value) {
11394       EVT VT = ValueVTs[Value];
11395       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11396       ISD::ArgFlagsTy Flags;
11397 
11398 
11399       if (Arg.getType()->isPointerTy()) {
11400         Flags.setPointer();
11401         Flags.setPointerAddrSpace(
11402             cast<PointerType>(Arg.getType())->getAddressSpace());
11403       }
11404       if (Arg.hasAttribute(Attribute::ZExt))
11405         Flags.setZExt();
11406       if (Arg.hasAttribute(Attribute::SExt))
11407         Flags.setSExt();
11408       if (Arg.hasAttribute(Attribute::InReg)) {
11409         // If we are using vectorcall calling convention, a structure that is
11410         // passed InReg - is surely an HVA
11411         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11412             isa<StructType>(Arg.getType())) {
11413           // The first value of a structure is marked
11414           if (0 == Value)
11415             Flags.setHvaStart();
11416           Flags.setHva();
11417         }
11418         // Set InReg Flag
11419         Flags.setInReg();
11420       }
11421       if (Arg.hasAttribute(Attribute::StructRet))
11422         Flags.setSRet();
11423       if (Arg.hasAttribute(Attribute::SwiftSelf))
11424         Flags.setSwiftSelf();
11425       if (Arg.hasAttribute(Attribute::SwiftAsync))
11426         Flags.setSwiftAsync();
11427       if (Arg.hasAttribute(Attribute::SwiftError))
11428         Flags.setSwiftError();
11429       if (Arg.hasAttribute(Attribute::ByVal))
11430         Flags.setByVal();
11431       if (Arg.hasAttribute(Attribute::ByRef))
11432         Flags.setByRef();
11433       if (Arg.hasAttribute(Attribute::InAlloca)) {
11434         Flags.setInAlloca();
11435         // Set the byval flag for CCAssignFn callbacks that don't know about
11436         // inalloca.  This way we can know how many bytes we should've allocated
11437         // and how many bytes a callee cleanup function will pop.  If we port
11438         // inalloca to more targets, we'll have to add custom inalloca handling
11439         // in the various CC lowering callbacks.
11440         Flags.setByVal();
11441       }
11442       if (Arg.hasAttribute(Attribute::Preallocated)) {
11443         Flags.setPreallocated();
11444         // Set the byval flag for CCAssignFn callbacks that don't know about
11445         // preallocated.  This way we can know how many bytes we should've
11446         // allocated and how many bytes a callee cleanup function will pop.  If
11447         // we port preallocated to more targets, we'll have to add custom
11448         // preallocated handling in the various CC lowering callbacks.
11449         Flags.setByVal();
11450       }
11451 
11452       // Certain targets (such as MIPS), may have a different ABI alignment
11453       // for a type depending on the context. Give the target a chance to
11454       // specify the alignment it wants.
11455       const Align OriginalAlignment(
11456           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11457       Flags.setOrigAlign(OriginalAlignment);
11458 
11459       Align MemAlign;
11460       Type *ArgMemTy = nullptr;
11461       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11462           Flags.isByRef()) {
11463         if (!ArgMemTy)
11464           ArgMemTy = Arg.getPointeeInMemoryValueType();
11465 
11466         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11467 
11468         // For in-memory arguments, size and alignment should be passed from FE.
11469         // BE will guess if this info is not there but there are cases it cannot
11470         // get right.
11471         if (auto ParamAlign = Arg.getParamStackAlign())
11472           MemAlign = *ParamAlign;
11473         else if ((ParamAlign = Arg.getParamAlign()))
11474           MemAlign = *ParamAlign;
11475         else
11476           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11477         if (Flags.isByRef())
11478           Flags.setByRefSize(MemSize);
11479         else
11480           Flags.setByValSize(MemSize);
11481       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11482         MemAlign = *ParamAlign;
11483       } else {
11484         MemAlign = OriginalAlignment;
11485       }
11486       Flags.setMemAlign(MemAlign);
11487 
11488       if (Arg.hasAttribute(Attribute::Nest))
11489         Flags.setNest();
11490       if (NeedsRegBlock)
11491         Flags.setInConsecutiveRegs();
11492       if (ArgCopyElisionCandidates.count(&Arg))
11493         Flags.setCopyElisionCandidate();
11494       if (Arg.hasAttribute(Attribute::Returned))
11495         Flags.setReturned();
11496 
11497       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11498           *CurDAG->getContext(), F.getCallingConv(), VT);
11499       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11500           *CurDAG->getContext(), F.getCallingConv(), VT);
11501       for (unsigned i = 0; i != NumRegs; ++i) {
11502         // For scalable vectors, use the minimum size; individual targets
11503         // are responsible for handling scalable vector arguments and
11504         // return values.
11505         ISD::InputArg MyFlags(
11506             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11507             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11508         if (NumRegs > 1 && i == 0)
11509           MyFlags.Flags.setSplit();
11510         // if it isn't first piece, alignment must be 1
11511         else if (i > 0) {
11512           MyFlags.Flags.setOrigAlign(Align(1));
11513           if (i == NumRegs - 1)
11514             MyFlags.Flags.setSplitEnd();
11515         }
11516         Ins.push_back(MyFlags);
11517       }
11518       if (NeedsRegBlock && Value == NumValues - 1)
11519         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11520       PartBase += VT.getStoreSize().getKnownMinValue();
11521     }
11522   }
11523 
11524   // Call the target to set up the argument values.
11525   SmallVector<SDValue, 8> InVals;
11526   SDValue NewRoot = TLI->LowerFormalArguments(
11527       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11528 
11529   // Verify that the target's LowerFormalArguments behaved as expected.
11530   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11531          "LowerFormalArguments didn't return a valid chain!");
11532   assert(InVals.size() == Ins.size() &&
11533          "LowerFormalArguments didn't emit the correct number of values!");
11534   LLVM_DEBUG({
11535     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11536       assert(InVals[i].getNode() &&
11537              "LowerFormalArguments emitted a null value!");
11538       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11539              "LowerFormalArguments emitted a value with the wrong type!");
11540     }
11541   });
11542 
11543   // Update the DAG with the new chain value resulting from argument lowering.
11544   DAG.setRoot(NewRoot);
11545 
11546   // Set up the argument values.
11547   unsigned i = 0;
11548   if (!FuncInfo->CanLowerReturn) {
11549     // Create a virtual register for the sret pointer, and put in a copy
11550     // from the sret argument into it.
11551     SmallVector<EVT, 1> ValueVTs;
11552     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11553                     PointerType::get(F.getContext(),
11554                                      DAG.getDataLayout().getAllocaAddrSpace()),
11555                     ValueVTs);
11556     MVT VT = ValueVTs[0].getSimpleVT();
11557     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11558     std::optional<ISD::NodeType> AssertOp;
11559     SDValue ArgValue =
11560         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11561                          F.getCallingConv(), AssertOp);
11562 
11563     MachineFunction& MF = SDB->DAG.getMachineFunction();
11564     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11565     Register SRetReg =
11566         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11567     FuncInfo->DemoteRegister = SRetReg;
11568     NewRoot =
11569         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11570     DAG.setRoot(NewRoot);
11571 
11572     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11573     ++i;
11574   }
11575 
11576   SmallVector<SDValue, 4> Chains;
11577   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11578   for (const Argument &Arg : F.args()) {
11579     SmallVector<SDValue, 4> ArgValues;
11580     SmallVector<EVT, 4> ValueVTs;
11581     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11582     unsigned NumValues = ValueVTs.size();
11583     if (NumValues == 0)
11584       continue;
11585 
11586     bool ArgHasUses = !Arg.use_empty();
11587 
11588     // Elide the copying store if the target loaded this argument from a
11589     // suitable fixed stack object.
11590     if (Ins[i].Flags.isCopyElisionCandidate()) {
11591       unsigned NumParts = 0;
11592       for (EVT VT : ValueVTs)
11593         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11594                                                        F.getCallingConv(), VT);
11595 
11596       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11597                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11598                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11599     }
11600 
11601     // If this argument is unused then remember its value. It is used to generate
11602     // debugging information.
11603     bool isSwiftErrorArg =
11604         TLI->supportSwiftError() &&
11605         Arg.hasAttribute(Attribute::SwiftError);
11606     if (!ArgHasUses && !isSwiftErrorArg) {
11607       SDB->setUnusedArgValue(&Arg, InVals[i]);
11608 
11609       // Also remember any frame index for use in FastISel.
11610       if (FrameIndexSDNode *FI =
11611           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11612         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11613     }
11614 
11615     for (unsigned Val = 0; Val != NumValues; ++Val) {
11616       EVT VT = ValueVTs[Val];
11617       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11618                                                       F.getCallingConv(), VT);
11619       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11620           *CurDAG->getContext(), F.getCallingConv(), VT);
11621 
11622       // Even an apparent 'unused' swifterror argument needs to be returned. So
11623       // we do generate a copy for it that can be used on return from the
11624       // function.
11625       if (ArgHasUses || isSwiftErrorArg) {
11626         std::optional<ISD::NodeType> AssertOp;
11627         if (Arg.hasAttribute(Attribute::SExt))
11628           AssertOp = ISD::AssertSext;
11629         else if (Arg.hasAttribute(Attribute::ZExt))
11630           AssertOp = ISD::AssertZext;
11631 
11632         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11633                                              PartVT, VT, nullptr, NewRoot,
11634                                              F.getCallingConv(), AssertOp));
11635       }
11636 
11637       i += NumParts;
11638     }
11639 
11640     // We don't need to do anything else for unused arguments.
11641     if (ArgValues.empty())
11642       continue;
11643 
11644     // Note down frame index.
11645     if (FrameIndexSDNode *FI =
11646         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11647       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11648 
11649     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11650                                      SDB->getCurSDLoc());
11651 
11652     SDB->setValue(&Arg, Res);
11653     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11654       // We want to associate the argument with the frame index, among
11655       // involved operands, that correspond to the lowest address. The
11656       // getCopyFromParts function, called earlier, is swapping the order of
11657       // the operands to BUILD_PAIR depending on endianness. The result of
11658       // that swapping is that the least significant bits of the argument will
11659       // be in the first operand of the BUILD_PAIR node, and the most
11660       // significant bits will be in the second operand.
11661       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11662       if (LoadSDNode *LNode =
11663           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11664         if (FrameIndexSDNode *FI =
11665             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11666           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11667     }
11668 
11669     // Analyses past this point are naive and don't expect an assertion.
11670     if (Res.getOpcode() == ISD::AssertZext)
11671       Res = Res.getOperand(0);
11672 
11673     // Update the SwiftErrorVRegDefMap.
11674     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11675       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11676       if (Register::isVirtualRegister(Reg))
11677         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11678                                    Reg);
11679     }
11680 
11681     // If this argument is live outside of the entry block, insert a copy from
11682     // wherever we got it to the vreg that other BB's will reference it as.
11683     if (Res.getOpcode() == ISD::CopyFromReg) {
11684       // If we can, though, try to skip creating an unnecessary vreg.
11685       // FIXME: This isn't very clean... it would be nice to make this more
11686       // general.
11687       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11688       if (Register::isVirtualRegister(Reg)) {
11689         FuncInfo->ValueMap[&Arg] = Reg;
11690         continue;
11691       }
11692     }
11693     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11694       FuncInfo->InitializeRegForValue(&Arg);
11695       SDB->CopyToExportRegsIfNeeded(&Arg);
11696     }
11697   }
11698 
11699   if (!Chains.empty()) {
11700     Chains.push_back(NewRoot);
11701     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11702   }
11703 
11704   DAG.setRoot(NewRoot);
11705 
11706   assert(i == InVals.size() && "Argument register count mismatch!");
11707 
11708   // If any argument copy elisions occurred and we have debug info, update the
11709   // stale frame indices used in the dbg.declare variable info table.
11710   if (!ArgCopyElisionFrameIndexMap.empty()) {
11711     for (MachineFunction::VariableDbgInfo &VI :
11712          MF->getInStackSlotVariableDbgInfo()) {
11713       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11714       if (I != ArgCopyElisionFrameIndexMap.end())
11715         VI.updateStackSlot(I->second);
11716     }
11717   }
11718 
11719   // Finally, if the target has anything special to do, allow it to do so.
11720   emitFunctionEntryCode();
11721 }
11722 
11723 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11724 /// ensure constants are generated when needed.  Remember the virtual registers
11725 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11726 /// directly add them, because expansion might result in multiple MBB's for one
11727 /// BB.  As such, the start of the BB might correspond to a different MBB than
11728 /// the end.
11729 void
11730 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11732 
11733   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11734 
11735   // Check PHI nodes in successors that expect a value to be available from this
11736   // block.
11737   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11738     if (!isa<PHINode>(SuccBB->begin())) continue;
11739     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11740 
11741     // If this terminator has multiple identical successors (common for
11742     // switches), only handle each succ once.
11743     if (!SuccsHandled.insert(SuccMBB).second)
11744       continue;
11745 
11746     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11747 
11748     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11749     // nodes and Machine PHI nodes, but the incoming operands have not been
11750     // emitted yet.
11751     for (const PHINode &PN : SuccBB->phis()) {
11752       // Ignore dead phi's.
11753       if (PN.use_empty())
11754         continue;
11755 
11756       // Skip empty types
11757       if (PN.getType()->isEmptyTy())
11758         continue;
11759 
11760       unsigned Reg;
11761       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11762 
11763       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11764         unsigned &RegOut = ConstantsOut[C];
11765         if (RegOut == 0) {
11766           RegOut = FuncInfo.CreateRegs(C);
11767           // We need to zero/sign extend ConstantInt phi operands to match
11768           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11769           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11770           if (auto *CI = dyn_cast<ConstantInt>(C))
11771             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11772                                                     : ISD::ZERO_EXTEND;
11773           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11774         }
11775         Reg = RegOut;
11776       } else {
11777         DenseMap<const Value *, Register>::iterator I =
11778           FuncInfo.ValueMap.find(PHIOp);
11779         if (I != FuncInfo.ValueMap.end())
11780           Reg = I->second;
11781         else {
11782           assert(isa<AllocaInst>(PHIOp) &&
11783                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11784                  "Didn't codegen value into a register!??");
11785           Reg = FuncInfo.CreateRegs(PHIOp);
11786           CopyValueToVirtualRegister(PHIOp, Reg);
11787         }
11788       }
11789 
11790       // Remember that this register needs to added to the machine PHI node as
11791       // the input for this MBB.
11792       SmallVector<EVT, 4> ValueVTs;
11793       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11794       for (EVT VT : ValueVTs) {
11795         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11796         for (unsigned i = 0; i != NumRegisters; ++i)
11797           FuncInfo.PHINodesToUpdate.push_back(
11798               std::make_pair(&*MBBI++, Reg + i));
11799         Reg += NumRegisters;
11800       }
11801     }
11802   }
11803 
11804   ConstantsOut.clear();
11805 }
11806 
11807 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11808   MachineFunction::iterator I(MBB);
11809   if (++I == FuncInfo.MF->end())
11810     return nullptr;
11811   return &*I;
11812 }
11813 
11814 /// During lowering new call nodes can be created (such as memset, etc.).
11815 /// Those will become new roots of the current DAG, but complications arise
11816 /// when they are tail calls. In such cases, the call lowering will update
11817 /// the root, but the builder still needs to know that a tail call has been
11818 /// lowered in order to avoid generating an additional return.
11819 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11820   // If the node is null, we do have a tail call.
11821   if (MaybeTC.getNode() != nullptr)
11822     DAG.setRoot(MaybeTC);
11823   else
11824     HasTailCall = true;
11825 }
11826 
11827 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11828                                         MachineBasicBlock *SwitchMBB,
11829                                         MachineBasicBlock *DefaultMBB) {
11830   MachineFunction *CurMF = FuncInfo.MF;
11831   MachineBasicBlock *NextMBB = nullptr;
11832   MachineFunction::iterator BBI(W.MBB);
11833   if (++BBI != FuncInfo.MF->end())
11834     NextMBB = &*BBI;
11835 
11836   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11837 
11838   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11839 
11840   if (Size == 2 && W.MBB == SwitchMBB) {
11841     // If any two of the cases has the same destination, and if one value
11842     // is the same as the other, but has one bit unset that the other has set,
11843     // use bit manipulation to do two compares at once.  For example:
11844     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11845     // TODO: This could be extended to merge any 2 cases in switches with 3
11846     // cases.
11847     // TODO: Handle cases where W.CaseBB != SwitchBB.
11848     CaseCluster &Small = *W.FirstCluster;
11849     CaseCluster &Big = *W.LastCluster;
11850 
11851     if (Small.Low == Small.High && Big.Low == Big.High &&
11852         Small.MBB == Big.MBB) {
11853       const APInt &SmallValue = Small.Low->getValue();
11854       const APInt &BigValue = Big.Low->getValue();
11855 
11856       // Check that there is only one bit different.
11857       APInt CommonBit = BigValue ^ SmallValue;
11858       if (CommonBit.isPowerOf2()) {
11859         SDValue CondLHS = getValue(Cond);
11860         EVT VT = CondLHS.getValueType();
11861         SDLoc DL = getCurSDLoc();
11862 
11863         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11864                                  DAG.getConstant(CommonBit, DL, VT));
11865         SDValue Cond = DAG.getSetCC(
11866             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11867             ISD::SETEQ);
11868 
11869         // Update successor info.
11870         // Both Small and Big will jump to Small.BB, so we sum up the
11871         // probabilities.
11872         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11873         if (BPI)
11874           addSuccessorWithProb(
11875               SwitchMBB, DefaultMBB,
11876               // The default destination is the first successor in IR.
11877               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11878         else
11879           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11880 
11881         // Insert the true branch.
11882         SDValue BrCond =
11883             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11884                         DAG.getBasicBlock(Small.MBB));
11885         // Insert the false branch.
11886         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11887                              DAG.getBasicBlock(DefaultMBB));
11888 
11889         DAG.setRoot(BrCond);
11890         return;
11891       }
11892     }
11893   }
11894 
11895   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11896     // Here, we order cases by probability so the most likely case will be
11897     // checked first. However, two clusters can have the same probability in
11898     // which case their relative ordering is non-deterministic. So we use Low
11899     // as a tie-breaker as clusters are guaranteed to never overlap.
11900     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11901                [](const CaseCluster &a, const CaseCluster &b) {
11902       return a.Prob != b.Prob ?
11903              a.Prob > b.Prob :
11904              a.Low->getValue().slt(b.Low->getValue());
11905     });
11906 
11907     // Rearrange the case blocks so that the last one falls through if possible
11908     // without changing the order of probabilities.
11909     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
11910       --I;
11911       if (I->Prob > W.LastCluster->Prob)
11912         break;
11913       if (I->Kind == CC_Range && I->MBB == NextMBB) {
11914         std::swap(*I, *W.LastCluster);
11915         break;
11916       }
11917     }
11918   }
11919 
11920   // Compute total probability.
11921   BranchProbability DefaultProb = W.DefaultProb;
11922   BranchProbability UnhandledProbs = DefaultProb;
11923   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
11924     UnhandledProbs += I->Prob;
11925 
11926   MachineBasicBlock *CurMBB = W.MBB;
11927   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
11928     bool FallthroughUnreachable = false;
11929     MachineBasicBlock *Fallthrough;
11930     if (I == W.LastCluster) {
11931       // For the last cluster, fall through to the default destination.
11932       Fallthrough = DefaultMBB;
11933       FallthroughUnreachable = isa<UnreachableInst>(
11934           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
11935     } else {
11936       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
11937       CurMF->insert(BBI, Fallthrough);
11938       // Put Cond in a virtual register to make it available from the new blocks.
11939       ExportFromCurrentBlock(Cond);
11940     }
11941     UnhandledProbs -= I->Prob;
11942 
11943     switch (I->Kind) {
11944       case CC_JumpTable: {
11945         // FIXME: Optimize away range check based on pivot comparisons.
11946         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
11947         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
11948 
11949         // The jump block hasn't been inserted yet; insert it here.
11950         MachineBasicBlock *JumpMBB = JT->MBB;
11951         CurMF->insert(BBI, JumpMBB);
11952 
11953         auto JumpProb = I->Prob;
11954         auto FallthroughProb = UnhandledProbs;
11955 
11956         // If the default statement is a target of the jump table, we evenly
11957         // distribute the default probability to successors of CurMBB. Also
11958         // update the probability on the edge from JumpMBB to Fallthrough.
11959         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
11960                                               SE = JumpMBB->succ_end();
11961              SI != SE; ++SI) {
11962           if (*SI == DefaultMBB) {
11963             JumpProb += DefaultProb / 2;
11964             FallthroughProb -= DefaultProb / 2;
11965             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
11966             JumpMBB->normalizeSuccProbs();
11967             break;
11968           }
11969         }
11970 
11971         // If the default clause is unreachable, propagate that knowledge into
11972         // JTH->FallthroughUnreachable which will use it to suppress the range
11973         // check.
11974         //
11975         // However, don't do this if we're doing branch target enforcement,
11976         // because a table branch _without_ a range check can be a tempting JOP
11977         // gadget - out-of-bounds inputs that are impossible in correct
11978         // execution become possible again if an attacker can influence the
11979         // control flow. So if an attacker doesn't already have a BTI bypass
11980         // available, we don't want them to be able to get one out of this
11981         // table branch.
11982         if (FallthroughUnreachable) {
11983           Function &CurFunc = CurMF->getFunction();
11984           bool HasBranchTargetEnforcement = false;
11985           if (CurFunc.hasFnAttribute("branch-target-enforcement")) {
11986             HasBranchTargetEnforcement =
11987                 CurFunc.getFnAttribute("branch-target-enforcement")
11988                     .getValueAsBool();
11989           } else {
11990             HasBranchTargetEnforcement =
11991                 CurMF->getMMI().getModule()->getModuleFlag(
11992                     "branch-target-enforcement");
11993           }
11994           if (!HasBranchTargetEnforcement)
11995             JTH->FallthroughUnreachable = true;
11996         }
11997 
11998         if (!JTH->FallthroughUnreachable)
11999           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12000         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12001         CurMBB->normalizeSuccProbs();
12002 
12003         // The jump table header will be inserted in our current block, do the
12004         // range check, and fall through to our fallthrough block.
12005         JTH->HeaderBB = CurMBB;
12006         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12007 
12008         // If we're in the right place, emit the jump table header right now.
12009         if (CurMBB == SwitchMBB) {
12010           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12011           JTH->Emitted = true;
12012         }
12013         break;
12014       }
12015       case CC_BitTests: {
12016         // FIXME: Optimize away range check based on pivot comparisons.
12017         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12018 
12019         // The bit test blocks haven't been inserted yet; insert them here.
12020         for (BitTestCase &BTC : BTB->Cases)
12021           CurMF->insert(BBI, BTC.ThisBB);
12022 
12023         // Fill in fields of the BitTestBlock.
12024         BTB->Parent = CurMBB;
12025         BTB->Default = Fallthrough;
12026 
12027         BTB->DefaultProb = UnhandledProbs;
12028         // If the cases in bit test don't form a contiguous range, we evenly
12029         // distribute the probability on the edge to Fallthrough to two
12030         // successors of CurMBB.
12031         if (!BTB->ContiguousRange) {
12032           BTB->Prob += DefaultProb / 2;
12033           BTB->DefaultProb -= DefaultProb / 2;
12034         }
12035 
12036         if (FallthroughUnreachable)
12037           BTB->FallthroughUnreachable = true;
12038 
12039         // If we're in the right place, emit the bit test header right now.
12040         if (CurMBB == SwitchMBB) {
12041           visitBitTestHeader(*BTB, SwitchMBB);
12042           BTB->Emitted = true;
12043         }
12044         break;
12045       }
12046       case CC_Range: {
12047         const Value *RHS, *LHS, *MHS;
12048         ISD::CondCode CC;
12049         if (I->Low == I->High) {
12050           // Check Cond == I->Low.
12051           CC = ISD::SETEQ;
12052           LHS = Cond;
12053           RHS=I->Low;
12054           MHS = nullptr;
12055         } else {
12056           // Check I->Low <= Cond <= I->High.
12057           CC = ISD::SETLE;
12058           LHS = I->Low;
12059           MHS = Cond;
12060           RHS = I->High;
12061         }
12062 
12063         // If Fallthrough is unreachable, fold away the comparison.
12064         if (FallthroughUnreachable)
12065           CC = ISD::SETTRUE;
12066 
12067         // The false probability is the sum of all unhandled cases.
12068         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12069                      getCurSDLoc(), I->Prob, UnhandledProbs);
12070 
12071         if (CurMBB == SwitchMBB)
12072           visitSwitchCase(CB, SwitchMBB);
12073         else
12074           SL->SwitchCases.push_back(CB);
12075 
12076         break;
12077       }
12078     }
12079     CurMBB = Fallthrough;
12080   }
12081 }
12082 
12083 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12084                                         const SwitchWorkListItem &W,
12085                                         Value *Cond,
12086                                         MachineBasicBlock *SwitchMBB) {
12087   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12088          "Clusters not sorted?");
12089   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12090 
12091   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12092       SL->computeSplitWorkItemInfo(W);
12093 
12094   // Use the first element on the right as pivot since we will make less-than
12095   // comparisons against it.
12096   CaseClusterIt PivotCluster = FirstRight;
12097   assert(PivotCluster > W.FirstCluster);
12098   assert(PivotCluster <= W.LastCluster);
12099 
12100   CaseClusterIt FirstLeft = W.FirstCluster;
12101   CaseClusterIt LastRight = W.LastCluster;
12102 
12103   const ConstantInt *Pivot = PivotCluster->Low;
12104 
12105   // New blocks will be inserted immediately after the current one.
12106   MachineFunction::iterator BBI(W.MBB);
12107   ++BBI;
12108 
12109   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12110   // we can branch to its destination directly if it's squeezed exactly in
12111   // between the known lower bound and Pivot - 1.
12112   MachineBasicBlock *LeftMBB;
12113   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12114       FirstLeft->Low == W.GE &&
12115       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12116     LeftMBB = FirstLeft->MBB;
12117   } else {
12118     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12119     FuncInfo.MF->insert(BBI, LeftMBB);
12120     WorkList.push_back(
12121         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12122     // Put Cond in a virtual register to make it available from the new blocks.
12123     ExportFromCurrentBlock(Cond);
12124   }
12125 
12126   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12127   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12128   // directly if RHS.High equals the current upper bound.
12129   MachineBasicBlock *RightMBB;
12130   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12131       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12132     RightMBB = FirstRight->MBB;
12133   } else {
12134     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12135     FuncInfo.MF->insert(BBI, RightMBB);
12136     WorkList.push_back(
12137         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12138     // Put Cond in a virtual register to make it available from the new blocks.
12139     ExportFromCurrentBlock(Cond);
12140   }
12141 
12142   // Create the CaseBlock record that will be used to lower the branch.
12143   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12144                getCurSDLoc(), LeftProb, RightProb);
12145 
12146   if (W.MBB == SwitchMBB)
12147     visitSwitchCase(CB, SwitchMBB);
12148   else
12149     SL->SwitchCases.push_back(CB);
12150 }
12151 
12152 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12153 // from the swith statement.
12154 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12155                                             BranchProbability PeeledCaseProb) {
12156   if (PeeledCaseProb == BranchProbability::getOne())
12157     return BranchProbability::getZero();
12158   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12159 
12160   uint32_t Numerator = CaseProb.getNumerator();
12161   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12162   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12163 }
12164 
12165 // Try to peel the top probability case if it exceeds the threshold.
12166 // Return current MachineBasicBlock for the switch statement if the peeling
12167 // does not occur.
12168 // If the peeling is performed, return the newly created MachineBasicBlock
12169 // for the peeled switch statement. Also update Clusters to remove the peeled
12170 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12171 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12172     const SwitchInst &SI, CaseClusterVector &Clusters,
12173     BranchProbability &PeeledCaseProb) {
12174   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12175   // Don't perform if there is only one cluster or optimizing for size.
12176   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12177       TM.getOptLevel() == CodeGenOptLevel::None ||
12178       SwitchMBB->getParent()->getFunction().hasMinSize())
12179     return SwitchMBB;
12180 
12181   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12182   unsigned PeeledCaseIndex = 0;
12183   bool SwitchPeeled = false;
12184   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12185     CaseCluster &CC = Clusters[Index];
12186     if (CC.Prob < TopCaseProb)
12187       continue;
12188     TopCaseProb = CC.Prob;
12189     PeeledCaseIndex = Index;
12190     SwitchPeeled = true;
12191   }
12192   if (!SwitchPeeled)
12193     return SwitchMBB;
12194 
12195   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12196                     << TopCaseProb << "\n");
12197 
12198   // Record the MBB for the peeled switch statement.
12199   MachineFunction::iterator BBI(SwitchMBB);
12200   ++BBI;
12201   MachineBasicBlock *PeeledSwitchMBB =
12202       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12203   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12204 
12205   ExportFromCurrentBlock(SI.getCondition());
12206   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12207   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12208                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12209   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12210 
12211   Clusters.erase(PeeledCaseIt);
12212   for (CaseCluster &CC : Clusters) {
12213     LLVM_DEBUG(
12214         dbgs() << "Scale the probablity for one cluster, before scaling: "
12215                << CC.Prob << "\n");
12216     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12217     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12218   }
12219   PeeledCaseProb = TopCaseProb;
12220   return PeeledSwitchMBB;
12221 }
12222 
12223 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12224   // Extract cases from the switch.
12225   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12226   CaseClusterVector Clusters;
12227   Clusters.reserve(SI.getNumCases());
12228   for (auto I : SI.cases()) {
12229     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
12230     const ConstantInt *CaseVal = I.getCaseValue();
12231     BranchProbability Prob =
12232         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12233             : BranchProbability(1, SI.getNumCases() + 1);
12234     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12235   }
12236 
12237   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
12238 
12239   // Cluster adjacent cases with the same destination. We do this at all
12240   // optimization levels because it's cheap to do and will make codegen faster
12241   // if there are many clusters.
12242   sortAndRangeify(Clusters);
12243 
12244   // The branch probablity of the peeled case.
12245   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12246   MachineBasicBlock *PeeledSwitchMBB =
12247       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12248 
12249   // If there is only the default destination, jump there directly.
12250   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12251   if (Clusters.empty()) {
12252     assert(PeeledSwitchMBB == SwitchMBB);
12253     SwitchMBB->addSuccessor(DefaultMBB);
12254     if (DefaultMBB != NextBlock(SwitchMBB)) {
12255       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12256                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12257     }
12258     return;
12259   }
12260 
12261   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12262                      DAG.getBFI());
12263   SL->findBitTestClusters(Clusters, &SI);
12264 
12265   LLVM_DEBUG({
12266     dbgs() << "Case clusters: ";
12267     for (const CaseCluster &C : Clusters) {
12268       if (C.Kind == CC_JumpTable)
12269         dbgs() << "JT:";
12270       if (C.Kind == CC_BitTests)
12271         dbgs() << "BT:";
12272 
12273       C.Low->getValue().print(dbgs(), true);
12274       if (C.Low != C.High) {
12275         dbgs() << '-';
12276         C.High->getValue().print(dbgs(), true);
12277       }
12278       dbgs() << ' ';
12279     }
12280     dbgs() << '\n';
12281   });
12282 
12283   assert(!Clusters.empty());
12284   SwitchWorkList WorkList;
12285   CaseClusterIt First = Clusters.begin();
12286   CaseClusterIt Last = Clusters.end() - 1;
12287   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12288   // Scale the branchprobability for DefaultMBB if the peel occurs and
12289   // DefaultMBB is not replaced.
12290   if (PeeledCaseProb != BranchProbability::getZero() &&
12291       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
12292     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12293   WorkList.push_back(
12294       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12295 
12296   while (!WorkList.empty()) {
12297     SwitchWorkListItem W = WorkList.pop_back_val();
12298     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12299 
12300     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12301         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12302       // For optimized builds, lower large range as a balanced binary tree.
12303       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12304       continue;
12305     }
12306 
12307     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12308   }
12309 }
12310 
12311 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12312   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12313   auto DL = getCurSDLoc();
12314   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12315   setValue(&I, DAG.getStepVector(DL, ResultVT));
12316 }
12317 
12318 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12319   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12320   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12321 
12322   SDLoc DL = getCurSDLoc();
12323   SDValue V = getValue(I.getOperand(0));
12324   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12325 
12326   if (VT.isScalableVector()) {
12327     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12328     return;
12329   }
12330 
12331   // Use VECTOR_SHUFFLE for the fixed-length vector
12332   // to maintain existing behavior.
12333   SmallVector<int, 8> Mask;
12334   unsigned NumElts = VT.getVectorMinNumElements();
12335   for (unsigned i = 0; i != NumElts; ++i)
12336     Mask.push_back(NumElts - 1 - i);
12337 
12338   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12339 }
12340 
12341 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12342   auto DL = getCurSDLoc();
12343   SDValue InVec = getValue(I.getOperand(0));
12344   EVT OutVT =
12345       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12346 
12347   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12348 
12349   // ISD Node needs the input vectors split into two equal parts
12350   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12351                            DAG.getVectorIdxConstant(0, DL));
12352   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12353                            DAG.getVectorIdxConstant(OutNumElts, DL));
12354 
12355   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12356   // legalisation and combines.
12357   if (OutVT.isFixedLengthVector()) {
12358     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12359                                         createStrideMask(0, 2, OutNumElts));
12360     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12361                                        createStrideMask(1, 2, OutNumElts));
12362     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12363     setValue(&I, Res);
12364     return;
12365   }
12366 
12367   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12368                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12369   setValue(&I, Res);
12370 }
12371 
12372 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12373   auto DL = getCurSDLoc();
12374   EVT InVT = getValue(I.getOperand(0)).getValueType();
12375   SDValue InVec0 = getValue(I.getOperand(0));
12376   SDValue InVec1 = getValue(I.getOperand(1));
12377   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12378   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12379 
12380   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12381   // legalisation and combines.
12382   if (OutVT.isFixedLengthVector()) {
12383     unsigned NumElts = InVT.getVectorMinNumElements();
12384     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12385     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12386                                       createInterleaveMask(NumElts, 2)));
12387     return;
12388   }
12389 
12390   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12391                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12392   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12393                     Res.getValue(1));
12394   setValue(&I, Res);
12395 }
12396 
12397 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12398   SmallVector<EVT, 4> ValueVTs;
12399   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12400                   ValueVTs);
12401   unsigned NumValues = ValueVTs.size();
12402   if (NumValues == 0) return;
12403 
12404   SmallVector<SDValue, 4> Values(NumValues);
12405   SDValue Op = getValue(I.getOperand(0));
12406 
12407   for (unsigned i = 0; i != NumValues; ++i)
12408     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12409                             SDValue(Op.getNode(), Op.getResNo() + i));
12410 
12411   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12412                            DAG.getVTList(ValueVTs), Values));
12413 }
12414 
12415 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12416   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12417   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12418 
12419   SDLoc DL = getCurSDLoc();
12420   SDValue V1 = getValue(I.getOperand(0));
12421   SDValue V2 = getValue(I.getOperand(1));
12422   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12423 
12424   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12425   if (VT.isScalableVector()) {
12426     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12427                              DAG.getVectorIdxConstant(Imm, DL)));
12428     return;
12429   }
12430 
12431   unsigned NumElts = VT.getVectorNumElements();
12432 
12433   uint64_t Idx = (NumElts + Imm) % NumElts;
12434 
12435   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12436   SmallVector<int, 8> Mask;
12437   for (unsigned i = 0; i < NumElts; ++i)
12438     Mask.push_back(Idx + i);
12439   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12440 }
12441 
12442 // Consider the following MIR after SelectionDAG, which produces output in
12443 // phyregs in the first case or virtregs in the second case.
12444 //
12445 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12446 // %5:gr32 = COPY $ebx
12447 // %6:gr32 = COPY $edx
12448 // %1:gr32 = COPY %6:gr32
12449 // %0:gr32 = COPY %5:gr32
12450 //
12451 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12452 // %1:gr32 = COPY %6:gr32
12453 // %0:gr32 = COPY %5:gr32
12454 //
12455 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12456 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12457 //
12458 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12459 // to a single virtreg (such as %0). The remaining outputs monotonically
12460 // increase in virtreg number from there. If a callbr has no outputs, then it
12461 // should not have a corresponding callbr landingpad; in fact, the callbr
12462 // landingpad would not even be able to refer to such a callbr.
12463 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12464   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12465   // There is definitely at least one copy.
12466   assert(MI->getOpcode() == TargetOpcode::COPY &&
12467          "start of copy chain MUST be COPY");
12468   Reg = MI->getOperand(1).getReg();
12469   MI = MRI.def_begin(Reg)->getParent();
12470   // There may be an optional second copy.
12471   if (MI->getOpcode() == TargetOpcode::COPY) {
12472     assert(Reg.isVirtual() && "expected COPY of virtual register");
12473     Reg = MI->getOperand(1).getReg();
12474     assert(Reg.isPhysical() && "expected COPY of physical register");
12475     MI = MRI.def_begin(Reg)->getParent();
12476   }
12477   // The start of the chain must be an INLINEASM_BR.
12478   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12479          "end of copy chain MUST be INLINEASM_BR");
12480   return Reg;
12481 }
12482 
12483 // We must do this walk rather than the simpler
12484 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12485 // otherwise we will end up with copies of virtregs only valid along direct
12486 // edges.
12487 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12488   SmallVector<EVT, 8> ResultVTs;
12489   SmallVector<SDValue, 8> ResultValues;
12490   const auto *CBR =
12491       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12492 
12493   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12494   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12495   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12496 
12497   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12498   SDValue Chain = DAG.getRoot();
12499 
12500   // Re-parse the asm constraints string.
12501   TargetLowering::AsmOperandInfoVector TargetConstraints =
12502       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12503   for (auto &T : TargetConstraints) {
12504     SDISelAsmOperandInfo OpInfo(T);
12505     if (OpInfo.Type != InlineAsm::isOutput)
12506       continue;
12507 
12508     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12509     // individual constraint.
12510     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12511 
12512     switch (OpInfo.ConstraintType) {
12513     case TargetLowering::C_Register:
12514     case TargetLowering::C_RegisterClass: {
12515       // Fill in OpInfo.AssignedRegs.Regs.
12516       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12517 
12518       // getRegistersForValue may produce 1 to many registers based on whether
12519       // the OpInfo.ConstraintVT is legal on the target or not.
12520       for (size_t i = 0, e = OpInfo.AssignedRegs.Regs.size(); i != e; ++i) {
12521         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12522         if (Register::isPhysicalRegister(OriginalDef))
12523           FuncInfo.MBB->addLiveIn(OriginalDef);
12524         // Update the assigned registers to use the original defs.
12525         OpInfo.AssignedRegs.Regs[i] = OriginalDef;
12526       }
12527 
12528       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12529           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12530       ResultValues.push_back(V);
12531       ResultVTs.push_back(OpInfo.ConstraintVT);
12532       break;
12533     }
12534     case TargetLowering::C_Other: {
12535       SDValue Flag;
12536       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12537                                                   OpInfo, DAG);
12538       ++InitialDef;
12539       ResultValues.push_back(V);
12540       ResultVTs.push_back(OpInfo.ConstraintVT);
12541       break;
12542     }
12543     default:
12544       break;
12545     }
12546   }
12547   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12548                           DAG.getVTList(ResultVTs), ResultValues);
12549   setValue(&I, V);
12550 }
12551