xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision ae6dc64ec670891cb15049277e43133d4df7fb4b)
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/RuntimeLibcallUtil.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 <deque>
108 #include <iterator>
109 #include <limits>
110 #include <optional>
111 #include <tuple>
112 
113 using namespace llvm;
114 using namespace PatternMatch;
115 using namespace SwitchCG;
116 
117 #define DEBUG_TYPE "isel"
118 
119 /// LimitFloatPrecision - Generate low-precision inline sequences for
120 /// some float libcalls (6, 8 or 12 bits).
121 static unsigned LimitFloatPrecision;
122 
123 static cl::opt<bool>
124     InsertAssertAlign("insert-assert-align", cl::init(true),
125                       cl::desc("Insert the experimental `assertalign` node."),
126                       cl::ReallyHidden);
127 
128 static cl::opt<unsigned, true>
129     LimitFPPrecision("limit-float-precision",
130                      cl::desc("Generate low-precision inline sequences "
131                               "for some float libcalls"),
132                      cl::location(LimitFloatPrecision), cl::Hidden,
133                      cl::init(0));
134 
135 static cl::opt<unsigned> SwitchPeelThreshold(
136     "switch-peel-threshold", cl::Hidden, cl::init(66),
137     cl::desc("Set the case probability threshold for peeling the case from a "
138              "switch statement. A value greater than 100 will void this "
139              "optimization"));
140 
141 // Limit the width of DAG chains. This is important in general to prevent
142 // DAG-based analysis from blowing up. For example, alias analysis and
143 // load clustering may not complete in reasonable time. It is difficult to
144 // recognize and avoid this situation within each individual analysis, and
145 // future analyses are likely to have the same behavior. Limiting DAG width is
146 // the safe approach and will be especially important with global DAGs.
147 //
148 // MaxParallelChains default is arbitrarily high to avoid affecting
149 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
150 // sequence over this should have been converted to llvm.memcpy by the
151 // frontend. It is easy to induce this behavior with .ll code such as:
152 // %buffer = alloca [4096 x i8]
153 // %data = load [4096 x i8]* %argPtr
154 // store [4096 x i8] %data, [4096 x i8]* %buffer
155 static const unsigned MaxParallelChains = 64;
156 
157 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
158                                       const SDValue *Parts, unsigned NumParts,
159                                       MVT PartVT, EVT ValueVT, const Value *V,
160                                       SDValue InChain,
161                                       std::optional<CallingConv::ID> CC);
162 
163 /// getCopyFromParts - Create a value that contains the specified legal parts
164 /// combined into the value they represent.  If the parts combine to a type
165 /// larger than ValueVT then AssertOp can be used to specify whether the extra
166 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
167 /// (ISD::AssertSext).
168 static SDValue
169 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
170                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
171                  SDValue InChain,
172                  std::optional<CallingConv::ID> CC = std::nullopt,
173                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
174   // Let the target assemble the parts if it wants to
175   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
176   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
177                                                    PartVT, ValueVT, CC))
178     return Val;
179 
180   if (ValueVT.isVector())
181     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
182                                   InChain, CC);
183 
184   assert(NumParts > 0 && "No parts to assemble!");
185   SDValue Val = Parts[0];
186 
187   if (NumParts > 1) {
188     // Assemble the value from multiple parts.
189     if (ValueVT.isInteger()) {
190       unsigned PartBits = PartVT.getSizeInBits();
191       unsigned ValueBits = ValueVT.getSizeInBits();
192 
193       // Assemble the power of 2 part.
194       unsigned RoundParts = llvm::bit_floor(NumParts);
195       unsigned RoundBits = PartBits * RoundParts;
196       EVT RoundVT = RoundBits == ValueBits ?
197         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
198       SDValue Lo, Hi;
199 
200       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
201 
202       if (RoundParts > 2) {
203         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
204                               InChain);
205         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
206                               PartVT, HalfVT, V, InChain);
207       } else {
208         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
209         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
210       }
211 
212       if (DAG.getDataLayout().isBigEndian())
213         std::swap(Lo, Hi);
214 
215       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
216 
217       if (RoundParts < NumParts) {
218         // Assemble the trailing non-power-of-2 part.
219         unsigned OddParts = NumParts - RoundParts;
220         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
221         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
222                               OddVT, V, InChain, CC);
223 
224         // Combine the round and odd parts.
225         Lo = Val;
226         if (DAG.getDataLayout().isBigEndian())
227           std::swap(Lo, Hi);
228         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
229         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
230         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
231                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
232                                          TLI.getShiftAmountTy(
233                                              TotalVT, DAG.getDataLayout())));
234         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
235         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
236       }
237     } else if (PartVT.isFloatingPoint()) {
238       // FP split into multiple FP parts (for ppcf128)
239       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
240              "Unexpected split");
241       SDValue Lo, Hi;
242       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
243       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
244       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
245         std::swap(Lo, Hi);
246       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
247     } else {
248       // FP split into integer parts (soft fp)
249       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
250              !PartVT.isVector() && "Unexpected split");
251       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
252       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
253                              InChain, CC);
254     }
255   }
256 
257   // There is now one part, held in Val.  Correct it to match ValueVT.
258   // PartEVT is the type of the register class that holds the value.
259   // ValueVT is the type of the inline asm operation.
260   EVT PartEVT = Val.getValueType();
261 
262   if (PartEVT == ValueVT)
263     return Val;
264 
265   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
266       ValueVT.bitsLT(PartEVT)) {
267     // For an FP value in an integer part, we need to truncate to the right
268     // width first.
269     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
270     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
271   }
272 
273   // Handle types that have the same size.
274   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
275     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
276 
277   // Handle types with different sizes.
278   if (PartEVT.isInteger() && ValueVT.isInteger()) {
279     if (ValueVT.bitsLT(PartEVT)) {
280       // For a truncate, see if we have any information to
281       // indicate whether the truncated bits will always be
282       // zero or sign-extension.
283       if (AssertOp)
284         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
285                           DAG.getValueType(ValueVT));
286       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
287     }
288     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
289   }
290 
291   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
292     // FP_ROUND's are always exact here.
293     if (ValueVT.bitsLT(Val.getValueType())) {
294 
295       SDValue NoChange =
296           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
297 
298       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
299               llvm::Attribute::StrictFP)) {
300         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
301                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
302                            NoChange);
303       }
304 
305       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
306     }
307 
308     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
309   }
310 
311   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
312   // then truncating.
313   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
314       ValueVT.bitsLT(PartEVT)) {
315     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
316     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
317   }
318 
319   report_fatal_error("Unknown mismatch in getCopyFromParts!");
320 }
321 
322 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
323                                               const Twine &ErrMsg) {
324   const Instruction *I = dyn_cast_or_null<Instruction>(V);
325   if (!V)
326     return Ctx.emitError(ErrMsg);
327 
328   const char *AsmError = ", possible invalid constraint for vector type";
329   if (const CallInst *CI = dyn_cast<CallInst>(I))
330     if (CI->isInlineAsm())
331       return Ctx.emitError(I, ErrMsg + AsmError);
332 
333   return Ctx.emitError(I, ErrMsg);
334 }
335 
336 /// getCopyFromPartsVector - Create a value that contains the specified legal
337 /// parts combined into the value they represent.  If the parts combine to a
338 /// type larger than ValueVT then AssertOp can be used to specify whether the
339 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
340 /// ValueVT (ISD::AssertSext).
341 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
342                                       const SDValue *Parts, unsigned NumParts,
343                                       MVT PartVT, EVT ValueVT, const Value *V,
344                                       SDValue InChain,
345                                       std::optional<CallingConv::ID> CallConv) {
346   assert(ValueVT.isVector() && "Not a vector value");
347   assert(NumParts > 0 && "No parts to assemble!");
348   const bool IsABIRegCopy = CallConv.has_value();
349 
350   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
351   SDValue Val = Parts[0];
352 
353   // Handle a multi-element vector.
354   if (NumParts > 1) {
355     EVT IntermediateVT;
356     MVT RegisterVT;
357     unsigned NumIntermediates;
358     unsigned NumRegs;
359 
360     if (IsABIRegCopy) {
361       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
362           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
363           NumIntermediates, RegisterVT);
364     } else {
365       NumRegs =
366           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
367                                      NumIntermediates, RegisterVT);
368     }
369 
370     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
371     NumParts = NumRegs; // Silence a compiler warning.
372     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
373     assert(RegisterVT.getSizeInBits() ==
374            Parts[0].getSimpleValueType().getSizeInBits() &&
375            "Part type sizes don't match!");
376 
377     // Assemble the parts into intermediate operands.
378     SmallVector<SDValue, 8> Ops(NumIntermediates);
379     if (NumIntermediates == NumParts) {
380       // If the register was not expanded, truncate or copy the value,
381       // as appropriate.
382       for (unsigned i = 0; i != NumParts; ++i)
383         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
384                                   V, InChain, CallConv);
385     } else if (NumParts > 0) {
386       // If the intermediate type was expanded, build the intermediate
387       // operands from the parts.
388       assert(NumParts % NumIntermediates == 0 &&
389              "Must expand into a divisible number of parts!");
390       unsigned Factor = NumParts / NumIntermediates;
391       for (unsigned i = 0; i != NumIntermediates; ++i)
392         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
393                                   IntermediateVT, V, InChain, CallConv);
394     }
395 
396     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
397     // intermediate operands.
398     EVT BuiltVectorTy =
399         IntermediateVT.isVector()
400             ? EVT::getVectorVT(
401                   *DAG.getContext(), IntermediateVT.getScalarType(),
402                   IntermediateVT.getVectorElementCount() * NumParts)
403             : EVT::getVectorVT(*DAG.getContext(),
404                                IntermediateVT.getScalarType(),
405                                NumIntermediates);
406     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
407                                                 : ISD::BUILD_VECTOR,
408                       DL, BuiltVectorTy, Ops);
409   }
410 
411   // There is now one part, held in Val.  Correct it to match ValueVT.
412   EVT PartEVT = Val.getValueType();
413 
414   if (PartEVT == ValueVT)
415     return Val;
416 
417   if (PartEVT.isVector()) {
418     // Vector/Vector bitcast.
419     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
420       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
421 
422     // If the parts vector has more elements than the value vector, then we
423     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
424     // Extract the elements we want.
425     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
426       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
427               ValueVT.getVectorElementCount().getKnownMinValue()) &&
428              (PartEVT.getVectorElementCount().isScalable() ==
429               ValueVT.getVectorElementCount().isScalable()) &&
430              "Cannot narrow, it would be a lossy transformation");
431       PartEVT =
432           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
433                            ValueVT.getVectorElementCount());
434       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
435                         DAG.getVectorIdxConstant(0, DL));
436       if (PartEVT == ValueVT)
437         return Val;
438       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
439         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
440 
441       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
442       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
443         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
444     }
445 
446     // Promoted vector extract
447     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
448   }
449 
450   // Trivial bitcast if the types are the same size and the destination
451   // vector type is legal.
452   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
453       TLI.isTypeLegal(ValueVT))
454     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
455 
456   if (ValueVT.getVectorNumElements() != 1) {
457      // Certain ABIs require that vectors are passed as integers. For vectors
458      // are the same size, this is an obvious bitcast.
459      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
460        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
461      } else if (ValueVT.bitsLT(PartEVT)) {
462        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
463        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
464        // Drop the extra bits.
465        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
466        return DAG.getBitcast(ValueVT, Val);
467      }
468 
469      diagnosePossiblyInvalidConstraint(
470          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
471      return DAG.getUNDEF(ValueVT);
472   }
473 
474   // Handle cases such as i8 -> <1 x i1>
475   EVT ValueSVT = ValueVT.getVectorElementType();
476   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
477     unsigned ValueSize = ValueSVT.getSizeInBits();
478     if (ValueSize == PartEVT.getSizeInBits()) {
479       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
480     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
481       // It's possible a scalar floating point type gets softened to integer and
482       // then promoted to a larger integer. If PartEVT is the larger integer
483       // we need to truncate it and then bitcast to the FP type.
484       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
485       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
486       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
487       Val = DAG.getBitcast(ValueSVT, Val);
488     } else {
489       Val = ValueVT.isFloatingPoint()
490                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
491                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
492     }
493   }
494 
495   return DAG.getBuildVector(ValueVT, DL, Val);
496 }
497 
498 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
499                                  SDValue Val, SDValue *Parts, unsigned NumParts,
500                                  MVT PartVT, const Value *V,
501                                  std::optional<CallingConv::ID> CallConv);
502 
503 /// getCopyToParts - Create a series of nodes that contain the specified value
504 /// split into legal parts.  If the parts contain more bits than Val, then, for
505 /// integers, ExtendKind can be used to specify how to generate the extra bits.
506 static void
507 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
508                unsigned NumParts, MVT PartVT, const Value *V,
509                std::optional<CallingConv::ID> CallConv = std::nullopt,
510                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
511   // Let the target split the parts if it wants to
512   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
513   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
514                                       CallConv))
515     return;
516   EVT ValueVT = Val.getValueType();
517 
518   // Handle the vector case separately.
519   if (ValueVT.isVector())
520     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
521                                 CallConv);
522 
523   unsigned OrigNumParts = NumParts;
524   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
525          "Copying to an illegal type!");
526 
527   if (NumParts == 0)
528     return;
529 
530   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
531   EVT PartEVT = PartVT;
532   if (PartEVT == ValueVT) {
533     assert(NumParts == 1 && "No-op copy with multiple parts!");
534     Parts[0] = Val;
535     return;
536   }
537 
538   unsigned PartBits = PartVT.getSizeInBits();
539   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
540     // If the parts cover more bits than the value has, promote the value.
541     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
542       assert(NumParts == 1 && "Do not know what to promote to!");
543       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
544     } else {
545       if (ValueVT.isFloatingPoint()) {
546         // FP values need to be bitcast, then extended if they are being put
547         // into a larger container.
548         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
549         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
550       }
551       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
552              ValueVT.isInteger() &&
553              "Unknown mismatch!");
554       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
555       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
556       if (PartVT == MVT::x86mmx)
557         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
558     }
559   } else if (PartBits == ValueVT.getSizeInBits()) {
560     // Different types of the same size.
561     assert(NumParts == 1 && PartEVT != ValueVT);
562     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
563   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
564     // If the parts cover less bits than value has, truncate the value.
565     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
566            ValueVT.isInteger() &&
567            "Unknown mismatch!");
568     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
569     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
570     if (PartVT == MVT::x86mmx)
571       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
572   }
573 
574   // The value may have changed - recompute ValueVT.
575   ValueVT = Val.getValueType();
576   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
577          "Failed to tile the value with PartVT!");
578 
579   if (NumParts == 1) {
580     if (PartEVT != ValueVT) {
581       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
582                                         "scalar-to-vector conversion failed");
583       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
584     }
585 
586     Parts[0] = Val;
587     return;
588   }
589 
590   // Expand the value into multiple parts.
591   if (NumParts & (NumParts - 1)) {
592     // The number of parts is not a power of 2.  Split off and copy the tail.
593     assert(PartVT.isInteger() && ValueVT.isInteger() &&
594            "Do not know what to expand to!");
595     unsigned RoundParts = llvm::bit_floor(NumParts);
596     unsigned RoundBits = RoundParts * PartBits;
597     unsigned OddParts = NumParts - RoundParts;
598     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
599       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
600 
601     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
602                    CallConv);
603 
604     if (DAG.getDataLayout().isBigEndian())
605       // The odd parts were reversed by getCopyToParts - unreverse them.
606       std::reverse(Parts + RoundParts, Parts + NumParts);
607 
608     NumParts = RoundParts;
609     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
610     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
611   }
612 
613   // The number of parts is a power of 2.  Repeatedly bisect the value using
614   // EXTRACT_ELEMENT.
615   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
616                          EVT::getIntegerVT(*DAG.getContext(),
617                                            ValueVT.getSizeInBits()),
618                          Val);
619 
620   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
621     for (unsigned i = 0; i < NumParts; i += StepSize) {
622       unsigned ThisBits = StepSize * PartBits / 2;
623       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
624       SDValue &Part0 = Parts[i];
625       SDValue &Part1 = Parts[i+StepSize/2];
626 
627       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
628                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
629       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
630                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
631 
632       if (ThisBits == PartBits && ThisVT != PartVT) {
633         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
634         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
635       }
636     }
637   }
638 
639   if (DAG.getDataLayout().isBigEndian())
640     std::reverse(Parts, Parts + OrigNumParts);
641 }
642 
643 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
644                                      const SDLoc &DL, EVT PartVT) {
645   if (!PartVT.isVector())
646     return SDValue();
647 
648   EVT ValueVT = Val.getValueType();
649   EVT PartEVT = PartVT.getVectorElementType();
650   EVT ValueEVT = ValueVT.getVectorElementType();
651   ElementCount PartNumElts = PartVT.getVectorElementCount();
652   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
653 
654   // We only support widening vectors with equivalent element types and
655   // fixed/scalable properties. If a target needs to widen a fixed-length type
656   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
657   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
658       PartNumElts.isScalable() != ValueNumElts.isScalable())
659     return SDValue();
660 
661   // Have a try for bf16 because some targets share its ABI with fp16.
662   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
663     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
664            "Cannot widen to illegal type");
665     Val = DAG.getNode(ISD::BITCAST, DL,
666                       ValueVT.changeVectorElementType(MVT::f16), Val);
667   } else if (PartEVT != ValueEVT) {
668     return SDValue();
669   }
670 
671   // Widening a scalable vector to another scalable vector is done by inserting
672   // the vector into a larger undef one.
673   if (PartNumElts.isScalable())
674     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
675                        Val, DAG.getVectorIdxConstant(0, DL));
676 
677   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
678   // undef elements.
679   SmallVector<SDValue, 16> Ops;
680   DAG.ExtractVectorElements(Val, Ops);
681   SDValue EltUndef = DAG.getUNDEF(PartEVT);
682   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
683 
684   // FIXME: Use CONCAT for 2x -> 4x.
685   return DAG.getBuildVector(PartVT, DL, Ops);
686 }
687 
688 /// getCopyToPartsVector - Create a series of nodes that contain the specified
689 /// value split into legal parts.
690 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
691                                  SDValue Val, SDValue *Parts, unsigned NumParts,
692                                  MVT PartVT, const Value *V,
693                                  std::optional<CallingConv::ID> CallConv) {
694   EVT ValueVT = Val.getValueType();
695   assert(ValueVT.isVector() && "Not a vector");
696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
697   const bool IsABIRegCopy = CallConv.has_value();
698 
699   if (NumParts == 1) {
700     EVT PartEVT = PartVT;
701     if (PartEVT == ValueVT) {
702       // Nothing to do.
703     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
704       // Bitconvert vector->vector case.
705       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
706     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
707       Val = Widened;
708     } else if (PartVT.isVector() &&
709                PartEVT.getVectorElementType().bitsGE(
710                    ValueVT.getVectorElementType()) &&
711                PartEVT.getVectorElementCount() ==
712                    ValueVT.getVectorElementCount()) {
713 
714       // Promoted vector extract
715       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
716     } else if (PartEVT.isVector() &&
717                PartEVT.getVectorElementType() !=
718                    ValueVT.getVectorElementType() &&
719                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
720                    TargetLowering::TypeWidenVector) {
721       // Combination of widening and promotion.
722       EVT WidenVT =
723           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
724                            PartVT.getVectorElementCount());
725       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
726       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
727     } else {
728       // Don't extract an integer from a float vector. This can happen if the
729       // FP type gets softened to integer and then promoted. The promotion
730       // prevents it from being picked up by the earlier bitcast case.
731       if (ValueVT.getVectorElementCount().isScalar() &&
732           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
733         // If we reach this condition and PartVT is FP, this means that
734         // ValueVT is also FP and both have a different size, otherwise we
735         // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
736         // would be invalid since that would mean the smaller FP type has to
737         // be extended to the larger one.
738         if (PartVT.isFloatingPoint()) {
739           Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
740           Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
741         } else
742           Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
743                             DAG.getVectorIdxConstant(0, DL));
744       } else {
745         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
746         assert(PartVT.getFixedSizeInBits() > ValueSize &&
747                "lossy conversion of vector to scalar type");
748         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
749         Val = DAG.getBitcast(IntermediateType, Val);
750         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
751       }
752     }
753 
754     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
755     Parts[0] = Val;
756     return;
757   }
758 
759   // Handle a multi-element vector.
760   EVT IntermediateVT;
761   MVT RegisterVT;
762   unsigned NumIntermediates;
763   unsigned NumRegs;
764   if (IsABIRegCopy) {
765     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
766         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
767         RegisterVT);
768   } else {
769     NumRegs =
770         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
771                                    NumIntermediates, RegisterVT);
772   }
773 
774   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
775   NumParts = NumRegs; // Silence a compiler warning.
776   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
777 
778   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
779          "Mixing scalable and fixed vectors when copying in parts");
780 
781   std::optional<ElementCount> DestEltCnt;
782 
783   if (IntermediateVT.isVector())
784     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
785   else
786     DestEltCnt = ElementCount::getFixed(NumIntermediates);
787 
788   EVT BuiltVectorTy = EVT::getVectorVT(
789       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
790 
791   if (ValueVT == BuiltVectorTy) {
792     // Nothing to do.
793   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
794     // Bitconvert vector->vector case.
795     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
796   } else {
797     if (BuiltVectorTy.getVectorElementType().bitsGT(
798             ValueVT.getVectorElementType())) {
799       // Integer promotion.
800       ValueVT = EVT::getVectorVT(*DAG.getContext(),
801                                  BuiltVectorTy.getVectorElementType(),
802                                  ValueVT.getVectorElementCount());
803       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
804     }
805 
806     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
807       Val = Widened;
808     }
809   }
810 
811   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
812 
813   // Split the vector into intermediate operands.
814   SmallVector<SDValue, 8> Ops(NumIntermediates);
815   for (unsigned i = 0; i != NumIntermediates; ++i) {
816     if (IntermediateVT.isVector()) {
817       // This does something sensible for scalable vectors - see the
818       // definition of EXTRACT_SUBVECTOR for further details.
819       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
820       Ops[i] =
821           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
822                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
823     } else {
824       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
825                            DAG.getVectorIdxConstant(i, DL));
826     }
827   }
828 
829   // Split the intermediate operands into legal parts.
830   if (NumParts == NumIntermediates) {
831     // If the register was not expanded, promote or copy the value,
832     // as appropriate.
833     for (unsigned i = 0; i != NumParts; ++i)
834       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
835   } else if (NumParts > 0) {
836     // If the intermediate type was expanded, split each the value into
837     // legal parts.
838     assert(NumIntermediates != 0 && "division by zero");
839     assert(NumParts % NumIntermediates == 0 &&
840            "Must expand into a divisible number of parts!");
841     unsigned Factor = NumParts / NumIntermediates;
842     for (unsigned i = 0; i != NumIntermediates; ++i)
843       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
844                      CallConv);
845   }
846 }
847 
848 RegsForValue::RegsForValue(const SmallVector<unsigned, 4> &regs, MVT regvt,
849                            EVT valuevt, std::optional<CallingConv::ID> CC)
850     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
851       RegCount(1, regs.size()), CallConv(CC) {}
852 
853 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
854                            const DataLayout &DL, unsigned Reg, Type *Ty,
855                            std::optional<CallingConv::ID> CC) {
856   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
857 
858   CallConv = CC;
859 
860   for (EVT ValueVT : ValueVTs) {
861     unsigned NumRegs =
862         isABIMangled()
863             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
864             : TLI.getNumRegisters(Context, ValueVT);
865     MVT RegisterVT =
866         isABIMangled()
867             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
868             : TLI.getRegisterType(Context, ValueVT);
869     for (unsigned i = 0; i != NumRegs; ++i)
870       Regs.push_back(Reg + i);
871     RegVTs.push_back(RegisterVT);
872     RegCount.push_back(NumRegs);
873     Reg += NumRegs;
874   }
875 }
876 
877 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
878                                       FunctionLoweringInfo &FuncInfo,
879                                       const SDLoc &dl, SDValue &Chain,
880                                       SDValue *Glue, const Value *V) const {
881   // A Value with type {} or [0 x %t] needs no registers.
882   if (ValueVTs.empty())
883     return SDValue();
884 
885   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
886 
887   // Assemble the legal parts into the final values.
888   SmallVector<SDValue, 4> Values(ValueVTs.size());
889   SmallVector<SDValue, 8> Parts;
890   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
891     // Copy the legal parts from the registers.
892     EVT ValueVT = ValueVTs[Value];
893     unsigned NumRegs = RegCount[Value];
894     MVT RegisterVT = isABIMangled()
895                          ? TLI.getRegisterTypeForCallingConv(
896                                *DAG.getContext(), *CallConv, RegVTs[Value])
897                          : RegVTs[Value];
898 
899     Parts.resize(NumRegs);
900     for (unsigned i = 0; i != NumRegs; ++i) {
901       SDValue P;
902       if (!Glue) {
903         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
904       } else {
905         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
906         *Glue = P.getValue(2);
907       }
908 
909       Chain = P.getValue(1);
910       Parts[i] = P;
911 
912       // If the source register was virtual and if we know something about it,
913       // add an assert node.
914       if (!Register::isVirtualRegister(Regs[Part + i]) ||
915           !RegisterVT.isInteger())
916         continue;
917 
918       const FunctionLoweringInfo::LiveOutInfo *LOI =
919         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
920       if (!LOI)
921         continue;
922 
923       unsigned RegSize = RegisterVT.getScalarSizeInBits();
924       unsigned NumSignBits = LOI->NumSignBits;
925       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
926 
927       if (NumZeroBits == RegSize) {
928         // The current value is a zero.
929         // Explicitly express that as it would be easier for
930         // optimizations to kick in.
931         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
932         continue;
933       }
934 
935       // FIXME: We capture more information than the dag can represent.  For
936       // now, just use the tightest assertzext/assertsext possible.
937       bool isSExt;
938       EVT FromVT(MVT::Other);
939       if (NumZeroBits) {
940         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
941         isSExt = false;
942       } else if (NumSignBits > 1) {
943         FromVT =
944             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
945         isSExt = true;
946       } else {
947         continue;
948       }
949       // Add an assertion node.
950       assert(FromVT != MVT::Other);
951       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
952                              RegisterVT, P, DAG.getValueType(FromVT));
953     }
954 
955     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
956                                      RegisterVT, ValueVT, V, Chain, CallConv);
957     Part += NumRegs;
958     Parts.clear();
959   }
960 
961   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
962 }
963 
964 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
965                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
966                                  const Value *V,
967                                  ISD::NodeType PreferredExtendType) const {
968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
969   ISD::NodeType ExtendKind = PreferredExtendType;
970 
971   // Get the list of the values's legal parts.
972   unsigned NumRegs = Regs.size();
973   SmallVector<SDValue, 8> Parts(NumRegs);
974   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
975     unsigned NumParts = RegCount[Value];
976 
977     MVT RegisterVT = isABIMangled()
978                          ? TLI.getRegisterTypeForCallingConv(
979                                *DAG.getContext(), *CallConv, RegVTs[Value])
980                          : RegVTs[Value];
981 
982     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
983       ExtendKind = ISD::ZERO_EXTEND;
984 
985     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
986                    NumParts, RegisterVT, V, CallConv, ExtendKind);
987     Part += NumParts;
988   }
989 
990   // Copy the parts into the registers.
991   SmallVector<SDValue, 8> Chains(NumRegs);
992   for (unsigned i = 0; i != NumRegs; ++i) {
993     SDValue Part;
994     if (!Glue) {
995       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
996     } else {
997       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
998       *Glue = Part.getValue(1);
999     }
1000 
1001     Chains[i] = Part.getValue(0);
1002   }
1003 
1004   if (NumRegs == 1 || Glue)
1005     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1006     // flagged to it. That is the CopyToReg nodes and the user are considered
1007     // a single scheduling unit. If we create a TokenFactor and return it as
1008     // chain, then the TokenFactor is both a predecessor (operand) of the
1009     // user as well as a successor (the TF operands are flagged to the user).
1010     // c1, f1 = CopyToReg
1011     // c2, f2 = CopyToReg
1012     // c3     = TokenFactor c1, c2
1013     // ...
1014     //        = op c3, ..., f2
1015     Chain = Chains[NumRegs-1];
1016   else
1017     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1018 }
1019 
1020 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1021                                         unsigned MatchingIdx, const SDLoc &dl,
1022                                         SelectionDAG &DAG,
1023                                         std::vector<SDValue> &Ops) const {
1024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1025 
1026   InlineAsm::Flag Flag(Code, Regs.size());
1027   if (HasMatching)
1028     Flag.setMatchingOp(MatchingIdx);
1029   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1030     // Put the register class of the virtual registers in the flag word.  That
1031     // way, later passes can recompute register class constraints for inline
1032     // assembly as well as normal instructions.
1033     // Don't do this for tied operands that can use the regclass information
1034     // from the def.
1035     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1036     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1037     Flag.setRegClass(RC->getID());
1038   }
1039 
1040   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1041   Ops.push_back(Res);
1042 
1043   if (Code == InlineAsm::Kind::Clobber) {
1044     // Clobbers should always have a 1:1 mapping with registers, and may
1045     // reference registers that have illegal (e.g. vector) types. Hence, we
1046     // shouldn't try to apply any sort of splitting logic to them.
1047     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1048            "No 1:1 mapping from clobbers to regs?");
1049     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1050     (void)SP;
1051     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1052       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1053       assert(
1054           (Regs[I] != SP ||
1055            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1056           "If we clobbered the stack pointer, MFI should know about it.");
1057     }
1058     return;
1059   }
1060 
1061   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1062     MVT RegisterVT = RegVTs[Value];
1063     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1064                                            RegisterVT);
1065     for (unsigned i = 0; i != NumRegs; ++i) {
1066       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1067       unsigned TheReg = Regs[Reg++];
1068       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1069     }
1070   }
1071 }
1072 
1073 SmallVector<std::pair<unsigned, TypeSize>, 4>
1074 RegsForValue::getRegsAndSizes() const {
1075   SmallVector<std::pair<unsigned, TypeSize>, 4> OutVec;
1076   unsigned I = 0;
1077   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1078     unsigned RegCount = std::get<0>(CountAndVT);
1079     MVT RegisterVT = std::get<1>(CountAndVT);
1080     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1081     for (unsigned E = I + RegCount; I != E; ++I)
1082       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1083   }
1084   return OutVec;
1085 }
1086 
1087 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis *aa,
1088                                AssumptionCache *ac,
1089                                const TargetLibraryInfo *li) {
1090   AA = aa;
1091   AC = ac;
1092   GFI = gfi;
1093   LibInfo = li;
1094   Context = DAG.getContext();
1095   LPadToCallSiteMap.clear();
1096   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1097   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1098       *DAG.getMachineFunction().getFunction().getParent());
1099 }
1100 
1101 void SelectionDAGBuilder::clear() {
1102   NodeMap.clear();
1103   UnusedArgNodeMap.clear();
1104   PendingLoads.clear();
1105   PendingExports.clear();
1106   PendingConstrainedFP.clear();
1107   PendingConstrainedFPStrict.clear();
1108   CurInst = nullptr;
1109   HasTailCall = false;
1110   SDNodeOrder = LowestSDNodeOrder;
1111   StatepointLowering.clear();
1112 }
1113 
1114 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1115   DanglingDebugInfoMap.clear();
1116 }
1117 
1118 // Update DAG root to include dependencies on Pending chains.
1119 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1120   SDValue Root = DAG.getRoot();
1121 
1122   if (Pending.empty())
1123     return Root;
1124 
1125   // Add current root to PendingChains, unless we already indirectly
1126   // depend on it.
1127   if (Root.getOpcode() != ISD::EntryToken) {
1128     unsigned i = 0, e = Pending.size();
1129     for (; i != e; ++i) {
1130       assert(Pending[i].getNode()->getNumOperands() > 1);
1131       if (Pending[i].getNode()->getOperand(0) == Root)
1132         break;  // Don't add the root if we already indirectly depend on it.
1133     }
1134 
1135     if (i == e)
1136       Pending.push_back(Root);
1137   }
1138 
1139   if (Pending.size() == 1)
1140     Root = Pending[0];
1141   else
1142     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1143 
1144   DAG.setRoot(Root);
1145   Pending.clear();
1146   return Root;
1147 }
1148 
1149 SDValue SelectionDAGBuilder::getMemoryRoot() {
1150   return updateRoot(PendingLoads);
1151 }
1152 
1153 SDValue SelectionDAGBuilder::getRoot() {
1154   // Chain up all pending constrained intrinsics together with all
1155   // pending loads, by simply appending them to PendingLoads and
1156   // then calling getMemoryRoot().
1157   PendingLoads.reserve(PendingLoads.size() +
1158                        PendingConstrainedFP.size() +
1159                        PendingConstrainedFPStrict.size());
1160   PendingLoads.append(PendingConstrainedFP.begin(),
1161                       PendingConstrainedFP.end());
1162   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1163                       PendingConstrainedFPStrict.end());
1164   PendingConstrainedFP.clear();
1165   PendingConstrainedFPStrict.clear();
1166   return getMemoryRoot();
1167 }
1168 
1169 SDValue SelectionDAGBuilder::getControlRoot() {
1170   // We need to emit pending fpexcept.strict constrained intrinsics,
1171   // so append them to the PendingExports list.
1172   PendingExports.append(PendingConstrainedFPStrict.begin(),
1173                         PendingConstrainedFPStrict.end());
1174   PendingConstrainedFPStrict.clear();
1175   return updateRoot(PendingExports);
1176 }
1177 
1178 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1179                                              DILocalVariable *Variable,
1180                                              DIExpression *Expression,
1181                                              DebugLoc DL) {
1182   assert(Variable && "Missing variable");
1183 
1184   // Check if address has undef value.
1185   if (!Address || isa<UndefValue>(Address) ||
1186       (Address->use_empty() && !isa<Argument>(Address))) {
1187     LLVM_DEBUG(
1188         dbgs()
1189         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1190     return;
1191   }
1192 
1193   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1194 
1195   SDValue &N = NodeMap[Address];
1196   if (!N.getNode() && isa<Argument>(Address))
1197     // Check unused arguments map.
1198     N = UnusedArgNodeMap[Address];
1199   SDDbgValue *SDV;
1200   if (N.getNode()) {
1201     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1202       Address = BCI->getOperand(0);
1203     // Parameters are handled specially.
1204     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1205     if (IsParameter && FINode) {
1206       // Byval parameter. We have a frame index at this point.
1207       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1208                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1209     } else if (isa<Argument>(Address)) {
1210       // Address is an argument, so try to emit its dbg value using
1211       // virtual register info from the FuncInfo.ValueMap.
1212       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1213                                FuncArgumentDbgValueKind::Declare, N);
1214       return;
1215     } else {
1216       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1217                             true, DL, SDNodeOrder);
1218     }
1219     DAG.AddDbgValue(SDV, IsParameter);
1220   } else {
1221     // If Address is an argument then try to emit its dbg value using
1222     // virtual register info from the FuncInfo.ValueMap.
1223     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1224                                   FuncArgumentDbgValueKind::Declare, N)) {
1225       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1226                         << " (could not emit func-arg dbg_value)\n");
1227     }
1228   }
1229   return;
1230 }
1231 
1232 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1233   // Add SDDbgValue nodes for any var locs here. Do so before updating
1234   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1235   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1236     // Add SDDbgValue nodes for any var locs here. Do so before updating
1237     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1238     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1239          It != End; ++It) {
1240       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1241       dropDanglingDebugInfo(Var, It->Expr);
1242       if (It->Values.isKillLocation(It->Expr)) {
1243         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1244         continue;
1245       }
1246       SmallVector<Value *> Values(It->Values.location_ops());
1247       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1248                             It->Values.hasArgList())) {
1249         SmallVector<Value *, 4> Vals(It->Values.location_ops());
1250         addDanglingDebugInfo(Vals,
1251                              FnVarLocs->getDILocalVariable(It->VariableID),
1252                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1253       }
1254     }
1255   }
1256 
1257   // We must skip DbgVariableRecords if they've already been processed above as
1258   // we have just emitted the debug values resulting from assignment tracking
1259   // analysis, making any existing DbgVariableRecords redundant (and probably
1260   // less correct). We still need to process DbgLabelRecords. This does sink
1261   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1262   // be important as it does so deterministcally and ordering between
1263   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1264   // printing).
1265   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1266   // Is there is any debug-info attached to this instruction, in the form of
1267   // DbgRecord non-instruction debug-info records.
1268   for (DbgRecord &DR : I.getDbgRecordRange()) {
1269     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1270       assert(DLR->getLabel() && "Missing label");
1271       SDDbgLabel *SDV =
1272           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1273       DAG.AddDbgLabel(SDV);
1274       continue;
1275     }
1276 
1277     if (SkipDbgVariableRecords)
1278       continue;
1279     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1280     DILocalVariable *Variable = DVR.getVariable();
1281     DIExpression *Expression = DVR.getExpression();
1282     dropDanglingDebugInfo(Variable, Expression);
1283 
1284     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1285       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1286         continue;
1287       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1288                         << "\n");
1289       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1290                          DVR.getDebugLoc());
1291       continue;
1292     }
1293 
1294     // A DbgVariableRecord with no locations is a kill location.
1295     SmallVector<Value *, 4> Values(DVR.location_ops());
1296     if (Values.empty()) {
1297       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1298                            SDNodeOrder);
1299       continue;
1300     }
1301 
1302     // A DbgVariableRecord with an undef or absent location is also a kill
1303     // location.
1304     if (llvm::any_of(Values,
1305                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1306       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1307                            SDNodeOrder);
1308       continue;
1309     }
1310 
1311     bool IsVariadic = DVR.hasArgList();
1312     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1313                           SDNodeOrder, IsVariadic)) {
1314       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1315                            DVR.getDebugLoc(), SDNodeOrder);
1316     }
1317   }
1318 }
1319 
1320 void SelectionDAGBuilder::visit(const Instruction &I) {
1321   visitDbgInfo(I);
1322 
1323   // Set up outgoing PHI node register values before emitting the terminator.
1324   if (I.isTerminator()) {
1325     HandlePHINodesInSuccessorBlocks(I.getParent());
1326   }
1327 
1328   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1329   if (!isa<DbgInfoIntrinsic>(I))
1330     ++SDNodeOrder;
1331 
1332   CurInst = &I;
1333 
1334   // Set inserted listener only if required.
1335   bool NodeInserted = false;
1336   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1337   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1338   MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1339   if (PCSectionsMD || MMRA) {
1340     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1341         DAG, [&](SDNode *) { NodeInserted = true; });
1342   }
1343 
1344   visit(I.getOpcode(), I);
1345 
1346   if (!I.isTerminator() && !HasTailCall &&
1347       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1348     CopyToExportRegsIfNeeded(&I);
1349 
1350   // Handle metadata.
1351   if (PCSectionsMD || MMRA) {
1352     auto It = NodeMap.find(&I);
1353     if (It != NodeMap.end()) {
1354       if (PCSectionsMD)
1355         DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1356       if (MMRA)
1357         DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1358     } else if (NodeInserted) {
1359       // This should not happen; if it does, don't let it go unnoticed so we can
1360       // fix it. Relevant visit*() function is probably missing a setValue().
1361       errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1362              << I.getModule()->getName() << "]\n";
1363       LLVM_DEBUG(I.dump());
1364       assert(false);
1365     }
1366   }
1367 
1368   CurInst = nullptr;
1369 }
1370 
1371 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1372   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1373 }
1374 
1375 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1376   // Note: this doesn't use InstVisitor, because it has to work with
1377   // ConstantExpr's in addition to instructions.
1378   switch (Opcode) {
1379   default: llvm_unreachable("Unknown instruction type encountered!");
1380     // Build the switch statement using the Instruction.def file.
1381 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1382     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1383 #include "llvm/IR/Instruction.def"
1384   }
1385 }
1386 
1387 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1388                                             DILocalVariable *Variable,
1389                                             DebugLoc DL, unsigned Order,
1390                                             SmallVectorImpl<Value *> &Values,
1391                                             DIExpression *Expression) {
1392   // For variadic dbg_values we will now insert an undef.
1393   // FIXME: We can potentially recover these!
1394   SmallVector<SDDbgOperand, 2> Locs;
1395   for (const Value *V : Values) {
1396     auto *Undef = UndefValue::get(V->getType());
1397     Locs.push_back(SDDbgOperand::fromConst(Undef));
1398   }
1399   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1400                                         /*IsIndirect=*/false, DL, Order,
1401                                         /*IsVariadic=*/true);
1402   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1403   return true;
1404 }
1405 
1406 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1407                                                DILocalVariable *Var,
1408                                                DIExpression *Expr,
1409                                                bool IsVariadic, DebugLoc DL,
1410                                                unsigned Order) {
1411   if (IsVariadic) {
1412     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1413     return;
1414   }
1415   // TODO: Dangling debug info will eventually either be resolved or produce
1416   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1417   // between the original dbg.value location and its resolved DBG_VALUE,
1418   // which we should ideally fill with an extra Undef DBG_VALUE.
1419   assert(Values.size() == 1);
1420   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1421 }
1422 
1423 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1424                                                 const DIExpression *Expr) {
1425   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1426     DIVariable *DanglingVariable = DDI.getVariable();
1427     DIExpression *DanglingExpr = DDI.getExpression();
1428     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1429       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1430                         << printDDI(nullptr, DDI) << "\n");
1431       return true;
1432     }
1433     return false;
1434   };
1435 
1436   for (auto &DDIMI : DanglingDebugInfoMap) {
1437     DanglingDebugInfoVector &DDIV = DDIMI.second;
1438 
1439     // If debug info is to be dropped, run it through final checks to see
1440     // whether it can be salvaged.
1441     for (auto &DDI : DDIV)
1442       if (isMatchingDbgValue(DDI))
1443         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1444 
1445     erase_if(DDIV, isMatchingDbgValue);
1446   }
1447 }
1448 
1449 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1450 // generate the debug data structures now that we've seen its definition.
1451 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1452                                                    SDValue Val) {
1453   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1454   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1455     return;
1456 
1457   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1458   for (auto &DDI : DDIV) {
1459     DebugLoc DL = DDI.getDebugLoc();
1460     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1461     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1462     DILocalVariable *Variable = DDI.getVariable();
1463     DIExpression *Expr = DDI.getExpression();
1464     assert(Variable->isValidLocationForIntrinsic(DL) &&
1465            "Expected inlined-at fields to agree");
1466     SDDbgValue *SDV;
1467     if (Val.getNode()) {
1468       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1469       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1470       // we couldn't resolve it directly when examining the DbgValue intrinsic
1471       // in the first place we should not be more successful here). Unless we
1472       // have some test case that prove this to be correct we should avoid
1473       // calling EmitFuncArgumentDbgValue here.
1474       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1475                                     FuncArgumentDbgValueKind::Value, Val)) {
1476         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1477                           << printDDI(V, DDI) << "\n");
1478         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1479         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1480         // inserted after the definition of Val when emitting the instructions
1481         // after ISel. An alternative could be to teach
1482         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1483         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1484                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1485                    << ValSDNodeOrder << "\n");
1486         SDV = getDbgValue(Val, Variable, Expr, DL,
1487                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1488         DAG.AddDbgValue(SDV, false);
1489       } else
1490         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1491                           << printDDI(V, DDI)
1492                           << " in EmitFuncArgumentDbgValue\n");
1493     } else {
1494       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1495                         << "\n");
1496       auto Undef = UndefValue::get(V->getType());
1497       auto SDV =
1498           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1499       DAG.AddDbgValue(SDV, false);
1500     }
1501   }
1502   DDIV.clear();
1503 }
1504 
1505 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1506                                                     DanglingDebugInfo &DDI) {
1507   // TODO: For the variadic implementation, instead of only checking the fail
1508   // state of `handleDebugValue`, we need know specifically which values were
1509   // invalid, so that we attempt to salvage only those values when processing
1510   // a DIArgList.
1511   const Value *OrigV = V;
1512   DILocalVariable *Var = DDI.getVariable();
1513   DIExpression *Expr = DDI.getExpression();
1514   DebugLoc DL = DDI.getDebugLoc();
1515   unsigned SDOrder = DDI.getSDNodeOrder();
1516 
1517   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1518   // that DW_OP_stack_value is desired.
1519   bool StackValue = true;
1520 
1521   // Can this Value can be encoded without any further work?
1522   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1523     return;
1524 
1525   // Attempt to salvage back through as many instructions as possible. Bail if
1526   // a non-instruction is seen, such as a constant expression or global
1527   // variable. FIXME: Further work could recover those too.
1528   while (isa<Instruction>(V)) {
1529     const Instruction &VAsInst = *cast<const Instruction>(V);
1530     // Temporary "0", awaiting real implementation.
1531     SmallVector<uint64_t, 16> Ops;
1532     SmallVector<Value *, 4> AdditionalValues;
1533     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1534                              Expr->getNumLocationOperands(), Ops,
1535                              AdditionalValues);
1536     // If we cannot salvage any further, and haven't yet found a suitable debug
1537     // expression, bail out.
1538     if (!V)
1539       break;
1540 
1541     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1542     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1543     // here for variadic dbg_values, remove that condition.
1544     if (!AdditionalValues.empty())
1545       break;
1546 
1547     // New value and expr now represent this debuginfo.
1548     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1549 
1550     // Some kind of simplification occurred: check whether the operand of the
1551     // salvaged debug expression can be encoded in this DAG.
1552     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1553       LLVM_DEBUG(
1554           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1555                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1556       return;
1557     }
1558   }
1559 
1560   // This was the final opportunity to salvage this debug information, and it
1561   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1562   // any earlier variable location.
1563   assert(OrigV && "V shouldn't be null");
1564   auto *Undef = UndefValue::get(OrigV->getType());
1565   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1566   DAG.AddDbgValue(SDV, false);
1567   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1568                     << printDDI(OrigV, DDI) << "\n");
1569 }
1570 
1571 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1572                                                DIExpression *Expr,
1573                                                DebugLoc DbgLoc,
1574                                                unsigned Order) {
1575   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1576   DIExpression *NewExpr =
1577       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1578   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1579                    /*IsVariadic*/ false);
1580 }
1581 
1582 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1583                                            DILocalVariable *Var,
1584                                            DIExpression *Expr, DebugLoc DbgLoc,
1585                                            unsigned Order, bool IsVariadic) {
1586   if (Values.empty())
1587     return true;
1588 
1589   // Filter EntryValue locations out early.
1590   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1591     return true;
1592 
1593   SmallVector<SDDbgOperand> LocationOps;
1594   SmallVector<SDNode *> Dependencies;
1595   for (const Value *V : Values) {
1596     // Constant value.
1597     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1598         isa<ConstantPointerNull>(V)) {
1599       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1600       continue;
1601     }
1602 
1603     // Look through IntToPtr constants.
1604     if (auto *CE = dyn_cast<ConstantExpr>(V))
1605       if (CE->getOpcode() == Instruction::IntToPtr) {
1606         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1607         continue;
1608       }
1609 
1610     // If the Value is a frame index, we can create a FrameIndex debug value
1611     // without relying on the DAG at all.
1612     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1613       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1614       if (SI != FuncInfo.StaticAllocaMap.end()) {
1615         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1616         continue;
1617       }
1618     }
1619 
1620     // Do not use getValue() in here; we don't want to generate code at
1621     // this point if it hasn't been done yet.
1622     SDValue N = NodeMap[V];
1623     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1624       N = UnusedArgNodeMap[V];
1625     if (N.getNode()) {
1626       // Only emit func arg dbg value for non-variadic dbg.values for now.
1627       if (!IsVariadic &&
1628           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1629                                    FuncArgumentDbgValueKind::Value, N))
1630         return true;
1631       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1632         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1633         // describe stack slot locations.
1634         //
1635         // Consider "int x = 0; int *px = &x;". There are two kinds of
1636         // interesting debug values here after optimization:
1637         //
1638         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1639         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1640         //
1641         // Both describe the direct values of their associated variables.
1642         Dependencies.push_back(N.getNode());
1643         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1644         continue;
1645       }
1646       LocationOps.emplace_back(
1647           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1648       continue;
1649     }
1650 
1651     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1652     // Special rules apply for the first dbg.values of parameter variables in a
1653     // function. Identify them by the fact they reference Argument Values, that
1654     // they're parameters, and they are parameters of the current function. We
1655     // need to let them dangle until they get an SDNode.
1656     bool IsParamOfFunc =
1657         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1658     if (IsParamOfFunc)
1659       return false;
1660 
1661     // The value is not used in this block yet (or it would have an SDNode).
1662     // We still want the value to appear for the user if possible -- if it has
1663     // an associated VReg, we can refer to that instead.
1664     auto VMI = FuncInfo.ValueMap.find(V);
1665     if (VMI != FuncInfo.ValueMap.end()) {
1666       unsigned Reg = VMI->second;
1667       // If this is a PHI node, it may be split up into several MI PHI nodes
1668       // (in FunctionLoweringInfo::set).
1669       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1670                        V->getType(), std::nullopt);
1671       if (RFV.occupiesMultipleRegs()) {
1672         // FIXME: We could potentially support variadic dbg_values here.
1673         if (IsVariadic)
1674           return false;
1675         unsigned Offset = 0;
1676         unsigned BitsToDescribe = 0;
1677         if (auto VarSize = Var->getSizeInBits())
1678           BitsToDescribe = *VarSize;
1679         if (auto Fragment = Expr->getFragmentInfo())
1680           BitsToDescribe = Fragment->SizeInBits;
1681         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1682           // Bail out if all bits are described already.
1683           if (Offset >= BitsToDescribe)
1684             break;
1685           // TODO: handle scalable vectors.
1686           unsigned RegisterSize = RegAndSize.second;
1687           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1688                                       ? BitsToDescribe - Offset
1689                                       : RegisterSize;
1690           auto FragmentExpr = DIExpression::createFragmentExpression(
1691               Expr, Offset, FragmentSize);
1692           if (!FragmentExpr)
1693             continue;
1694           SDDbgValue *SDV = DAG.getVRegDbgValue(
1695               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1696           DAG.AddDbgValue(SDV, false);
1697           Offset += RegisterSize;
1698         }
1699         return true;
1700       }
1701       // We can use simple vreg locations for variadic dbg_values as well.
1702       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1703       continue;
1704     }
1705     // We failed to create a SDDbgOperand for V.
1706     return false;
1707   }
1708 
1709   // We have created a SDDbgOperand for each Value in Values.
1710   assert(!LocationOps.empty());
1711   SDDbgValue *SDV =
1712       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1713                           /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1714   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1715   return true;
1716 }
1717 
1718 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1719   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1720   for (auto &Pair : DanglingDebugInfoMap)
1721     for (auto &DDI : Pair.second)
1722       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1723   clearDanglingDebugInfo();
1724 }
1725 
1726 /// getCopyFromRegs - If there was virtual register allocated for the value V
1727 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1728 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1729   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1730   SDValue Result;
1731 
1732   if (It != FuncInfo.ValueMap.end()) {
1733     Register InReg = It->second;
1734 
1735     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1736                      DAG.getDataLayout(), InReg, Ty,
1737                      std::nullopt); // This is not an ABI copy.
1738     SDValue Chain = DAG.getEntryNode();
1739     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1740                                  V);
1741     resolveDanglingDebugInfo(V, Result);
1742   }
1743 
1744   return Result;
1745 }
1746 
1747 /// getValue - Return an SDValue for the given Value.
1748 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1749   // If we already have an SDValue for this value, use it. It's important
1750   // to do this first, so that we don't create a CopyFromReg if we already
1751   // have a regular SDValue.
1752   SDValue &N = NodeMap[V];
1753   if (N.getNode()) return N;
1754 
1755   // If there's a virtual register allocated and initialized for this
1756   // value, use it.
1757   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1758     return copyFromReg;
1759 
1760   // Otherwise create a new SDValue and remember it.
1761   SDValue Val = getValueImpl(V);
1762   NodeMap[V] = Val;
1763   resolveDanglingDebugInfo(V, Val);
1764   return Val;
1765 }
1766 
1767 /// getNonRegisterValue - Return an SDValue for the given Value, but
1768 /// don't look in FuncInfo.ValueMap for a virtual register.
1769 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1770   // If we already have an SDValue for this value, use it.
1771   SDValue &N = NodeMap[V];
1772   if (N.getNode()) {
1773     if (isIntOrFPConstant(N)) {
1774       // Remove the debug location from the node as the node is about to be used
1775       // in a location which may differ from the original debug location.  This
1776       // is relevant to Constant and ConstantFP nodes because they can appear
1777       // as constant expressions inside PHI nodes.
1778       N->setDebugLoc(DebugLoc());
1779     }
1780     return N;
1781   }
1782 
1783   // Otherwise create a new SDValue and remember it.
1784   SDValue Val = getValueImpl(V);
1785   NodeMap[V] = Val;
1786   resolveDanglingDebugInfo(V, Val);
1787   return Val;
1788 }
1789 
1790 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1791 /// Create an SDValue for the given value.
1792 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1793   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1794 
1795   if (const Constant *C = dyn_cast<Constant>(V)) {
1796     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1797 
1798     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1799       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1800 
1801     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1802       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1803 
1804     if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1805       return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1806                          getValue(CPA->getPointer()), getValue(CPA->getKey()),
1807                          getValue(CPA->getAddrDiscriminator()),
1808                          getValue(CPA->getDiscriminator()));
1809     }
1810 
1811     if (isa<ConstantPointerNull>(C)) {
1812       unsigned AS = V->getType()->getPointerAddressSpace();
1813       return DAG.getConstant(0, getCurSDLoc(),
1814                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1815     }
1816 
1817     if (match(C, m_VScale()))
1818       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1819 
1820     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1821       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1822 
1823     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1824       return DAG.getUNDEF(VT);
1825 
1826     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1827       visit(CE->getOpcode(), *CE);
1828       SDValue N1 = NodeMap[V];
1829       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1830       return N1;
1831     }
1832 
1833     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1834       SmallVector<SDValue, 4> Constants;
1835       for (const Use &U : C->operands()) {
1836         SDNode *Val = getValue(U).getNode();
1837         // If the operand is an empty aggregate, there are no values.
1838         if (!Val) continue;
1839         // Add each leaf value from the operand to the Constants list
1840         // to form a flattened list of all the values.
1841         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1842           Constants.push_back(SDValue(Val, i));
1843       }
1844 
1845       return DAG.getMergeValues(Constants, getCurSDLoc());
1846     }
1847 
1848     if (const ConstantDataSequential *CDS =
1849           dyn_cast<ConstantDataSequential>(C)) {
1850       SmallVector<SDValue, 4> Ops;
1851       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1852         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1853         // Add each leaf value from the operand to the Constants list
1854         // to form a flattened list of all the values.
1855         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1856           Ops.push_back(SDValue(Val, i));
1857       }
1858 
1859       if (isa<ArrayType>(CDS->getType()))
1860         return DAG.getMergeValues(Ops, getCurSDLoc());
1861       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1862     }
1863 
1864     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1865       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1866              "Unknown struct or array constant!");
1867 
1868       SmallVector<EVT, 4> ValueVTs;
1869       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1870       unsigned NumElts = ValueVTs.size();
1871       if (NumElts == 0)
1872         return SDValue(); // empty struct
1873       SmallVector<SDValue, 4> Constants(NumElts);
1874       for (unsigned i = 0; i != NumElts; ++i) {
1875         EVT EltVT = ValueVTs[i];
1876         if (isa<UndefValue>(C))
1877           Constants[i] = DAG.getUNDEF(EltVT);
1878         else if (EltVT.isFloatingPoint())
1879           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1880         else
1881           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1882       }
1883 
1884       return DAG.getMergeValues(Constants, getCurSDLoc());
1885     }
1886 
1887     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1888       return DAG.getBlockAddress(BA, VT);
1889 
1890     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1891       return getValue(Equiv->getGlobalValue());
1892 
1893     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1894       return getValue(NC->getGlobalValue());
1895 
1896     if (VT == MVT::aarch64svcount) {
1897       assert(C->isNullValue() && "Can only zero this target type!");
1898       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1899                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1900     }
1901 
1902     VectorType *VecTy = cast<VectorType>(V->getType());
1903 
1904     // Now that we know the number and type of the elements, get that number of
1905     // elements into the Ops array based on what kind of constant it is.
1906     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1907       SmallVector<SDValue, 16> Ops;
1908       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1909       for (unsigned i = 0; i != NumElements; ++i)
1910         Ops.push_back(getValue(CV->getOperand(i)));
1911 
1912       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1913     }
1914 
1915     if (isa<ConstantAggregateZero>(C)) {
1916       EVT EltVT =
1917           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1918 
1919       SDValue Op;
1920       if (EltVT.isFloatingPoint())
1921         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1922       else
1923         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1924 
1925       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1926     }
1927 
1928     llvm_unreachable("Unknown vector constant");
1929   }
1930 
1931   // If this is a static alloca, generate it as the frameindex instead of
1932   // computation.
1933   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1934     DenseMap<const AllocaInst*, int>::iterator SI =
1935       FuncInfo.StaticAllocaMap.find(AI);
1936     if (SI != FuncInfo.StaticAllocaMap.end())
1937       return DAG.getFrameIndex(
1938           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1939   }
1940 
1941   // If this is an instruction which fast-isel has deferred, select it now.
1942   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1943     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1944 
1945     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1946                      Inst->getType(), std::nullopt);
1947     SDValue Chain = DAG.getEntryNode();
1948     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1949   }
1950 
1951   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1952     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1953 
1954   if (const auto *BB = dyn_cast<BasicBlock>(V))
1955     return DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
1956 
1957   llvm_unreachable("Can't get register for value!");
1958 }
1959 
1960 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1961   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1962   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1963   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1964   bool IsSEH = isAsynchronousEHPersonality(Pers);
1965   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1966   if (!IsSEH)
1967     CatchPadMBB->setIsEHScopeEntry();
1968   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1969   if (IsMSVCCXX || IsCoreCLR)
1970     CatchPadMBB->setIsEHFuncletEntry();
1971 }
1972 
1973 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1974   // Update machine-CFG edge.
1975   MachineBasicBlock *TargetMBB = FuncInfo.MBBMap[I.getSuccessor()];
1976   FuncInfo.MBB->addSuccessor(TargetMBB);
1977   TargetMBB->setIsEHCatchretTarget(true);
1978   DAG.getMachineFunction().setHasEHCatchret(true);
1979 
1980   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1981   bool IsSEH = isAsynchronousEHPersonality(Pers);
1982   if (IsSEH) {
1983     // If this is not a fall-through branch or optimizations are switched off,
1984     // emit the branch.
1985     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1986         TM.getOptLevel() == CodeGenOptLevel::None)
1987       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1988                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1989     return;
1990   }
1991 
1992   // Figure out the funclet membership for the catchret's successor.
1993   // This will be used by the FuncletLayout pass to determine how to order the
1994   // BB's.
1995   // A 'catchret' returns to the outer scope's color.
1996   Value *ParentPad = I.getCatchSwitchParentPad();
1997   const BasicBlock *SuccessorColor;
1998   if (isa<ConstantTokenNone>(ParentPad))
1999     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2000   else
2001     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2002   assert(SuccessorColor && "No parent funclet for catchret!");
2003   MachineBasicBlock *SuccessorColorMBB = FuncInfo.MBBMap[SuccessorColor];
2004   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2005 
2006   // Create the terminator node.
2007   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2008                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
2009                             DAG.getBasicBlock(SuccessorColorMBB));
2010   DAG.setRoot(Ret);
2011 }
2012 
2013 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2014   // Don't emit any special code for the cleanuppad instruction. It just marks
2015   // the start of an EH scope/funclet.
2016   FuncInfo.MBB->setIsEHScopeEntry();
2017   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2018   if (Pers != EHPersonality::Wasm_CXX) {
2019     FuncInfo.MBB->setIsEHFuncletEntry();
2020     FuncInfo.MBB->setIsCleanupFuncletEntry();
2021   }
2022 }
2023 
2024 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2025 // not match, it is OK to add only the first unwind destination catchpad to the
2026 // successors, because there will be at least one invoke instruction within the
2027 // catch scope that points to the next unwind destination, if one exists, so
2028 // CFGSort cannot mess up with BB sorting order.
2029 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2030 // call within them, and catchpads only consisting of 'catch (...)' have a
2031 // '__cxa_end_catch' call within them, both of which generate invokes in case
2032 // the next unwind destination exists, i.e., the next unwind destination is not
2033 // the caller.)
2034 //
2035 // Having at most one EH pad successor is also simpler and helps later
2036 // transformations.
2037 //
2038 // For example,
2039 // current:
2040 //   invoke void @foo to ... unwind label %catch.dispatch
2041 // catch.dispatch:
2042 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2043 // catch.start:
2044 //   ...
2045 //   ... in this BB or some other child BB dominated by this BB there will be an
2046 //   invoke that points to 'next' BB as an unwind destination
2047 //
2048 // next: ; We don't need to add this to 'current' BB's successor
2049 //   ...
2050 static void findWasmUnwindDestinations(
2051     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2052     BranchProbability Prob,
2053     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2054         &UnwindDests) {
2055   while (EHPadBB) {
2056     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2057     if (isa<CleanupPadInst>(Pad)) {
2058       // Stop on cleanup pads.
2059       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2060       UnwindDests.back().first->setIsEHScopeEntry();
2061       break;
2062     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2063       // Add the catchpad handlers to the possible destinations. We don't
2064       // continue to the unwind destination of the catchswitch for wasm.
2065       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2066         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2067         UnwindDests.back().first->setIsEHScopeEntry();
2068       }
2069       break;
2070     } else {
2071       continue;
2072     }
2073   }
2074 }
2075 
2076 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2077 /// many places it could ultimately go. In the IR, we have a single unwind
2078 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2079 /// This function skips over imaginary basic blocks that hold catchswitch
2080 /// instructions, and finds all the "real" machine
2081 /// basic block destinations. As those destinations may not be successors of
2082 /// EHPadBB, here we also calculate the edge probability to those destinations.
2083 /// The passed-in Prob is the edge probability to EHPadBB.
2084 static void findUnwindDestinations(
2085     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2086     BranchProbability Prob,
2087     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2088         &UnwindDests) {
2089   EHPersonality Personality =
2090     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2091   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2092   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2093   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2094   bool IsSEH = isAsynchronousEHPersonality(Personality);
2095 
2096   if (IsWasmCXX) {
2097     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2098     assert(UnwindDests.size() <= 1 &&
2099            "There should be at most one unwind destination for wasm");
2100     return;
2101   }
2102 
2103   while (EHPadBB) {
2104     const Instruction *Pad = EHPadBB->getFirstNonPHI();
2105     BasicBlock *NewEHPadBB = nullptr;
2106     if (isa<LandingPadInst>(Pad)) {
2107       // Stop on landingpads. They are not funclets.
2108       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2109       break;
2110     } else if (isa<CleanupPadInst>(Pad)) {
2111       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2112       // personalities.
2113       UnwindDests.emplace_back(FuncInfo.MBBMap[EHPadBB], Prob);
2114       UnwindDests.back().first->setIsEHScopeEntry();
2115       UnwindDests.back().first->setIsEHFuncletEntry();
2116       break;
2117     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2118       // Add the catchpad handlers to the possible destinations.
2119       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2120         UnwindDests.emplace_back(FuncInfo.MBBMap[CatchPadBB], Prob);
2121         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2122         if (IsMSVCCXX || IsCoreCLR)
2123           UnwindDests.back().first->setIsEHFuncletEntry();
2124         if (!IsSEH)
2125           UnwindDests.back().first->setIsEHScopeEntry();
2126       }
2127       NewEHPadBB = CatchSwitch->getUnwindDest();
2128     } else {
2129       continue;
2130     }
2131 
2132     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2133     if (BPI && NewEHPadBB)
2134       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2135     EHPadBB = NewEHPadBB;
2136   }
2137 }
2138 
2139 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2140   // Update successor info.
2141   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2142   auto UnwindDest = I.getUnwindDest();
2143   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2144   BranchProbability UnwindDestProb =
2145       (BPI && UnwindDest)
2146           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2147           : BranchProbability::getZero();
2148   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2149   for (auto &UnwindDest : UnwindDests) {
2150     UnwindDest.first->setIsEHPad();
2151     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2152   }
2153   FuncInfo.MBB->normalizeSuccProbs();
2154 
2155   // Create the terminator node.
2156   SDValue Ret =
2157       DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other, getControlRoot());
2158   DAG.setRoot(Ret);
2159 }
2160 
2161 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2162   report_fatal_error("visitCatchSwitch not yet implemented!");
2163 }
2164 
2165 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2166   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2167   auto &DL = DAG.getDataLayout();
2168   SDValue Chain = getControlRoot();
2169   SmallVector<ISD::OutputArg, 8> Outs;
2170   SmallVector<SDValue, 8> OutVals;
2171 
2172   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2173   // lower
2174   //
2175   //   %val = call <ty> @llvm.experimental.deoptimize()
2176   //   ret <ty> %val
2177   //
2178   // differently.
2179   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2180     LowerDeoptimizingReturn();
2181     return;
2182   }
2183 
2184   if (!FuncInfo.CanLowerReturn) {
2185     unsigned DemoteReg = FuncInfo.DemoteRegister;
2186     const Function *F = I.getParent()->getParent();
2187 
2188     // Emit a store of the return value through the virtual register.
2189     // Leave Outs empty so that LowerReturn won't try to load return
2190     // registers the usual way.
2191     SmallVector<EVT, 1> PtrValueVTs;
2192     ComputeValueVTs(TLI, DL,
2193                     PointerType::get(F->getContext(),
2194                                      DAG.getDataLayout().getAllocaAddrSpace()),
2195                     PtrValueVTs);
2196 
2197     SDValue RetPtr =
2198         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVTs[0]);
2199     SDValue RetOp = getValue(I.getOperand(0));
2200 
2201     SmallVector<EVT, 4> ValueVTs, MemVTs;
2202     SmallVector<uint64_t, 4> Offsets;
2203     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2204                     &Offsets, 0);
2205     unsigned NumValues = ValueVTs.size();
2206 
2207     SmallVector<SDValue, 4> Chains(NumValues);
2208     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2209     for (unsigned i = 0; i != NumValues; ++i) {
2210       // An aggregate return value cannot wrap around the address space, so
2211       // offsets to its parts don't wrap either.
2212       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2213                                            TypeSize::getFixed(Offsets[i]));
2214 
2215       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2216       if (MemVTs[i] != ValueVTs[i])
2217         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2218       Chains[i] = DAG.getStore(
2219           Chain, getCurSDLoc(), Val,
2220           // FIXME: better loc info would be nice.
2221           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2222           commonAlignment(BaseAlign, Offsets[i]));
2223     }
2224 
2225     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2226                         MVT::Other, Chains);
2227   } else if (I.getNumOperands() != 0) {
2228     SmallVector<EVT, 4> ValueVTs;
2229     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2230     unsigned NumValues = ValueVTs.size();
2231     if (NumValues) {
2232       SDValue RetOp = getValue(I.getOperand(0));
2233 
2234       const Function *F = I.getParent()->getParent();
2235 
2236       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2237           I.getOperand(0)->getType(), F->getCallingConv(),
2238           /*IsVarArg*/ false, DL);
2239 
2240       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2241       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2242         ExtendKind = ISD::SIGN_EXTEND;
2243       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2244         ExtendKind = ISD::ZERO_EXTEND;
2245 
2246       LLVMContext &Context = F->getContext();
2247       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2248 
2249       for (unsigned j = 0; j != NumValues; ++j) {
2250         EVT VT = ValueVTs[j];
2251 
2252         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2253           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2254 
2255         CallingConv::ID CC = F->getCallingConv();
2256 
2257         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2258         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2259         SmallVector<SDValue, 4> Parts(NumParts);
2260         getCopyToParts(DAG, getCurSDLoc(),
2261                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2262                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2263 
2264         // 'inreg' on function refers to return value
2265         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2266         if (RetInReg)
2267           Flags.setInReg();
2268 
2269         if (I.getOperand(0)->getType()->isPointerTy()) {
2270           Flags.setPointer();
2271           Flags.setPointerAddrSpace(
2272               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2273         }
2274 
2275         if (NeedsRegBlock) {
2276           Flags.setInConsecutiveRegs();
2277           if (j == NumValues - 1)
2278             Flags.setInConsecutiveRegsLast();
2279         }
2280 
2281         // Propagate extension type if any
2282         if (ExtendKind == ISD::SIGN_EXTEND)
2283           Flags.setSExt();
2284         else if (ExtendKind == ISD::ZERO_EXTEND)
2285           Flags.setZExt();
2286 
2287         for (unsigned i = 0; i < NumParts; ++i) {
2288           Outs.push_back(ISD::OutputArg(Flags,
2289                                         Parts[i].getValueType().getSimpleVT(),
2290                                         VT, /*isfixed=*/true, 0, 0));
2291           OutVals.push_back(Parts[i]);
2292         }
2293       }
2294     }
2295   }
2296 
2297   // Push in swifterror virtual register as the last element of Outs. This makes
2298   // sure swifterror virtual register will be returned in the swifterror
2299   // physical register.
2300   const Function *F = I.getParent()->getParent();
2301   if (TLI.supportSwiftError() &&
2302       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2303     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2304     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2305     Flags.setSwiftError();
2306     Outs.push_back(ISD::OutputArg(
2307         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2308         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2309     // Create SDNode for the swifterror virtual register.
2310     OutVals.push_back(
2311         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2312                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2313                         EVT(TLI.getPointerTy(DL))));
2314   }
2315 
2316   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2317   CallingConv::ID CallConv =
2318     DAG.getMachineFunction().getFunction().getCallingConv();
2319   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2320       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2321 
2322   // Verify that the target's LowerReturn behaved as expected.
2323   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2324          "LowerReturn didn't return a valid chain!");
2325 
2326   // Update the DAG with the new chain value resulting from return lowering.
2327   DAG.setRoot(Chain);
2328 }
2329 
2330 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2331 /// created for it, emit nodes to copy the value into the virtual
2332 /// registers.
2333 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2334   // Skip empty types
2335   if (V->getType()->isEmptyTy())
2336     return;
2337 
2338   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2339   if (VMI != FuncInfo.ValueMap.end()) {
2340     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2341            "Unused value assigned virtual registers!");
2342     CopyValueToVirtualRegister(V, VMI->second);
2343   }
2344 }
2345 
2346 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2347 /// the current basic block, add it to ValueMap now so that we'll get a
2348 /// CopyTo/FromReg.
2349 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2350   // No need to export constants.
2351   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2352 
2353   // Already exported?
2354   if (FuncInfo.isExportedInst(V)) return;
2355 
2356   Register Reg = FuncInfo.InitializeRegForValue(V);
2357   CopyValueToVirtualRegister(V, Reg);
2358 }
2359 
2360 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2361                                                      const BasicBlock *FromBB) {
2362   // The operands of the setcc have to be in this block.  We don't know
2363   // how to export them from some other block.
2364   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2365     // Can export from current BB.
2366     if (VI->getParent() == FromBB)
2367       return true;
2368 
2369     // Is already exported, noop.
2370     return FuncInfo.isExportedInst(V);
2371   }
2372 
2373   // If this is an argument, we can export it if the BB is the entry block or
2374   // if it is already exported.
2375   if (isa<Argument>(V)) {
2376     if (FromBB->isEntryBlock())
2377       return true;
2378 
2379     // Otherwise, can only export this if it is already exported.
2380     return FuncInfo.isExportedInst(V);
2381   }
2382 
2383   // Otherwise, constants can always be exported.
2384   return true;
2385 }
2386 
2387 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2388 BranchProbability
2389 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2390                                         const MachineBasicBlock *Dst) const {
2391   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2392   const BasicBlock *SrcBB = Src->getBasicBlock();
2393   const BasicBlock *DstBB = Dst->getBasicBlock();
2394   if (!BPI) {
2395     // If BPI is not available, set the default probability as 1 / N, where N is
2396     // the number of successors.
2397     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2398     return BranchProbability(1, SuccSize);
2399   }
2400   return BPI->getEdgeProbability(SrcBB, DstBB);
2401 }
2402 
2403 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2404                                                MachineBasicBlock *Dst,
2405                                                BranchProbability Prob) {
2406   if (!FuncInfo.BPI)
2407     Src->addSuccessorWithoutProb(Dst);
2408   else {
2409     if (Prob.isUnknown())
2410       Prob = getEdgeProbability(Src, Dst);
2411     Src->addSuccessor(Dst, Prob);
2412   }
2413 }
2414 
2415 static bool InBlock(const Value *V, const BasicBlock *BB) {
2416   if (const Instruction *I = dyn_cast<Instruction>(V))
2417     return I->getParent() == BB;
2418   return true;
2419 }
2420 
2421 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2422 /// This function emits a branch and is used at the leaves of an OR or an
2423 /// AND operator tree.
2424 void
2425 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2426                                                   MachineBasicBlock *TBB,
2427                                                   MachineBasicBlock *FBB,
2428                                                   MachineBasicBlock *CurBB,
2429                                                   MachineBasicBlock *SwitchBB,
2430                                                   BranchProbability TProb,
2431                                                   BranchProbability FProb,
2432                                                   bool InvertCond) {
2433   const BasicBlock *BB = CurBB->getBasicBlock();
2434 
2435   // If the leaf of the tree is a comparison, merge the condition into
2436   // the caseblock.
2437   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2438     // The operands of the cmp have to be in this block.  We don't know
2439     // how to export them from some other block.  If this is the first block
2440     // of the sequence, no exporting is needed.
2441     if (CurBB == SwitchBB ||
2442         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2443          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2444       ISD::CondCode Condition;
2445       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2446         ICmpInst::Predicate Pred =
2447             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2448         Condition = getICmpCondCode(Pred);
2449       } else {
2450         const FCmpInst *FC = cast<FCmpInst>(Cond);
2451         FCmpInst::Predicate Pred =
2452             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2453         Condition = getFCmpCondCode(Pred);
2454         if (TM.Options.NoNaNsFPMath)
2455           Condition = getFCmpCodeWithoutNaN(Condition);
2456       }
2457 
2458       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2459                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2460       SL->SwitchCases.push_back(CB);
2461       return;
2462     }
2463   }
2464 
2465   // Create a CaseBlock record representing this branch.
2466   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2467   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2468                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2469   SL->SwitchCases.push_back(CB);
2470 }
2471 
2472 // Collect dependencies on V recursively. This is used for the cost analysis in
2473 // `shouldKeepJumpConditionsTogether`.
2474 static bool collectInstructionDeps(
2475     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2476     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2477     unsigned Depth = 0) {
2478   // Return false if we have an incomplete count.
2479   if (Depth >= SelectionDAG::MaxRecursionDepth)
2480     return false;
2481 
2482   auto *I = dyn_cast<Instruction>(V);
2483   if (I == nullptr)
2484     return true;
2485 
2486   if (Necessary != nullptr) {
2487     // This instruction is necessary for the other side of the condition so
2488     // don't count it.
2489     if (Necessary->contains(I))
2490       return true;
2491   }
2492 
2493   // Already added this dep.
2494   if (!Deps->try_emplace(I, false).second)
2495     return true;
2496 
2497   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2498     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2499                                 Depth + 1))
2500       return false;
2501   return true;
2502 }
2503 
2504 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2505     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2506     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2507     TargetLoweringBase::CondMergingParams Params) const {
2508   if (I.getNumSuccessors() != 2)
2509     return false;
2510 
2511   if (!I.isConditional())
2512     return false;
2513 
2514   if (Params.BaseCost < 0)
2515     return false;
2516 
2517   // Baseline cost.
2518   InstructionCost CostThresh = Params.BaseCost;
2519 
2520   BranchProbabilityInfo *BPI = nullptr;
2521   if (Params.LikelyBias || Params.UnlikelyBias)
2522     BPI = FuncInfo.BPI;
2523   if (BPI != nullptr) {
2524     // See if we are either likely to get an early out or compute both lhs/rhs
2525     // of the condition.
2526     BasicBlock *IfFalse = I.getSuccessor(0);
2527     BasicBlock *IfTrue = I.getSuccessor(1);
2528 
2529     std::optional<bool> Likely;
2530     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2531       Likely = true;
2532     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2533       Likely = false;
2534 
2535     if (Likely) {
2536       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2537         // Its likely we will have to compute both lhs and rhs of condition
2538         CostThresh += Params.LikelyBias;
2539       else {
2540         if (Params.UnlikelyBias < 0)
2541           return false;
2542         // Its likely we will get an early out.
2543         CostThresh -= Params.UnlikelyBias;
2544       }
2545     }
2546   }
2547 
2548   if (CostThresh <= 0)
2549     return false;
2550 
2551   // Collect "all" instructions that lhs condition is dependent on.
2552   // Use map for stable iteration (to avoid non-determanism of iteration of
2553   // SmallPtrSet). The `bool` value is just a dummy.
2554   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2555   collectInstructionDeps(&LhsDeps, Lhs);
2556   // Collect "all" instructions that rhs condition is dependent on AND are
2557   // dependencies of lhs. This gives us an estimate on which instructions we
2558   // stand to save by splitting the condition.
2559   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2560     return false;
2561   // Add the compare instruction itself unless its a dependency on the LHS.
2562   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2563     if (!LhsDeps.contains(RhsI))
2564       RhsDeps.try_emplace(RhsI, false);
2565 
2566   const auto &TLI = DAG.getTargetLoweringInfo();
2567   const auto &TTI =
2568       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2569 
2570   InstructionCost CostOfIncluding = 0;
2571   // See if this instruction will need to computed independently of whether RHS
2572   // is.
2573   Value *BrCond = I.getCondition();
2574   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2575     for (const auto *U : Ins->users()) {
2576       // If user is independent of RHS calculation we don't need to count it.
2577       if (auto *UIns = dyn_cast<Instruction>(U))
2578         if (UIns != BrCond && !RhsDeps.contains(UIns))
2579           return false;
2580     }
2581     return true;
2582   };
2583 
2584   // Prune instructions from RHS Deps that are dependencies of unrelated
2585   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2586   // arbitrary and just meant to cap the how much time we spend in the pruning
2587   // loop. Its highly unlikely to come into affect.
2588   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2589   // Stop after a certain point. No incorrectness from including too many
2590   // instructions.
2591   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2592     const Instruction *ToDrop = nullptr;
2593     for (const auto &InsPair : RhsDeps) {
2594       if (!ShouldCountInsn(InsPair.first)) {
2595         ToDrop = InsPair.first;
2596         break;
2597       }
2598     }
2599     if (ToDrop == nullptr)
2600       break;
2601     RhsDeps.erase(ToDrop);
2602   }
2603 
2604   for (const auto &InsPair : RhsDeps) {
2605     // Finally accumulate latency that we can only attribute to computing the
2606     // RHS condition. Use latency because we are essentially trying to calculate
2607     // the cost of the dependency chain.
2608     // Possible TODO: We could try to estimate ILP and make this more precise.
2609     CostOfIncluding +=
2610         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2611 
2612     if (CostOfIncluding > CostThresh)
2613       return false;
2614   }
2615   return true;
2616 }
2617 
2618 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2619                                                MachineBasicBlock *TBB,
2620                                                MachineBasicBlock *FBB,
2621                                                MachineBasicBlock *CurBB,
2622                                                MachineBasicBlock *SwitchBB,
2623                                                Instruction::BinaryOps Opc,
2624                                                BranchProbability TProb,
2625                                                BranchProbability FProb,
2626                                                bool InvertCond) {
2627   // Skip over not part of the tree and remember to invert op and operands at
2628   // next level.
2629   Value *NotCond;
2630   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2631       InBlock(NotCond, CurBB->getBasicBlock())) {
2632     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2633                          !InvertCond);
2634     return;
2635   }
2636 
2637   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2638   const Value *BOpOp0, *BOpOp1;
2639   // Compute the effective opcode for Cond, taking into account whether it needs
2640   // to be inverted, e.g.
2641   //   and (not (or A, B)), C
2642   // gets lowered as
2643   //   and (and (not A, not B), C)
2644   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2645   if (BOp) {
2646     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2647                ? Instruction::And
2648                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2649                       ? Instruction::Or
2650                       : (Instruction::BinaryOps)0);
2651     if (InvertCond) {
2652       if (BOpc == Instruction::And)
2653         BOpc = Instruction::Or;
2654       else if (BOpc == Instruction::Or)
2655         BOpc = Instruction::And;
2656     }
2657   }
2658 
2659   // If this node is not part of the or/and tree, emit it as a branch.
2660   // Note that all nodes in the tree should have same opcode.
2661   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2662   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2663       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2664       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2665     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2666                                  TProb, FProb, InvertCond);
2667     return;
2668   }
2669 
2670   //  Create TmpBB after CurBB.
2671   MachineFunction::iterator BBI(CurBB);
2672   MachineFunction &MF = DAG.getMachineFunction();
2673   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2674   CurBB->getParent()->insert(++BBI, TmpBB);
2675 
2676   if (Opc == Instruction::Or) {
2677     // Codegen X | Y as:
2678     // BB1:
2679     //   jmp_if_X TBB
2680     //   jmp TmpBB
2681     // TmpBB:
2682     //   jmp_if_Y TBB
2683     //   jmp FBB
2684     //
2685 
2686     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2687     // The requirement is that
2688     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2689     //     = TrueProb for original BB.
2690     // Assuming the original probabilities are A and B, one choice is to set
2691     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2692     // A/(1+B) and 2B/(1+B). This choice assumes that
2693     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2694     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2695     // TmpBB, but the math is more complicated.
2696 
2697     auto NewTrueProb = TProb / 2;
2698     auto NewFalseProb = TProb / 2 + FProb;
2699     // Emit the LHS condition.
2700     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2701                          NewFalseProb, InvertCond);
2702 
2703     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2704     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2705     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2706     // Emit the RHS condition into TmpBB.
2707     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2708                          Probs[1], InvertCond);
2709   } else {
2710     assert(Opc == Instruction::And && "Unknown merge op!");
2711     // Codegen X & Y as:
2712     // BB1:
2713     //   jmp_if_X TmpBB
2714     //   jmp FBB
2715     // TmpBB:
2716     //   jmp_if_Y TBB
2717     //   jmp FBB
2718     //
2719     //  This requires creation of TmpBB after CurBB.
2720 
2721     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2722     // The requirement is that
2723     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2724     //     = FalseProb for original BB.
2725     // Assuming the original probabilities are A and B, one choice is to set
2726     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2727     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2728     // TrueProb for BB1 * FalseProb for TmpBB.
2729 
2730     auto NewTrueProb = TProb + FProb / 2;
2731     auto NewFalseProb = FProb / 2;
2732     // Emit the LHS condition.
2733     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2734                          NewFalseProb, InvertCond);
2735 
2736     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2737     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2738     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2739     // Emit the RHS condition into TmpBB.
2740     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2741                          Probs[1], InvertCond);
2742   }
2743 }
2744 
2745 /// If the set of cases should be emitted as a series of branches, return true.
2746 /// If we should emit this as a bunch of and/or'd together conditions, return
2747 /// false.
2748 bool
2749 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2750   if (Cases.size() != 2) return true;
2751 
2752   // If this is two comparisons of the same values or'd or and'd together, they
2753   // will get folded into a single comparison, so don't emit two blocks.
2754   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2755        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2756       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2757        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2758     return false;
2759   }
2760 
2761   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2762   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2763   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2764       Cases[0].CC == Cases[1].CC &&
2765       isa<Constant>(Cases[0].CmpRHS) &&
2766       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2767     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2768       return false;
2769     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2770       return false;
2771   }
2772 
2773   return true;
2774 }
2775 
2776 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2777   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2778 
2779   // Update machine-CFG edges.
2780   MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
2781 
2782   if (I.isUnconditional()) {
2783     // Update machine-CFG edges.
2784     BrMBB->addSuccessor(Succ0MBB);
2785 
2786     // If this is not a fall-through branch or optimizations are switched off,
2787     // emit the branch.
2788     if (Succ0MBB != NextBlock(BrMBB) ||
2789         TM.getOptLevel() == CodeGenOptLevel::None) {
2790       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2791                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2792       setValue(&I, Br);
2793       DAG.setRoot(Br);
2794     }
2795 
2796     return;
2797   }
2798 
2799   // If this condition is one of the special cases we handle, do special stuff
2800   // now.
2801   const Value *CondVal = I.getCondition();
2802   MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
2803 
2804   // If this is a series of conditions that are or'd or and'd together, emit
2805   // this as a sequence of branches instead of setcc's with and/or operations.
2806   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2807   // unpredictable branches, and vector extracts because those jumps are likely
2808   // expensive for any target), this should improve performance.
2809   // For example, instead of something like:
2810   //     cmp A, B
2811   //     C = seteq
2812   //     cmp D, E
2813   //     F = setle
2814   //     or C, F
2815   //     jnz foo
2816   // Emit:
2817   //     cmp A, B
2818   //     je foo
2819   //     cmp D, E
2820   //     jle foo
2821   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2822   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2823       BOp->hasOneUse() && !I.hasMetadata(LLVMContext::MD_unpredictable)) {
2824     Value *Vec;
2825     const Value *BOp0, *BOp1;
2826     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2827     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2828       Opcode = Instruction::And;
2829     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2830       Opcode = Instruction::Or;
2831 
2832     if (Opcode &&
2833         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2834           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2835         !shouldKeepJumpConditionsTogether(
2836             FuncInfo, I, Opcode, BOp0, BOp1,
2837             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2838                 Opcode, BOp0, BOp1))) {
2839       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2840                            getEdgeProbability(BrMBB, Succ0MBB),
2841                            getEdgeProbability(BrMBB, Succ1MBB),
2842                            /*InvertCond=*/false);
2843       // If the compares in later blocks need to use values not currently
2844       // exported from this block, export them now.  This block should always
2845       // be the first entry.
2846       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2847 
2848       // Allow some cases to be rejected.
2849       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2850         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2851           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2852           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2853         }
2854 
2855         // Emit the branch for this block.
2856         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2857         SL->SwitchCases.erase(SL->SwitchCases.begin());
2858         return;
2859       }
2860 
2861       // Okay, we decided not to do this, remove any inserted MBB's and clear
2862       // SwitchCases.
2863       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2864         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2865 
2866       SL->SwitchCases.clear();
2867     }
2868   }
2869 
2870   // Create a CaseBlock record representing this branch.
2871   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2872                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc());
2873 
2874   // Use visitSwitchCase to actually insert the fast branch sequence for this
2875   // cond branch.
2876   visitSwitchCase(CB, BrMBB);
2877 }
2878 
2879 /// visitSwitchCase - Emits the necessary code to represent a single node in
2880 /// the binary search tree resulting from lowering a switch instruction.
2881 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2882                                           MachineBasicBlock *SwitchBB) {
2883   SDValue Cond;
2884   SDValue CondLHS = getValue(CB.CmpLHS);
2885   SDLoc dl = CB.DL;
2886 
2887   if (CB.CC == ISD::SETTRUE) {
2888     // Branch or fall through to TrueBB.
2889     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2890     SwitchBB->normalizeSuccProbs();
2891     if (CB.TrueBB != NextBlock(SwitchBB)) {
2892       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2893                               DAG.getBasicBlock(CB.TrueBB)));
2894     }
2895     return;
2896   }
2897 
2898   auto &TLI = DAG.getTargetLoweringInfo();
2899   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2900 
2901   // Build the setcc now.
2902   if (!CB.CmpMHS) {
2903     // Fold "(X == true)" to X and "(X == false)" to !X to
2904     // handle common cases produced by branch lowering.
2905     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2906         CB.CC == ISD::SETEQ)
2907       Cond = CondLHS;
2908     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2909              CB.CC == ISD::SETEQ) {
2910       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2911       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2912     } else {
2913       SDValue CondRHS = getValue(CB.CmpRHS);
2914 
2915       // If a pointer's DAG type is larger than its memory type then the DAG
2916       // values are zero-extended. This breaks signed comparisons so truncate
2917       // back to the underlying type before doing the compare.
2918       if (CondLHS.getValueType() != MemVT) {
2919         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2920         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2921       }
2922       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2923     }
2924   } else {
2925     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2926 
2927     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2928     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2929 
2930     SDValue CmpOp = getValue(CB.CmpMHS);
2931     EVT VT = CmpOp.getValueType();
2932 
2933     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2934       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2935                           ISD::SETLE);
2936     } else {
2937       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2938                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2939       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2940                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2941     }
2942   }
2943 
2944   // Update successor info
2945   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2946   // TrueBB and FalseBB are always different unless the incoming IR is
2947   // degenerate. This only happens when running llc on weird IR.
2948   if (CB.TrueBB != CB.FalseBB)
2949     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2950   SwitchBB->normalizeSuccProbs();
2951 
2952   // If the lhs block is the next block, invert the condition so that we can
2953   // fall through to the lhs instead of the rhs block.
2954   if (CB.TrueBB == NextBlock(SwitchBB)) {
2955     std::swap(CB.TrueBB, CB.FalseBB);
2956     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2957     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2958   }
2959 
2960   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
2961                                MVT::Other, getControlRoot(), Cond,
2962                                DAG.getBasicBlock(CB.TrueBB));
2963 
2964   setValue(CurInst, BrCond);
2965 
2966   // Insert the false branch. Do this even if it's a fall through branch,
2967   // this makes it easier to do DAG optimizations which require inverting
2968   // the branch condition.
2969   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2970                        DAG.getBasicBlock(CB.FalseBB));
2971 
2972   DAG.setRoot(BrCond);
2973 }
2974 
2975 /// visitJumpTable - Emit JumpTable node in the current MBB
2976 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2977   // Emit the code for the jump table
2978   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2979   assert(JT.Reg != -1U && "Should lower JT Header first!");
2980   EVT PTy = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
2981   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2982   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2983   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2984                                     Index.getValue(1), Table, Index);
2985   DAG.setRoot(BrJumpTable);
2986 }
2987 
2988 /// visitJumpTableHeader - This function emits necessary code to produce index
2989 /// in the JumpTable from switch case.
2990 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2991                                                JumpTableHeader &JTH,
2992                                                MachineBasicBlock *SwitchBB) {
2993   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2994   const SDLoc &dl = *JT.SL;
2995 
2996   // Subtract the lowest switch case value from the value being switched on.
2997   SDValue SwitchOp = getValue(JTH.SValue);
2998   EVT VT = SwitchOp.getValueType();
2999   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3000                             DAG.getConstant(JTH.First, dl, VT));
3001 
3002   // The SDNode we just created, which holds the value being switched on minus
3003   // the smallest case value, needs to be copied to a virtual register so it
3004   // can be used as an index into the jump table in a subsequent basic block.
3005   // This value may be smaller or larger than the target's pointer type, and
3006   // therefore require extension or truncating.
3007   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3008   SwitchOp = DAG.getZExtOrTrunc(Sub, dl, TLI.getPointerTy(DAG.getDataLayout()));
3009 
3010   unsigned JumpTableReg =
3011       FuncInfo.CreateReg(TLI.getPointerTy(DAG.getDataLayout()));
3012   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl,
3013                                     JumpTableReg, SwitchOp);
3014   JT.Reg = JumpTableReg;
3015 
3016   if (!JTH.FallthroughUnreachable) {
3017     // Emit the range check for the jump table, and branch to the default block
3018     // for the switch statement if the value being switched on exceeds the
3019     // largest case in the switch.
3020     SDValue CMP = DAG.getSetCC(
3021         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3022                                    Sub.getValueType()),
3023         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3024 
3025     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3026                                  MVT::Other, CopyTo, CMP,
3027                                  DAG.getBasicBlock(JT.Default));
3028 
3029     // Avoid emitting unnecessary branches to the next block.
3030     if (JT.MBB != NextBlock(SwitchBB))
3031       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3032                            DAG.getBasicBlock(JT.MBB));
3033 
3034     DAG.setRoot(BrCond);
3035   } else {
3036     // Avoid emitting unnecessary branches to the next block.
3037     if (JT.MBB != NextBlock(SwitchBB))
3038       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3039                               DAG.getBasicBlock(JT.MBB)));
3040     else
3041       DAG.setRoot(CopyTo);
3042   }
3043 }
3044 
3045 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3046 /// variable if there exists one.
3047 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3048                                  SDValue &Chain) {
3049   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3050   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3051   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3052   MachineFunction &MF = DAG.getMachineFunction();
3053   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3054   MachineSDNode *Node =
3055       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3056   if (Global) {
3057     MachinePointerInfo MPInfo(Global);
3058     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3059                  MachineMemOperand::MODereferenceable;
3060     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3061         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3062         DAG.getEVTAlign(PtrTy));
3063     DAG.setNodeMemRefs(Node, {MemRef});
3064   }
3065   if (PtrTy != PtrMemTy)
3066     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3067   return SDValue(Node, 0);
3068 }
3069 
3070 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3071 /// tail spliced into a stack protector check success bb.
3072 ///
3073 /// For a high level explanation of how this fits into the stack protector
3074 /// generation see the comment on the declaration of class
3075 /// StackProtectorDescriptor.
3076 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3077                                                   MachineBasicBlock *ParentBB) {
3078 
3079   // First create the loads to the guard/stack slot for the comparison.
3080   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3081   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3082   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3083 
3084   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3085   int FI = MFI.getStackProtectorIndex();
3086 
3087   SDValue Guard;
3088   SDLoc dl = getCurSDLoc();
3089   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3090   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3091   Align Align =
3092       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3093 
3094   // Generate code to load the content of the guard slot.
3095   SDValue GuardVal = DAG.getLoad(
3096       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3097       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3098       MachineMemOperand::MOVolatile);
3099 
3100   if (TLI.useStackGuardXorFP())
3101     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3102 
3103   // Retrieve guard check function, nullptr if instrumentation is inlined.
3104   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3105     // The target provides a guard check function to validate the guard value.
3106     // Generate a call to that function with the content of the guard slot as
3107     // argument.
3108     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3109     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3110 
3111     TargetLowering::ArgListTy Args;
3112     TargetLowering::ArgListEntry Entry;
3113     Entry.Node = GuardVal;
3114     Entry.Ty = FnTy->getParamType(0);
3115     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3116       Entry.IsInReg = true;
3117     Args.push_back(Entry);
3118 
3119     TargetLowering::CallLoweringInfo CLI(DAG);
3120     CLI.setDebugLoc(getCurSDLoc())
3121         .setChain(DAG.getEntryNode())
3122         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3123                    getValue(GuardCheckFn), std::move(Args));
3124 
3125     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3126     DAG.setRoot(Result.second);
3127     return;
3128   }
3129 
3130   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3131   // Otherwise, emit a volatile load to retrieve the stack guard value.
3132   SDValue Chain = DAG.getEntryNode();
3133   if (TLI.useLoadStackGuardNode()) {
3134     Guard = getLoadStackGuard(DAG, dl, Chain);
3135   } else {
3136     const Value *IRGuard = TLI.getSDagStackGuard(M);
3137     SDValue GuardPtr = getValue(IRGuard);
3138 
3139     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3140                         MachinePointerInfo(IRGuard, 0), Align,
3141                         MachineMemOperand::MOVolatile);
3142   }
3143 
3144   // Perform the comparison via a getsetcc.
3145   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3146                                                         *DAG.getContext(),
3147                                                         Guard.getValueType()),
3148                              Guard, GuardVal, ISD::SETNE);
3149 
3150   // If the guard/stackslot do not equal, branch to failure MBB.
3151   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3152                                MVT::Other, GuardVal.getOperand(0),
3153                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3154   // Otherwise branch to success MBB.
3155   SDValue Br = DAG.getNode(ISD::BR, dl,
3156                            MVT::Other, BrCond,
3157                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3158 
3159   DAG.setRoot(Br);
3160 }
3161 
3162 /// Codegen the failure basic block for a stack protector check.
3163 ///
3164 /// A failure stack protector machine basic block consists simply of a call to
3165 /// __stack_chk_fail().
3166 ///
3167 /// For a high level explanation of how this fits into the stack protector
3168 /// generation see the comment on the declaration of class
3169 /// StackProtectorDescriptor.
3170 void
3171 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3172   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3173   TargetLowering::MakeLibCallOptions CallOptions;
3174   CallOptions.setDiscardResult(true);
3175   SDValue Chain =
3176       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3177                       std::nullopt, CallOptions, getCurSDLoc())
3178           .second;
3179   // On PS4/PS5, the "return address" must still be within the calling
3180   // function, even if it's at the very end, so emit an explicit TRAP here.
3181   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3182   if (TM.getTargetTriple().isPS())
3183     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3184   // WebAssembly needs an unreachable instruction after a non-returning call,
3185   // because the function return type can be different from __stack_chk_fail's
3186   // return type (void).
3187   if (TM.getTargetTriple().isWasm())
3188     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3189 
3190   DAG.setRoot(Chain);
3191 }
3192 
3193 /// visitBitTestHeader - This function emits necessary code to produce value
3194 /// suitable for "bit tests"
3195 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3196                                              MachineBasicBlock *SwitchBB) {
3197   SDLoc dl = getCurSDLoc();
3198 
3199   // Subtract the minimum value.
3200   SDValue SwitchOp = getValue(B.SValue);
3201   EVT VT = SwitchOp.getValueType();
3202   SDValue RangeSub =
3203       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3204 
3205   // Determine the type of the test operands.
3206   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3207   bool UsePtrType = false;
3208   if (!TLI.isTypeLegal(VT)) {
3209     UsePtrType = true;
3210   } else {
3211     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3212       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3213         // Switch table case range are encoded into series of masks.
3214         // Just use pointer type, it's guaranteed to fit.
3215         UsePtrType = true;
3216         break;
3217       }
3218   }
3219   SDValue Sub = RangeSub;
3220   if (UsePtrType) {
3221     VT = TLI.getPointerTy(DAG.getDataLayout());
3222     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3223   }
3224 
3225   B.RegVT = VT.getSimpleVT();
3226   B.Reg = FuncInfo.CreateReg(B.RegVT);
3227   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3228 
3229   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3230 
3231   if (!B.FallthroughUnreachable)
3232     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3233   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3234   SwitchBB->normalizeSuccProbs();
3235 
3236   SDValue Root = CopyTo;
3237   if (!B.FallthroughUnreachable) {
3238     // Conditional branch to the default block.
3239     SDValue RangeCmp = DAG.getSetCC(dl,
3240         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3241                                RangeSub.getValueType()),
3242         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3243         ISD::SETUGT);
3244 
3245     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3246                        DAG.getBasicBlock(B.Default));
3247   }
3248 
3249   // Avoid emitting unnecessary branches to the next block.
3250   if (MBB != NextBlock(SwitchBB))
3251     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3252 
3253   DAG.setRoot(Root);
3254 }
3255 
3256 /// visitBitTestCase - this function produces one "bit test"
3257 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3258                                            MachineBasicBlock* NextMBB,
3259                                            BranchProbability BranchProbToNext,
3260                                            unsigned Reg,
3261                                            BitTestCase &B,
3262                                            MachineBasicBlock *SwitchBB) {
3263   SDLoc dl = getCurSDLoc();
3264   MVT VT = BB.RegVT;
3265   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3266   SDValue Cmp;
3267   unsigned PopCount = llvm::popcount(B.Mask);
3268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3269   if (PopCount == 1) {
3270     // Testing for a single bit; just compare the shift count with what it
3271     // would need to be to shift a 1 bit in that position.
3272     Cmp = DAG.getSetCC(
3273         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3274         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3275         ISD::SETEQ);
3276   } else if (PopCount == BB.Range) {
3277     // There is only one zero bit in the range, test for it directly.
3278     Cmp = DAG.getSetCC(
3279         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3280         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3281   } else {
3282     // Make desired shift
3283     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3284                                     DAG.getConstant(1, dl, VT), ShiftOp);
3285 
3286     // Emit bit tests and jumps
3287     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3288                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3289     Cmp = DAG.getSetCC(
3290         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3291         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3292   }
3293 
3294   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3295   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3296   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3297   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3298   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3299   // one as they are relative probabilities (and thus work more like weights),
3300   // and hence we need to normalize them to let the sum of them become one.
3301   SwitchBB->normalizeSuccProbs();
3302 
3303   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3304                               MVT::Other, getControlRoot(),
3305                               Cmp, DAG.getBasicBlock(B.TargetBB));
3306 
3307   // Avoid emitting unnecessary branches to the next block.
3308   if (NextMBB != NextBlock(SwitchBB))
3309     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3310                         DAG.getBasicBlock(NextMBB));
3311 
3312   DAG.setRoot(BrAnd);
3313 }
3314 
3315 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3316   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3317 
3318   // Retrieve successors. Look through artificial IR level blocks like
3319   // catchswitch for successors.
3320   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
3321   const BasicBlock *EHPadBB = I.getSuccessor(1);
3322   MachineBasicBlock *EHPadMBB = FuncInfo.MBBMap[EHPadBB];
3323 
3324   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3325   // have to do anything here to lower funclet bundles.
3326   assert(!I.hasOperandBundlesOtherThan(
3327              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3328               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3329               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3330               LLVMContext::OB_clang_arc_attachedcall}) &&
3331          "Cannot lower invokes with arbitrary operand bundles yet!");
3332 
3333   const Value *Callee(I.getCalledOperand());
3334   const Function *Fn = dyn_cast<Function>(Callee);
3335   if (isa<InlineAsm>(Callee))
3336     visitInlineAsm(I, EHPadBB);
3337   else if (Fn && Fn->isIntrinsic()) {
3338     switch (Fn->getIntrinsicID()) {
3339     default:
3340       llvm_unreachable("Cannot invoke this intrinsic");
3341     case Intrinsic::donothing:
3342       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3343     case Intrinsic::seh_try_begin:
3344     case Intrinsic::seh_scope_begin:
3345     case Intrinsic::seh_try_end:
3346     case Intrinsic::seh_scope_end:
3347       if (EHPadMBB)
3348           // a block referenced by EH table
3349           // so dtor-funclet not removed by opts
3350           EHPadMBB->setMachineBlockAddressTaken();
3351       break;
3352     case Intrinsic::experimental_patchpoint_void:
3353     case Intrinsic::experimental_patchpoint:
3354       visitPatchpoint(I, EHPadBB);
3355       break;
3356     case Intrinsic::experimental_gc_statepoint:
3357       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3358       break;
3359     case Intrinsic::wasm_rethrow: {
3360       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3361       // special because it can be invoked, so we manually lower it to a DAG
3362       // node here.
3363       SmallVector<SDValue, 8> Ops;
3364       Ops.push_back(getControlRoot()); // inchain for the terminator node
3365       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3366       Ops.push_back(
3367           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3368                                 TLI.getPointerTy(DAG.getDataLayout())));
3369       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3370       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3371       break;
3372     }
3373     }
3374   } else if (I.hasDeoptState()) {
3375     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3376     // Eventually we will support lowering the @llvm.experimental.deoptimize
3377     // intrinsic, and right now there are no plans to support other intrinsics
3378     // with deopt state.
3379     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3380   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3381     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3382   } else {
3383     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3384   }
3385 
3386   // If the value of the invoke is used outside of its defining block, make it
3387   // available as a virtual register.
3388   // We already took care of the exported value for the statepoint instruction
3389   // during call to the LowerStatepoint.
3390   if (!isa<GCStatepointInst>(I)) {
3391     CopyToExportRegsIfNeeded(&I);
3392   }
3393 
3394   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3395   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3396   BranchProbability EHPadBBProb =
3397       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3398           : BranchProbability::getZero();
3399   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3400 
3401   // Update successor info.
3402   addSuccessorWithProb(InvokeMBB, Return);
3403   for (auto &UnwindDest : UnwindDests) {
3404     UnwindDest.first->setIsEHPad();
3405     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3406   }
3407   InvokeMBB->normalizeSuccProbs();
3408 
3409   // Drop into normal successor.
3410   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3411                           DAG.getBasicBlock(Return)));
3412 }
3413 
3414 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3415   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3416 
3417   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3418   // have to do anything here to lower funclet bundles.
3419   assert(!I.hasOperandBundlesOtherThan(
3420              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3421          "Cannot lower callbrs with arbitrary operand bundles yet!");
3422 
3423   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3424   visitInlineAsm(I);
3425   CopyToExportRegsIfNeeded(&I);
3426 
3427   // Retrieve successors.
3428   SmallPtrSet<BasicBlock *, 8> Dests;
3429   Dests.insert(I.getDefaultDest());
3430   MachineBasicBlock *Return = FuncInfo.MBBMap[I.getDefaultDest()];
3431 
3432   // Update successor info.
3433   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3434   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3435     BasicBlock *Dest = I.getIndirectDest(i);
3436     MachineBasicBlock *Target = FuncInfo.MBBMap[Dest];
3437     Target->setIsInlineAsmBrIndirectTarget();
3438     Target->setMachineBlockAddressTaken();
3439     Target->setLabelMustBeEmitted();
3440     // Don't add duplicate machine successors.
3441     if (Dests.insert(Dest).second)
3442       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3443   }
3444   CallBrMBB->normalizeSuccProbs();
3445 
3446   // Drop into default successor.
3447   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3448                           MVT::Other, getControlRoot(),
3449                           DAG.getBasicBlock(Return)));
3450 }
3451 
3452 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3453   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3454 }
3455 
3456 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3457   assert(FuncInfo.MBB->isEHPad() &&
3458          "Call to landingpad not in landing pad!");
3459 
3460   // If there aren't registers to copy the values into (e.g., during SjLj
3461   // exceptions), then don't bother to create these DAG nodes.
3462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3463   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3464   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3465       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3466     return;
3467 
3468   // If landingpad's return type is token type, we don't create DAG nodes
3469   // for its exception pointer and selector value. The extraction of exception
3470   // pointer or selector value from token type landingpads is not currently
3471   // supported.
3472   if (LP.getType()->isTokenTy())
3473     return;
3474 
3475   SmallVector<EVT, 2> ValueVTs;
3476   SDLoc dl = getCurSDLoc();
3477   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3478   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3479 
3480   // Get the two live-in registers as SDValues. The physregs have already been
3481   // copied into virtual registers.
3482   SDValue Ops[2];
3483   if (FuncInfo.ExceptionPointerVirtReg) {
3484     Ops[0] = DAG.getZExtOrTrunc(
3485         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3486                            FuncInfo.ExceptionPointerVirtReg,
3487                            TLI.getPointerTy(DAG.getDataLayout())),
3488         dl, ValueVTs[0]);
3489   } else {
3490     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3491   }
3492   Ops[1] = DAG.getZExtOrTrunc(
3493       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3494                          FuncInfo.ExceptionSelectorVirtReg,
3495                          TLI.getPointerTy(DAG.getDataLayout())),
3496       dl, ValueVTs[1]);
3497 
3498   // Merge into one.
3499   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3500                             DAG.getVTList(ValueVTs), Ops);
3501   setValue(&LP, Res);
3502 }
3503 
3504 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3505                                            MachineBasicBlock *Last) {
3506   // Update JTCases.
3507   for (JumpTableBlock &JTB : SL->JTCases)
3508     if (JTB.first.HeaderBB == First)
3509       JTB.first.HeaderBB = Last;
3510 
3511   // Update BitTestCases.
3512   for (BitTestBlock &BTB : SL->BitTestCases)
3513     if (BTB.Parent == First)
3514       BTB.Parent = Last;
3515 }
3516 
3517 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3518   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3519 
3520   // Update machine-CFG edges with unique successors.
3521   SmallSet<BasicBlock*, 32> Done;
3522   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3523     BasicBlock *BB = I.getSuccessor(i);
3524     bool Inserted = Done.insert(BB).second;
3525     if (!Inserted)
3526         continue;
3527 
3528     MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
3529     addSuccessorWithProb(IndirectBrMBB, Succ);
3530   }
3531   IndirectBrMBB->normalizeSuccProbs();
3532 
3533   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3534                           MVT::Other, getControlRoot(),
3535                           getValue(I.getAddress())));
3536 }
3537 
3538 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3539   if (!DAG.getTarget().Options.TrapUnreachable)
3540     return;
3541 
3542   // We may be able to ignore unreachable behind a noreturn call.
3543   if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
3544       Call && Call->doesNotReturn()) {
3545     if (DAG.getTarget().Options.NoTrapAfterNoreturn)
3546       return;
3547     // Do not emit an additional trap instruction.
3548     if (Call->isNonContinuableTrap())
3549       return;
3550   }
3551 
3552   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3553 }
3554 
3555 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3556   SDNodeFlags Flags;
3557   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3558     Flags.copyFMF(*FPOp);
3559 
3560   SDValue Op = getValue(I.getOperand(0));
3561   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3562                                     Op, Flags);
3563   setValue(&I, UnNodeValue);
3564 }
3565 
3566 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3567   SDNodeFlags Flags;
3568   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3569     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3570     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3571   }
3572   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3573     Flags.setExact(ExactOp->isExact());
3574   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3575     Flags.setDisjoint(DisjointOp->isDisjoint());
3576   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3577     Flags.copyFMF(*FPOp);
3578 
3579   SDValue Op1 = getValue(I.getOperand(0));
3580   SDValue Op2 = getValue(I.getOperand(1));
3581   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3582                                      Op1, Op2, Flags);
3583   setValue(&I, BinNodeValue);
3584 }
3585 
3586 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3587   SDValue Op1 = getValue(I.getOperand(0));
3588   SDValue Op2 = getValue(I.getOperand(1));
3589 
3590   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3591       Op1.getValueType(), DAG.getDataLayout());
3592 
3593   // Coerce the shift amount to the right type if we can. This exposes the
3594   // truncate or zext to optimization early.
3595   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3596     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3597            "Unexpected shift type");
3598     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3599   }
3600 
3601   bool nuw = false;
3602   bool nsw = false;
3603   bool exact = false;
3604 
3605   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3606 
3607     if (const OverflowingBinaryOperator *OFBinOp =
3608             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3609       nuw = OFBinOp->hasNoUnsignedWrap();
3610       nsw = OFBinOp->hasNoSignedWrap();
3611     }
3612     if (const PossiblyExactOperator *ExactOp =
3613             dyn_cast<const PossiblyExactOperator>(&I))
3614       exact = ExactOp->isExact();
3615   }
3616   SDNodeFlags Flags;
3617   Flags.setExact(exact);
3618   Flags.setNoSignedWrap(nsw);
3619   Flags.setNoUnsignedWrap(nuw);
3620   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3621                             Flags);
3622   setValue(&I, Res);
3623 }
3624 
3625 void SelectionDAGBuilder::visitSDiv(const User &I) {
3626   SDValue Op1 = getValue(I.getOperand(0));
3627   SDValue Op2 = getValue(I.getOperand(1));
3628 
3629   SDNodeFlags Flags;
3630   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3631                  cast<PossiblyExactOperator>(&I)->isExact());
3632   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3633                            Op2, Flags));
3634 }
3635 
3636 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3637   ICmpInst::Predicate predicate = I.getPredicate();
3638   SDValue Op1 = getValue(I.getOperand(0));
3639   SDValue Op2 = getValue(I.getOperand(1));
3640   ISD::CondCode Opcode = getICmpCondCode(predicate);
3641 
3642   auto &TLI = DAG.getTargetLoweringInfo();
3643   EVT MemVT =
3644       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3645 
3646   // If a pointer's DAG type is larger than its memory type then the DAG values
3647   // are zero-extended. This breaks signed comparisons so truncate back to the
3648   // underlying type before doing the compare.
3649   if (Op1.getValueType() != MemVT) {
3650     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3651     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3652   }
3653 
3654   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3655                                                         I.getType());
3656   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3657 }
3658 
3659 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3660   FCmpInst::Predicate predicate = I.getPredicate();
3661   SDValue Op1 = getValue(I.getOperand(0));
3662   SDValue Op2 = getValue(I.getOperand(1));
3663 
3664   ISD::CondCode Condition = getFCmpCondCode(predicate);
3665   auto *FPMO = cast<FPMathOperator>(&I);
3666   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3667     Condition = getFCmpCodeWithoutNaN(Condition);
3668 
3669   SDNodeFlags Flags;
3670   Flags.copyFMF(*FPMO);
3671   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3672 
3673   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3674                                                         I.getType());
3675   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3676 }
3677 
3678 // Check if the condition of the select has one use or two users that are both
3679 // selects with the same condition.
3680 static bool hasOnlySelectUsers(const Value *Cond) {
3681   return llvm::all_of(Cond->users(), [](const Value *V) {
3682     return isa<SelectInst>(V);
3683   });
3684 }
3685 
3686 void SelectionDAGBuilder::visitSelect(const User &I) {
3687   SmallVector<EVT, 4> ValueVTs;
3688   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3689                   ValueVTs);
3690   unsigned NumValues = ValueVTs.size();
3691   if (NumValues == 0) return;
3692 
3693   SmallVector<SDValue, 4> Values(NumValues);
3694   SDValue Cond     = getValue(I.getOperand(0));
3695   SDValue LHSVal   = getValue(I.getOperand(1));
3696   SDValue RHSVal   = getValue(I.getOperand(2));
3697   SmallVector<SDValue, 1> BaseOps(1, Cond);
3698   ISD::NodeType OpCode =
3699       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3700 
3701   bool IsUnaryAbs = false;
3702   bool Negate = false;
3703 
3704   SDNodeFlags Flags;
3705   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3706     Flags.copyFMF(*FPOp);
3707 
3708   Flags.setUnpredictable(
3709       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3710 
3711   // Min/max matching is only viable if all output VTs are the same.
3712   if (all_equal(ValueVTs)) {
3713     EVT VT = ValueVTs[0];
3714     LLVMContext &Ctx = *DAG.getContext();
3715     auto &TLI = DAG.getTargetLoweringInfo();
3716 
3717     // We care about the legality of the operation after it has been type
3718     // legalized.
3719     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3720       VT = TLI.getTypeToTransformTo(Ctx, VT);
3721 
3722     // If the vselect is legal, assume we want to leave this as a vector setcc +
3723     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3724     // min/max is legal on the scalar type.
3725     bool UseScalarMinMax = VT.isVector() &&
3726       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3727 
3728     // ValueTracking's select pattern matching does not account for -0.0,
3729     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3730     // -0.0 is less than +0.0.
3731     const Value *LHS, *RHS;
3732     auto SPR = matchSelectPattern(&I, LHS, RHS);
3733     ISD::NodeType Opc = ISD::DELETED_NODE;
3734     switch (SPR.Flavor) {
3735     case SPF_UMAX:    Opc = ISD::UMAX; break;
3736     case SPF_UMIN:    Opc = ISD::UMIN; break;
3737     case SPF_SMAX:    Opc = ISD::SMAX; break;
3738     case SPF_SMIN:    Opc = ISD::SMIN; break;
3739     case SPF_FMINNUM:
3740       switch (SPR.NaNBehavior) {
3741       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3742       case SPNB_RETURNS_NAN: break;
3743       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3744       case SPNB_RETURNS_ANY:
3745         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3746             (UseScalarMinMax &&
3747              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3748           Opc = ISD::FMINNUM;
3749         break;
3750       }
3751       break;
3752     case SPF_FMAXNUM:
3753       switch (SPR.NaNBehavior) {
3754       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3755       case SPNB_RETURNS_NAN: break;
3756       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3757       case SPNB_RETURNS_ANY:
3758         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3759             (UseScalarMinMax &&
3760              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3761           Opc = ISD::FMAXNUM;
3762         break;
3763       }
3764       break;
3765     case SPF_NABS:
3766       Negate = true;
3767       [[fallthrough]];
3768     case SPF_ABS:
3769       IsUnaryAbs = true;
3770       Opc = ISD::ABS;
3771       break;
3772     default: break;
3773     }
3774 
3775     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3776         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3777          (UseScalarMinMax &&
3778           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3779         // If the underlying comparison instruction is used by any other
3780         // instruction, the consumed instructions won't be destroyed, so it is
3781         // not profitable to convert to a min/max.
3782         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3783       OpCode = Opc;
3784       LHSVal = getValue(LHS);
3785       RHSVal = getValue(RHS);
3786       BaseOps.clear();
3787     }
3788 
3789     if (IsUnaryAbs) {
3790       OpCode = Opc;
3791       LHSVal = getValue(LHS);
3792       BaseOps.clear();
3793     }
3794   }
3795 
3796   if (IsUnaryAbs) {
3797     for (unsigned i = 0; i != NumValues; ++i) {
3798       SDLoc dl = getCurSDLoc();
3799       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3800       Values[i] =
3801           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3802       if (Negate)
3803         Values[i] = DAG.getNegative(Values[i], dl, VT);
3804     }
3805   } else {
3806     for (unsigned i = 0; i != NumValues; ++i) {
3807       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3808       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3809       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3810       Values[i] = DAG.getNode(
3811           OpCode, getCurSDLoc(),
3812           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3813     }
3814   }
3815 
3816   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3817                            DAG.getVTList(ValueVTs), Values));
3818 }
3819 
3820 void SelectionDAGBuilder::visitTrunc(const User &I) {
3821   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3822   SDValue N = getValue(I.getOperand(0));
3823   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3824                                                         I.getType());
3825   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3826 }
3827 
3828 void SelectionDAGBuilder::visitZExt(const User &I) {
3829   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3830   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3831   SDValue N = getValue(I.getOperand(0));
3832   auto &TLI = DAG.getTargetLoweringInfo();
3833   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3834 
3835   SDNodeFlags Flags;
3836   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3837     Flags.setNonNeg(PNI->hasNonNeg());
3838 
3839   // Eagerly use nonneg information to canonicalize towards sign_extend if
3840   // that is the target's preference.
3841   // TODO: Let the target do this later.
3842   if (Flags.hasNonNeg() &&
3843       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3844     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3845     return;
3846   }
3847 
3848   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3849 }
3850 
3851 void SelectionDAGBuilder::visitSExt(const User &I) {
3852   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3853   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3854   SDValue N = getValue(I.getOperand(0));
3855   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3856                                                         I.getType());
3857   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3858 }
3859 
3860 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3861   // FPTrunc is never a no-op cast, no need to check
3862   SDValue N = getValue(I.getOperand(0));
3863   SDLoc dl = getCurSDLoc();
3864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3865   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3866   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3867                            DAG.getTargetConstant(
3868                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3869 }
3870 
3871 void SelectionDAGBuilder::visitFPExt(const User &I) {
3872   // FPExt 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_EXTEND, getCurSDLoc(), DestVT, N));
3877 }
3878 
3879 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3880   // FPToUI 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_UINT, getCurSDLoc(), DestVT, N));
3885 }
3886 
3887 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3888   // FPToSI 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   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3893 }
3894 
3895 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3896   // UIToFP is never a no-op cast, no need to check
3897   SDValue N = getValue(I.getOperand(0));
3898   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3899                                                         I.getType());
3900   SDNodeFlags Flags;
3901   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3902     Flags.setNonNeg(PNI->hasNonNeg());
3903 
3904   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3905 }
3906 
3907 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3908   // SIToFP is never a no-op cast, no need to check
3909   SDValue N = getValue(I.getOperand(0));
3910   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3911                                                         I.getType());
3912   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3913 }
3914 
3915 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3916   // What to do depends on the size of the integer and the size of the pointer.
3917   // We can either truncate, zero extend, or no-op, accordingly.
3918   SDValue N = getValue(I.getOperand(0));
3919   auto &TLI = DAG.getTargetLoweringInfo();
3920   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3921                                                         I.getType());
3922   EVT PtrMemVT =
3923       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3924   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3925   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3926   setValue(&I, N);
3927 }
3928 
3929 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3930   // What to do depends on the size of the integer and the size of the pointer.
3931   // We can either truncate, zero extend, or no-op, accordingly.
3932   SDValue N = getValue(I.getOperand(0));
3933   auto &TLI = DAG.getTargetLoweringInfo();
3934   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3935   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3936   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3937   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3938   setValue(&I, N);
3939 }
3940 
3941 void SelectionDAGBuilder::visitBitCast(const User &I) {
3942   SDValue N = getValue(I.getOperand(0));
3943   SDLoc dl = getCurSDLoc();
3944   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3945                                                         I.getType());
3946 
3947   // BitCast assures us that source and destination are the same size so this is
3948   // either a BITCAST or a no-op.
3949   if (DestVT != N.getValueType())
3950     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3951                              DestVT, N)); // convert types.
3952   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3953   // might fold any kind of constant expression to an integer constant and that
3954   // is not what we are looking for. Only recognize a bitcast of a genuine
3955   // constant integer as an opaque constant.
3956   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3957     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3958                                  /*isOpaque*/true));
3959   else
3960     setValue(&I, N);            // noop cast.
3961 }
3962 
3963 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3964   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3965   const Value *SV = I.getOperand(0);
3966   SDValue N = getValue(SV);
3967   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3968 
3969   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3970   unsigned DestAS = I.getType()->getPointerAddressSpace();
3971 
3972   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3973     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3974 
3975   setValue(&I, N);
3976 }
3977 
3978 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3979   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3980   SDValue InVec = getValue(I.getOperand(0));
3981   SDValue InVal = getValue(I.getOperand(1));
3982   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3983                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3984   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3985                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3986                            InVec, InVal, InIdx));
3987 }
3988 
3989 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3991   SDValue InVec = getValue(I.getOperand(0));
3992   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3993                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3994   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
3995                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3996                            InVec, InIdx));
3997 }
3998 
3999 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4000   SDValue Src1 = getValue(I.getOperand(0));
4001   SDValue Src2 = getValue(I.getOperand(1));
4002   ArrayRef<int> Mask;
4003   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4004     Mask = SVI->getShuffleMask();
4005   else
4006     Mask = cast<ConstantExpr>(I).getShuffleMask();
4007   SDLoc DL = getCurSDLoc();
4008   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4009   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4010   EVT SrcVT = Src1.getValueType();
4011 
4012   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4013       VT.isScalableVector()) {
4014     // Canonical splat form of first element of first input vector.
4015     SDValue FirstElt =
4016         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4017                     DAG.getVectorIdxConstant(0, DL));
4018     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4019     return;
4020   }
4021 
4022   // For now, we only handle splats for scalable vectors.
4023   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4024   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4025   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4026 
4027   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4028   unsigned MaskNumElts = Mask.size();
4029 
4030   if (SrcNumElts == MaskNumElts) {
4031     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4032     return;
4033   }
4034 
4035   // Normalize the shuffle vector since mask and vector length don't match.
4036   if (SrcNumElts < MaskNumElts) {
4037     // Mask is longer than the source vectors. We can use concatenate vector to
4038     // make the mask and vectors lengths match.
4039 
4040     if (MaskNumElts % SrcNumElts == 0) {
4041       // Mask length is a multiple of the source vector length.
4042       // Check if the shuffle is some kind of concatenation of the input
4043       // vectors.
4044       unsigned NumConcat = MaskNumElts / SrcNumElts;
4045       bool IsConcat = true;
4046       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4047       for (unsigned i = 0; i != MaskNumElts; ++i) {
4048         int Idx = Mask[i];
4049         if (Idx < 0)
4050           continue;
4051         // Ensure the indices in each SrcVT sized piece are sequential and that
4052         // the same source is used for the whole piece.
4053         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4054             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4055              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4056           IsConcat = false;
4057           break;
4058         }
4059         // Remember which source this index came from.
4060         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4061       }
4062 
4063       // The shuffle is concatenating multiple vectors together. Just emit
4064       // a CONCAT_VECTORS operation.
4065       if (IsConcat) {
4066         SmallVector<SDValue, 8> ConcatOps;
4067         for (auto Src : ConcatSrcs) {
4068           if (Src < 0)
4069             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4070           else if (Src == 0)
4071             ConcatOps.push_back(Src1);
4072           else
4073             ConcatOps.push_back(Src2);
4074         }
4075         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4076         return;
4077       }
4078     }
4079 
4080     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4081     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4082     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4083                                     PaddedMaskNumElts);
4084 
4085     // Pad both vectors with undefs to make them the same length as the mask.
4086     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4087 
4088     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4089     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4090     MOps1[0] = Src1;
4091     MOps2[0] = Src2;
4092 
4093     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4094     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4095 
4096     // Readjust mask for new input vector length.
4097     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4098     for (unsigned i = 0; i != MaskNumElts; ++i) {
4099       int Idx = Mask[i];
4100       if (Idx >= (int)SrcNumElts)
4101         Idx -= SrcNumElts - PaddedMaskNumElts;
4102       MappedOps[i] = Idx;
4103     }
4104 
4105     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4106 
4107     // If the concatenated vector was padded, extract a subvector with the
4108     // correct number of elements.
4109     if (MaskNumElts != PaddedMaskNumElts)
4110       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4111                            DAG.getVectorIdxConstant(0, DL));
4112 
4113     setValue(&I, Result);
4114     return;
4115   }
4116 
4117   if (SrcNumElts > MaskNumElts) {
4118     // Analyze the access pattern of the vector to see if we can extract
4119     // two subvectors and do the shuffle.
4120     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4121     bool CanExtract = true;
4122     for (int Idx : Mask) {
4123       unsigned Input = 0;
4124       if (Idx < 0)
4125         continue;
4126 
4127       if (Idx >= (int)SrcNumElts) {
4128         Input = 1;
4129         Idx -= SrcNumElts;
4130       }
4131 
4132       // If all the indices come from the same MaskNumElts sized portion of
4133       // the sources we can use extract. Also make sure the extract wouldn't
4134       // extract past the end of the source.
4135       int NewStartIdx = alignDown(Idx, MaskNumElts);
4136       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4137           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4138         CanExtract = false;
4139       // Make sure we always update StartIdx as we use it to track if all
4140       // elements are undef.
4141       StartIdx[Input] = NewStartIdx;
4142     }
4143 
4144     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4145       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4146       return;
4147     }
4148     if (CanExtract) {
4149       // Extract appropriate subvector and generate a vector shuffle
4150       for (unsigned Input = 0; Input < 2; ++Input) {
4151         SDValue &Src = Input == 0 ? Src1 : Src2;
4152         if (StartIdx[Input] < 0)
4153           Src = DAG.getUNDEF(VT);
4154         else {
4155           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4156                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4157         }
4158       }
4159 
4160       // Calculate new mask.
4161       SmallVector<int, 8> MappedOps(Mask);
4162       for (int &Idx : MappedOps) {
4163         if (Idx >= (int)SrcNumElts)
4164           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4165         else if (Idx >= 0)
4166           Idx -= StartIdx[0];
4167       }
4168 
4169       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4170       return;
4171     }
4172   }
4173 
4174   // We can't use either concat vectors or extract subvectors so fall back to
4175   // replacing the shuffle with extract and build vector.
4176   // to insert and build vector.
4177   EVT EltVT = VT.getVectorElementType();
4178   SmallVector<SDValue,8> Ops;
4179   for (int Idx : Mask) {
4180     SDValue Res;
4181 
4182     if (Idx < 0) {
4183       Res = DAG.getUNDEF(EltVT);
4184     } else {
4185       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4186       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4187 
4188       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4189                         DAG.getVectorIdxConstant(Idx, DL));
4190     }
4191 
4192     Ops.push_back(Res);
4193   }
4194 
4195   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4196 }
4197 
4198 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4199   ArrayRef<unsigned> Indices = I.getIndices();
4200   const Value *Op0 = I.getOperand(0);
4201   const Value *Op1 = I.getOperand(1);
4202   Type *AggTy = I.getType();
4203   Type *ValTy = Op1->getType();
4204   bool IntoUndef = isa<UndefValue>(Op0);
4205   bool FromUndef = isa<UndefValue>(Op1);
4206 
4207   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4208 
4209   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4210   SmallVector<EVT, 4> AggValueVTs;
4211   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4212   SmallVector<EVT, 4> ValValueVTs;
4213   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4214 
4215   unsigned NumAggValues = AggValueVTs.size();
4216   unsigned NumValValues = ValValueVTs.size();
4217   SmallVector<SDValue, 4> Values(NumAggValues);
4218 
4219   // Ignore an insertvalue that produces an empty object
4220   if (!NumAggValues) {
4221     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4222     return;
4223   }
4224 
4225   SDValue Agg = getValue(Op0);
4226   unsigned i = 0;
4227   // Copy the beginning value(s) from the original aggregate.
4228   for (; i != LinearIndex; ++i)
4229     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4230                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4231   // Copy values from the inserted value(s).
4232   if (NumValValues) {
4233     SDValue Val = getValue(Op1);
4234     for (; i != LinearIndex + NumValValues; ++i)
4235       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4236                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4237   }
4238   // Copy remaining value(s) from the original aggregate.
4239   for (; i != NumAggValues; ++i)
4240     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4241                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4242 
4243   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4244                            DAG.getVTList(AggValueVTs), Values));
4245 }
4246 
4247 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4248   ArrayRef<unsigned> Indices = I.getIndices();
4249   const Value *Op0 = I.getOperand(0);
4250   Type *AggTy = Op0->getType();
4251   Type *ValTy = I.getType();
4252   bool OutOfUndef = isa<UndefValue>(Op0);
4253 
4254   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4255 
4256   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4257   SmallVector<EVT, 4> ValValueVTs;
4258   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4259 
4260   unsigned NumValValues = ValValueVTs.size();
4261 
4262   // Ignore a extractvalue that produces an empty object
4263   if (!NumValValues) {
4264     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4265     return;
4266   }
4267 
4268   SmallVector<SDValue, 4> Values(NumValValues);
4269 
4270   SDValue Agg = getValue(Op0);
4271   // Copy out the selected value(s).
4272   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4273     Values[i - LinearIndex] =
4274       OutOfUndef ?
4275         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4276         SDValue(Agg.getNode(), Agg.getResNo() + i);
4277 
4278   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4279                            DAG.getVTList(ValValueVTs), Values));
4280 }
4281 
4282 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4283   Value *Op0 = I.getOperand(0);
4284   // Note that the pointer operand may be a vector of pointers. Take the scalar
4285   // element which holds a pointer.
4286   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4287   SDValue N = getValue(Op0);
4288   SDLoc dl = getCurSDLoc();
4289   auto &TLI = DAG.getTargetLoweringInfo();
4290 
4291   // Normalize Vector GEP - all scalar operands should be converted to the
4292   // splat vector.
4293   bool IsVectorGEP = I.getType()->isVectorTy();
4294   ElementCount VectorElementCount =
4295       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4296                   : ElementCount::getFixed(0);
4297 
4298   if (IsVectorGEP && !N.getValueType().isVector()) {
4299     LLVMContext &Context = *DAG.getContext();
4300     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4301     N = DAG.getSplat(VT, dl, N);
4302   }
4303 
4304   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4305        GTI != E; ++GTI) {
4306     const Value *Idx = GTI.getOperand();
4307     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4308       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4309       if (Field) {
4310         // N = N + Offset
4311         uint64_t Offset =
4312             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4313 
4314         // In an inbounds GEP with an offset that is nonnegative even when
4315         // interpreted as signed, assume there is no unsigned overflow.
4316         SDNodeFlags Flags;
4317         if (int64_t(Offset) >= 0 && cast<GEPOperator>(I).isInBounds())
4318           Flags.setNoUnsignedWrap(true);
4319 
4320         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4321                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4322       }
4323     } else {
4324       // IdxSize is the width of the arithmetic according to IR semantics.
4325       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4326       // (and fix up the result later).
4327       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4328       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4329       TypeSize ElementSize =
4330           GTI.getSequentialElementStride(DAG.getDataLayout());
4331       // We intentionally mask away the high bits here; ElementSize may not
4332       // fit in IdxTy.
4333       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4334       bool ElementScalable = ElementSize.isScalable();
4335 
4336       // If this is a scalar constant or a splat vector of constants,
4337       // handle it quickly.
4338       const auto *C = dyn_cast<Constant>(Idx);
4339       if (C && isa<VectorType>(C->getType()))
4340         C = C->getSplatValue();
4341 
4342       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4343       if (CI && CI->isZero())
4344         continue;
4345       if (CI && !ElementScalable) {
4346         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4347         LLVMContext &Context = *DAG.getContext();
4348         SDValue OffsVal;
4349         if (IsVectorGEP)
4350           OffsVal = DAG.getConstant(
4351               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4352         else
4353           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4354 
4355         // In an inbounds GEP with an offset that is nonnegative even when
4356         // interpreted as signed, assume there is no unsigned overflow.
4357         SDNodeFlags Flags;
4358         if (Offs.isNonNegative() && cast<GEPOperator>(I).isInBounds())
4359           Flags.setNoUnsignedWrap(true);
4360 
4361         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4362 
4363         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4364         continue;
4365       }
4366 
4367       // N = N + Idx * ElementMul;
4368       SDValue IdxN = getValue(Idx);
4369 
4370       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4371         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4372                                   VectorElementCount);
4373         IdxN = DAG.getSplat(VT, dl, IdxN);
4374       }
4375 
4376       // If the index is smaller or larger than intptr_t, truncate or extend
4377       // it.
4378       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4379 
4380       if (ElementScalable) {
4381         EVT VScaleTy = N.getValueType().getScalarType();
4382         SDValue VScale = DAG.getNode(
4383             ISD::VSCALE, dl, VScaleTy,
4384             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4385         if (IsVectorGEP)
4386           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4387         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4388       } else {
4389         // If this is a multiply by a power of two, turn it into a shl
4390         // immediately.  This is a very common case.
4391         if (ElementMul != 1) {
4392           if (ElementMul.isPowerOf2()) {
4393             unsigned Amt = ElementMul.logBase2();
4394             IdxN = DAG.getNode(ISD::SHL, dl,
4395                                N.getValueType(), IdxN,
4396                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4397           } else {
4398             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4399                                             IdxN.getValueType());
4400             IdxN = DAG.getNode(ISD::MUL, dl,
4401                                N.getValueType(), IdxN, Scale);
4402           }
4403         }
4404       }
4405 
4406       N = DAG.getNode(ISD::ADD, dl,
4407                       N.getValueType(), N, IdxN);
4408     }
4409   }
4410 
4411   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4412   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4413   if (IsVectorGEP) {
4414     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4415     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4416   }
4417 
4418   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4419     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4420 
4421   setValue(&I, N);
4422 }
4423 
4424 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4425   // If this is a fixed sized alloca in the entry block of the function,
4426   // allocate it statically on the stack.
4427   if (FuncInfo.StaticAllocaMap.count(&I))
4428     return;   // getValue will auto-populate this.
4429 
4430   SDLoc dl = getCurSDLoc();
4431   Type *Ty = I.getAllocatedType();
4432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4433   auto &DL = DAG.getDataLayout();
4434   TypeSize TySize = DL.getTypeAllocSize(Ty);
4435   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4436 
4437   SDValue AllocSize = getValue(I.getArraySize());
4438 
4439   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4440   if (AllocSize.getValueType() != IntPtr)
4441     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4442 
4443   if (TySize.isScalable())
4444     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4445                             DAG.getVScale(dl, IntPtr,
4446                                           APInt(IntPtr.getScalarSizeInBits(),
4447                                                 TySize.getKnownMinValue())));
4448   else {
4449     SDValue TySizeValue =
4450         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4451     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4452                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4453   }
4454 
4455   // Handle alignment.  If the requested alignment is less than or equal to
4456   // the stack alignment, ignore it.  If the size is greater than or equal to
4457   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4458   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4459   if (*Alignment <= StackAlign)
4460     Alignment = std::nullopt;
4461 
4462   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4463   // Round the size of the allocation up to the stack alignment size
4464   // by add SA-1 to the size. This doesn't overflow because we're computing
4465   // an address inside an alloca.
4466   SDNodeFlags Flags;
4467   Flags.setNoUnsignedWrap(true);
4468   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4469                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4470 
4471   // Mask out the low bits for alignment purposes.
4472   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4473                           DAG.getConstant(~StackAlignMask, dl, IntPtr));
4474 
4475   SDValue Ops[] = {
4476       getRoot(), AllocSize,
4477       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4478   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4479   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4480   setValue(&I, DSA);
4481   DAG.setRoot(DSA.getValue(1));
4482 
4483   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4484 }
4485 
4486 static const MDNode *getRangeMetadata(const Instruction &I) {
4487   // If !noundef is not present, then !range violation results in a poison
4488   // value rather than immediate undefined behavior. In theory, transferring
4489   // these annotations to SDAG is fine, but in practice there are key SDAG
4490   // transforms that are known not to be poison-safe, such as folding logical
4491   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4492   // also present.
4493   if (!I.hasMetadata(LLVMContext::MD_noundef))
4494     return nullptr;
4495   return I.getMetadata(LLVMContext::MD_range);
4496 }
4497 
4498 static std::optional<ConstantRange> getRange(const Instruction &I) {
4499   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4500     // see comment in getRangeMetadata about this check
4501     if (CB->hasRetAttr(Attribute::NoUndef))
4502       return CB->getRange();
4503   }
4504   if (const MDNode *Range = getRangeMetadata(I))
4505     return getConstantRangeFromMetadata(*Range);
4506   return std::nullopt;
4507 }
4508 
4509 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4510   if (I.isAtomic())
4511     return visitAtomicLoad(I);
4512 
4513   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4514   const Value *SV = I.getOperand(0);
4515   if (TLI.supportSwiftError()) {
4516     // Swifterror values can come from either a function parameter with
4517     // swifterror attribute or an alloca with swifterror attribute.
4518     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4519       if (Arg->hasSwiftErrorAttr())
4520         return visitLoadFromSwiftError(I);
4521     }
4522 
4523     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4524       if (Alloca->isSwiftError())
4525         return visitLoadFromSwiftError(I);
4526     }
4527   }
4528 
4529   SDValue Ptr = getValue(SV);
4530 
4531   Type *Ty = I.getType();
4532   SmallVector<EVT, 4> ValueVTs, MemVTs;
4533   SmallVector<TypeSize, 4> Offsets;
4534   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4535   unsigned NumValues = ValueVTs.size();
4536   if (NumValues == 0)
4537     return;
4538 
4539   Align Alignment = I.getAlign();
4540   AAMDNodes AAInfo = I.getAAMetadata();
4541   const MDNode *Ranges = getRangeMetadata(I);
4542   bool isVolatile = I.isVolatile();
4543   MachineMemOperand::Flags MMOFlags =
4544       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4545 
4546   SDValue Root;
4547   bool ConstantMemory = false;
4548   if (isVolatile)
4549     // Serialize volatile loads with other side effects.
4550     Root = getRoot();
4551   else if (NumValues > MaxParallelChains)
4552     Root = getMemoryRoot();
4553   else if (AA &&
4554            AA->pointsToConstantMemory(MemoryLocation(
4555                SV,
4556                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4557                AAInfo))) {
4558     // Do not serialize (non-volatile) loads of constant memory with anything.
4559     Root = DAG.getEntryNode();
4560     ConstantMemory = true;
4561     MMOFlags |= MachineMemOperand::MOInvariant;
4562   } else {
4563     // Do not serialize non-volatile loads against each other.
4564     Root = DAG.getRoot();
4565   }
4566 
4567   SDLoc dl = getCurSDLoc();
4568 
4569   if (isVolatile)
4570     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4571 
4572   SmallVector<SDValue, 4> Values(NumValues);
4573   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4574 
4575   unsigned ChainI = 0;
4576   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4577     // Serializing loads here may result in excessive register pressure, and
4578     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4579     // could recover a bit by hoisting nodes upward in the chain by recognizing
4580     // they are side-effect free or do not alias. The optimizer should really
4581     // avoid this case by converting large object/array copies to llvm.memcpy
4582     // (MaxParallelChains should always remain as failsafe).
4583     if (ChainI == MaxParallelChains) {
4584       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4585       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4586                                   ArrayRef(Chains.data(), ChainI));
4587       Root = Chain;
4588       ChainI = 0;
4589     }
4590 
4591     // TODO: MachinePointerInfo only supports a fixed length offset.
4592     MachinePointerInfo PtrInfo =
4593         !Offsets[i].isScalable() || Offsets[i].isZero()
4594             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4595             : MachinePointerInfo();
4596 
4597     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4598     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4599                             MMOFlags, AAInfo, Ranges);
4600     Chains[ChainI] = L.getValue(1);
4601 
4602     if (MemVTs[i] != ValueVTs[i])
4603       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4604 
4605     Values[i] = L;
4606   }
4607 
4608   if (!ConstantMemory) {
4609     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4610                                 ArrayRef(Chains.data(), ChainI));
4611     if (isVolatile)
4612       DAG.setRoot(Chain);
4613     else
4614       PendingLoads.push_back(Chain);
4615   }
4616 
4617   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4618                            DAG.getVTList(ValueVTs), Values));
4619 }
4620 
4621 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4622   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4623          "call visitStoreToSwiftError when backend supports swifterror");
4624 
4625   SmallVector<EVT, 4> ValueVTs;
4626   SmallVector<uint64_t, 4> Offsets;
4627   const Value *SrcV = I.getOperand(0);
4628   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4629                   SrcV->getType(), ValueVTs, &Offsets, 0);
4630   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4631          "expect a single EVT for swifterror");
4632 
4633   SDValue Src = getValue(SrcV);
4634   // Create a virtual register, then update the virtual register.
4635   Register VReg =
4636       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4637   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4638   // Chain can be getRoot or getControlRoot.
4639   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4640                                       SDValue(Src.getNode(), Src.getResNo()));
4641   DAG.setRoot(CopyNode);
4642 }
4643 
4644 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4645   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4646          "call visitLoadFromSwiftError when backend supports swifterror");
4647 
4648   assert(!I.isVolatile() &&
4649          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4650          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4651          "Support volatile, non temporal, invariant for load_from_swift_error");
4652 
4653   const Value *SV = I.getOperand(0);
4654   Type *Ty = I.getType();
4655   assert(
4656       (!AA ||
4657        !AA->pointsToConstantMemory(MemoryLocation(
4658            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4659            I.getAAMetadata()))) &&
4660       "load_from_swift_error should not be constant memory");
4661 
4662   SmallVector<EVT, 4> ValueVTs;
4663   SmallVector<uint64_t, 4> Offsets;
4664   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4665                   ValueVTs, &Offsets, 0);
4666   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4667          "expect a single EVT for swifterror");
4668 
4669   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4670   SDValue L = DAG.getCopyFromReg(
4671       getRoot(), getCurSDLoc(),
4672       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4673 
4674   setValue(&I, L);
4675 }
4676 
4677 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4678   if (I.isAtomic())
4679     return visitAtomicStore(I);
4680 
4681   const Value *SrcV = I.getOperand(0);
4682   const Value *PtrV = I.getOperand(1);
4683 
4684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4685   if (TLI.supportSwiftError()) {
4686     // Swifterror values can come from either a function parameter with
4687     // swifterror attribute or an alloca with swifterror attribute.
4688     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4689       if (Arg->hasSwiftErrorAttr())
4690         return visitStoreToSwiftError(I);
4691     }
4692 
4693     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4694       if (Alloca->isSwiftError())
4695         return visitStoreToSwiftError(I);
4696     }
4697   }
4698 
4699   SmallVector<EVT, 4> ValueVTs, MemVTs;
4700   SmallVector<TypeSize, 4> Offsets;
4701   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4702                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4703   unsigned NumValues = ValueVTs.size();
4704   if (NumValues == 0)
4705     return;
4706 
4707   // Get the lowered operands. Note that we do this after
4708   // checking if NumResults is zero, because with zero results
4709   // the operands won't have values in the map.
4710   SDValue Src = getValue(SrcV);
4711   SDValue Ptr = getValue(PtrV);
4712 
4713   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4714   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4715   SDLoc dl = getCurSDLoc();
4716   Align Alignment = I.getAlign();
4717   AAMDNodes AAInfo = I.getAAMetadata();
4718 
4719   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4720 
4721   unsigned ChainI = 0;
4722   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4723     // See visitLoad comments.
4724     if (ChainI == MaxParallelChains) {
4725       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4726                                   ArrayRef(Chains.data(), ChainI));
4727       Root = Chain;
4728       ChainI = 0;
4729     }
4730 
4731     // TODO: MachinePointerInfo only supports a fixed length offset.
4732     MachinePointerInfo PtrInfo =
4733         !Offsets[i].isScalable() || Offsets[i].isZero()
4734             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4735             : MachinePointerInfo();
4736 
4737     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4738     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4739     if (MemVTs[i] != ValueVTs[i])
4740       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4741     SDValue St =
4742         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4743     Chains[ChainI] = St;
4744   }
4745 
4746   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4747                                   ArrayRef(Chains.data(), ChainI));
4748   setValue(&I, StoreNode);
4749   DAG.setRoot(StoreNode);
4750 }
4751 
4752 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4753                                            bool IsCompressing) {
4754   SDLoc sdl = getCurSDLoc();
4755 
4756   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4757                                Align &Alignment) {
4758     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4759     Src0 = I.getArgOperand(0);
4760     Ptr = I.getArgOperand(1);
4761     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4762     Mask = I.getArgOperand(3);
4763   };
4764   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4765                                     Align &Alignment) {
4766     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4767     Src0 = I.getArgOperand(0);
4768     Ptr = I.getArgOperand(1);
4769     Mask = I.getArgOperand(2);
4770     Alignment = I.getParamAlign(1).valueOrOne();
4771   };
4772 
4773   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4774   Align Alignment;
4775   if (IsCompressing)
4776     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4777   else
4778     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4779 
4780   SDValue Ptr = getValue(PtrOperand);
4781   SDValue Src0 = getValue(Src0Operand);
4782   SDValue Mask = getValue(MaskOperand);
4783   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4784 
4785   EVT VT = Src0.getValueType();
4786 
4787   auto MMOFlags = MachineMemOperand::MOStore;
4788   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4789     MMOFlags |= MachineMemOperand::MONonTemporal;
4790 
4791   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4792       MachinePointerInfo(PtrOperand), MMOFlags,
4793       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4794 
4795   const auto &TLI = DAG.getTargetLoweringInfo();
4796   const auto &TTI =
4797       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4798   SDValue StoreNode =
4799       !IsCompressing &&
4800               TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType())
4801           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4802                                  Mask)
4803           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4804                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4805                                IsCompressing);
4806   DAG.setRoot(StoreNode);
4807   setValue(&I, StoreNode);
4808 }
4809 
4810 // Get a uniform base for the Gather/Scatter intrinsic.
4811 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4812 // We try to represent it as a base pointer + vector of indices.
4813 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4814 // The first operand of the GEP may be a single pointer or a vector of pointers
4815 // Example:
4816 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4817 //  or
4818 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4819 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4820 //
4821 // When the first GEP operand is a single pointer - it is the uniform base we
4822 // are looking for. If first operand of the GEP is a splat vector - we
4823 // extract the splat value and use it as a uniform base.
4824 // In all other cases the function returns 'false'.
4825 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4826                            ISD::MemIndexType &IndexType, SDValue &Scale,
4827                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4828                            uint64_t ElemSize) {
4829   SelectionDAG& DAG = SDB->DAG;
4830   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4831   const DataLayout &DL = DAG.getDataLayout();
4832 
4833   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4834 
4835   // Handle splat constant pointer.
4836   if (auto *C = dyn_cast<Constant>(Ptr)) {
4837     C = C->getSplatValue();
4838     if (!C)
4839       return false;
4840 
4841     Base = SDB->getValue(C);
4842 
4843     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4844     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4845     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4846     IndexType = ISD::SIGNED_SCALED;
4847     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4848     return true;
4849   }
4850 
4851   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4852   if (!GEP || GEP->getParent() != CurBB)
4853     return false;
4854 
4855   if (GEP->getNumOperands() != 2)
4856     return false;
4857 
4858   const Value *BasePtr = GEP->getPointerOperand();
4859   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4860 
4861   // Make sure the base is scalar and the index is a vector.
4862   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4863     return false;
4864 
4865   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4866   if (ScaleVal.isScalable())
4867     return false;
4868 
4869   // Target may not support the required addressing mode.
4870   if (ScaleVal != 1 &&
4871       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4872     return false;
4873 
4874   Base = SDB->getValue(BasePtr);
4875   Index = SDB->getValue(IndexVal);
4876   IndexType = ISD::SIGNED_SCALED;
4877 
4878   Scale =
4879       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4880   return true;
4881 }
4882 
4883 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4884   SDLoc sdl = getCurSDLoc();
4885 
4886   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4887   const Value *Ptr = I.getArgOperand(1);
4888   SDValue Src0 = getValue(I.getArgOperand(0));
4889   SDValue Mask = getValue(I.getArgOperand(3));
4890   EVT VT = Src0.getValueType();
4891   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4892                         ->getMaybeAlignValue()
4893                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4895 
4896   SDValue Base;
4897   SDValue Index;
4898   ISD::MemIndexType IndexType;
4899   SDValue Scale;
4900   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4901                                     I.getParent(), VT.getScalarStoreSize());
4902 
4903   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4904   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4905       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4906       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4907   if (!UniformBase) {
4908     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4909     Index = getValue(Ptr);
4910     IndexType = ISD::SIGNED_SCALED;
4911     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4912   }
4913 
4914   EVT IdxVT = Index.getValueType();
4915   EVT EltTy = IdxVT.getVectorElementType();
4916   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4917     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4918     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4919   }
4920 
4921   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4922   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4923                                          Ops, MMO, IndexType, false);
4924   DAG.setRoot(Scatter);
4925   setValue(&I, Scatter);
4926 }
4927 
4928 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4929   SDLoc sdl = getCurSDLoc();
4930 
4931   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4932                               Align &Alignment) {
4933     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4934     Ptr = I.getArgOperand(0);
4935     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4936     Mask = I.getArgOperand(2);
4937     Src0 = I.getArgOperand(3);
4938   };
4939   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4940                                  Align &Alignment) {
4941     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4942     Ptr = I.getArgOperand(0);
4943     Alignment = I.getParamAlign(0).valueOrOne();
4944     Mask = I.getArgOperand(1);
4945     Src0 = I.getArgOperand(2);
4946   };
4947 
4948   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4949   Align Alignment;
4950   if (IsExpanding)
4951     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4952   else
4953     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4954 
4955   SDValue Ptr = getValue(PtrOperand);
4956   SDValue Src0 = getValue(Src0Operand);
4957   SDValue Mask = getValue(MaskOperand);
4958   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4959 
4960   EVT VT = Src0.getValueType();
4961   AAMDNodes AAInfo = I.getAAMetadata();
4962   const MDNode *Ranges = getRangeMetadata(I);
4963 
4964   // Do not serialize masked loads of constant memory with anything.
4965   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4966   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4967 
4968   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4969 
4970   auto MMOFlags = MachineMemOperand::MOLoad;
4971   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4972     MMOFlags |= MachineMemOperand::MONonTemporal;
4973 
4974   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4975       MachinePointerInfo(PtrOperand), MMOFlags,
4976       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4977 
4978   const auto &TLI = DAG.getTargetLoweringInfo();
4979   const auto &TTI =
4980       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4981   // The Load/Res may point to different values and both of them are output
4982   // variables.
4983   SDValue Load;
4984   SDValue Res;
4985   if (!IsExpanding &&
4986       TTI.hasConditionalLoadStoreForType(Src0Operand->getType()))
4987     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
4988   else
4989     Res = Load =
4990         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4991                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
4992   if (AddToChain)
4993     PendingLoads.push_back(Load.getValue(1));
4994   setValue(&I, Res);
4995 }
4996 
4997 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
4998   SDLoc sdl = getCurSDLoc();
4999 
5000   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5001   const Value *Ptr = I.getArgOperand(0);
5002   SDValue Src0 = getValue(I.getArgOperand(3));
5003   SDValue Mask = getValue(I.getArgOperand(2));
5004 
5005   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5006   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5007   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5008                         ->getMaybeAlignValue()
5009                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5010 
5011   const MDNode *Ranges = getRangeMetadata(I);
5012 
5013   SDValue Root = DAG.getRoot();
5014   SDValue Base;
5015   SDValue Index;
5016   ISD::MemIndexType IndexType;
5017   SDValue Scale;
5018   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5019                                     I.getParent(), VT.getScalarStoreSize());
5020   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5021   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5022       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5023       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5024       Ranges);
5025 
5026   if (!UniformBase) {
5027     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5028     Index = getValue(Ptr);
5029     IndexType = ISD::SIGNED_SCALED;
5030     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5031   }
5032 
5033   EVT IdxVT = Index.getValueType();
5034   EVT EltTy = IdxVT.getVectorElementType();
5035   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5036     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5037     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5038   }
5039 
5040   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5041   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5042                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5043 
5044   PendingLoads.push_back(Gather.getValue(1));
5045   setValue(&I, Gather);
5046 }
5047 
5048 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5049   SDLoc dl = getCurSDLoc();
5050   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5051   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5052   SyncScope::ID SSID = I.getSyncScopeID();
5053 
5054   SDValue InChain = getRoot();
5055 
5056   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5057   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5058 
5059   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5060   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5061 
5062   MachineFunction &MF = DAG.getMachineFunction();
5063   MachineMemOperand *MMO = MF.getMachineMemOperand(
5064       MachinePointerInfo(I.getPointerOperand()), Flags,
5065       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5066       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5067 
5068   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5069                                    dl, MemVT, VTs, InChain,
5070                                    getValue(I.getPointerOperand()),
5071                                    getValue(I.getCompareOperand()),
5072                                    getValue(I.getNewValOperand()), MMO);
5073 
5074   SDValue OutChain = L.getValue(2);
5075 
5076   setValue(&I, L);
5077   DAG.setRoot(OutChain);
5078 }
5079 
5080 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5081   SDLoc dl = getCurSDLoc();
5082   ISD::NodeType NT;
5083   switch (I.getOperation()) {
5084   default: llvm_unreachable("Unknown atomicrmw operation");
5085   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5086   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5087   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5088   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5089   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5090   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5091   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5092   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5093   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5094   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5095   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5096   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5097   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5098   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5099   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5100   case AtomicRMWInst::UIncWrap:
5101     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5102     break;
5103   case AtomicRMWInst::UDecWrap:
5104     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5105     break;
5106   }
5107   AtomicOrdering Ordering = I.getOrdering();
5108   SyncScope::ID SSID = I.getSyncScopeID();
5109 
5110   SDValue InChain = getRoot();
5111 
5112   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5114   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5115 
5116   MachineFunction &MF = DAG.getMachineFunction();
5117   MachineMemOperand *MMO = MF.getMachineMemOperand(
5118       MachinePointerInfo(I.getPointerOperand()), Flags,
5119       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5120       AAMDNodes(), nullptr, SSID, Ordering);
5121 
5122   SDValue L =
5123     DAG.getAtomic(NT, dl, MemVT, InChain,
5124                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5125                   MMO);
5126 
5127   SDValue OutChain = L.getValue(1);
5128 
5129   setValue(&I, L);
5130   DAG.setRoot(OutChain);
5131 }
5132 
5133 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5134   SDLoc dl = getCurSDLoc();
5135   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5136   SDValue Ops[3];
5137   Ops[0] = getRoot();
5138   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5139                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5140   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5141                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5142   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5143   setValue(&I, N);
5144   DAG.setRoot(N);
5145 }
5146 
5147 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5148   SDLoc dl = getCurSDLoc();
5149   AtomicOrdering Order = I.getOrdering();
5150   SyncScope::ID SSID = I.getSyncScopeID();
5151 
5152   SDValue InChain = getRoot();
5153 
5154   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5155   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5156   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5157 
5158   if (!TLI.supportsUnalignedAtomics() &&
5159       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5160     report_fatal_error("Cannot generate unaligned atomic load");
5161 
5162   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5163 
5164   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5165       MachinePointerInfo(I.getPointerOperand()), Flags,
5166       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5167       nullptr, SSID, Order);
5168 
5169   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5170 
5171   SDValue Ptr = getValue(I.getPointerOperand());
5172   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5173                             Ptr, MMO);
5174 
5175   SDValue OutChain = L.getValue(1);
5176   if (MemVT != VT)
5177     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5178 
5179   setValue(&I, L);
5180   DAG.setRoot(OutChain);
5181 }
5182 
5183 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5184   SDLoc dl = getCurSDLoc();
5185 
5186   AtomicOrdering Ordering = I.getOrdering();
5187   SyncScope::ID SSID = I.getSyncScopeID();
5188 
5189   SDValue InChain = getRoot();
5190 
5191   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5192   EVT MemVT =
5193       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5194 
5195   if (!TLI.supportsUnalignedAtomics() &&
5196       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5197     report_fatal_error("Cannot generate unaligned atomic store");
5198 
5199   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5200 
5201   MachineFunction &MF = DAG.getMachineFunction();
5202   MachineMemOperand *MMO = MF.getMachineMemOperand(
5203       MachinePointerInfo(I.getPointerOperand()), Flags,
5204       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5205       nullptr, SSID, Ordering);
5206 
5207   SDValue Val = getValue(I.getValueOperand());
5208   if (Val.getValueType() != MemVT)
5209     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5210   SDValue Ptr = getValue(I.getPointerOperand());
5211 
5212   SDValue OutChain =
5213       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5214 
5215   setValue(&I, OutChain);
5216   DAG.setRoot(OutChain);
5217 }
5218 
5219 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5220 /// node.
5221 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5222                                                unsigned Intrinsic) {
5223   // Ignore the callsite's attributes. A specific call site may be marked with
5224   // readnone, but the lowering code will expect the chain based on the
5225   // definition.
5226   const Function *F = I.getCalledFunction();
5227   bool HasChain = !F->doesNotAccessMemory();
5228   bool OnlyLoad = HasChain && F->onlyReadsMemory();
5229 
5230   // Build the operand list.
5231   SmallVector<SDValue, 8> Ops;
5232   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5233     if (OnlyLoad) {
5234       // We don't need to serialize loads against other loads.
5235       Ops.push_back(DAG.getRoot());
5236     } else {
5237       Ops.push_back(getRoot());
5238     }
5239   }
5240 
5241   // Info is set by getTgtMemIntrinsic
5242   TargetLowering::IntrinsicInfo Info;
5243   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5244   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5245                                                DAG.getMachineFunction(),
5246                                                Intrinsic);
5247 
5248   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5249   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5250       Info.opc == ISD::INTRINSIC_W_CHAIN)
5251     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5252                                         TLI.getPointerTy(DAG.getDataLayout())));
5253 
5254   // Add all operands of the call to the operand list.
5255   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5256     const Value *Arg = I.getArgOperand(i);
5257     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5258       Ops.push_back(getValue(Arg));
5259       continue;
5260     }
5261 
5262     // Use TargetConstant instead of a regular constant for immarg.
5263     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5264     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5265       assert(CI->getBitWidth() <= 64 &&
5266              "large intrinsic immediates not handled");
5267       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5268     } else {
5269       Ops.push_back(
5270           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5271     }
5272   }
5273 
5274   SmallVector<EVT, 4> ValueVTs;
5275   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5276 
5277   if (HasChain)
5278     ValueVTs.push_back(MVT::Other);
5279 
5280   SDVTList VTs = DAG.getVTList(ValueVTs);
5281 
5282   // Propagate fast-math-flags from IR to node(s).
5283   SDNodeFlags Flags;
5284   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5285     Flags.copyFMF(*FPMO);
5286   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5287 
5288   // Create the node.
5289   SDValue Result;
5290 
5291   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5292     auto *Token = Bundle->Inputs[0].get();
5293     SDValue ConvControlToken = getValue(Token);
5294     assert(Ops.back().getValueType() != MVT::Glue &&
5295            "Did not expected another glue node here.");
5296     ConvControlToken =
5297         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5298     Ops.push_back(ConvControlToken);
5299   }
5300 
5301   // In some cases, custom collection of operands from CallInst I may be needed.
5302   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5303   if (IsTgtIntrinsic) {
5304     // This is target intrinsic that touches memory
5305     //
5306     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5307     //       didn't yield anything useful.
5308     MachinePointerInfo MPI;
5309     if (Info.ptrVal)
5310       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5311     else if (Info.fallbackAddressSpace)
5312       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5313     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5314                                      Info.memVT, MPI, Info.align, Info.flags,
5315                                      Info.size, I.getAAMetadata());
5316   } else if (!HasChain) {
5317     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5318   } else if (!I.getType()->isVoidTy()) {
5319     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5320   } else {
5321     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5322   }
5323 
5324   if (HasChain) {
5325     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5326     if (OnlyLoad)
5327       PendingLoads.push_back(Chain);
5328     else
5329       DAG.setRoot(Chain);
5330   }
5331 
5332   if (!I.getType()->isVoidTy()) {
5333     if (!isa<VectorType>(I.getType()))
5334       Result = lowerRangeToAssertZExt(DAG, I, Result);
5335 
5336     MaybeAlign Alignment = I.getRetAlign();
5337 
5338     // Insert `assertalign` node if there's an alignment.
5339     if (InsertAssertAlign && Alignment) {
5340       Result =
5341           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5342     }
5343   }
5344 
5345   setValue(&I, Result);
5346 }
5347 
5348 /// GetSignificand - Get the significand and build it into a floating-point
5349 /// number with exponent of 1:
5350 ///
5351 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5352 ///
5353 /// where Op is the hexadecimal representation of floating point value.
5354 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5355   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5356                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5357   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5358                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5359   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5360 }
5361 
5362 /// GetExponent - Get the exponent:
5363 ///
5364 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5365 ///
5366 /// where Op is the hexadecimal representation of floating point value.
5367 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5368                            const TargetLowering &TLI, const SDLoc &dl) {
5369   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5370                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5371   SDValue t1 = DAG.getNode(
5372       ISD::SRL, dl, MVT::i32, t0,
5373       DAG.getConstant(23, dl,
5374                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5375   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5376                            DAG.getConstant(127, dl, MVT::i32));
5377   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5378 }
5379 
5380 /// getF32Constant - Get 32-bit floating point constant.
5381 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5382                               const SDLoc &dl) {
5383   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5384                            MVT::f32);
5385 }
5386 
5387 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5388                                        SelectionDAG &DAG) {
5389   // TODO: What fast-math-flags should be set on the floating-point nodes?
5390 
5391   //   IntegerPartOfX = ((int32_t)(t0);
5392   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5393 
5394   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5395   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5396   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5397 
5398   //   IntegerPartOfX <<= 23;
5399   IntegerPartOfX =
5400       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5401                   DAG.getConstant(23, dl,
5402                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5403                                       MVT::i32, DAG.getDataLayout())));
5404 
5405   SDValue TwoToFractionalPartOfX;
5406   if (LimitFloatPrecision <= 6) {
5407     // For floating-point precision of 6:
5408     //
5409     //   TwoToFractionalPartOfX =
5410     //     0.997535578f +
5411     //       (0.735607626f + 0.252464424f * x) * x;
5412     //
5413     // error 0.0144103317, which is 6 bits
5414     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5415                              getF32Constant(DAG, 0x3e814304, dl));
5416     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5417                              getF32Constant(DAG, 0x3f3c50c8, dl));
5418     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5419     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5420                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5421   } else if (LimitFloatPrecision <= 12) {
5422     // For floating-point precision of 12:
5423     //
5424     //   TwoToFractionalPartOfX =
5425     //     0.999892986f +
5426     //       (0.696457318f +
5427     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5428     //
5429     // error 0.000107046256, which is 13 to 14 bits
5430     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5431                              getF32Constant(DAG, 0x3da235e3, dl));
5432     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5433                              getF32Constant(DAG, 0x3e65b8f3, dl));
5434     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5435     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5436                              getF32Constant(DAG, 0x3f324b07, dl));
5437     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5438     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5439                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5440   } else { // LimitFloatPrecision <= 18
5441     // For floating-point precision of 18:
5442     //
5443     //   TwoToFractionalPartOfX =
5444     //     0.999999982f +
5445     //       (0.693148872f +
5446     //         (0.240227044f +
5447     //           (0.554906021e-1f +
5448     //             (0.961591928e-2f +
5449     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5450     // error 2.47208000*10^(-7), which is better than 18 bits
5451     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5452                              getF32Constant(DAG, 0x3924b03e, dl));
5453     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5454                              getF32Constant(DAG, 0x3ab24b87, dl));
5455     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5456     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5457                              getF32Constant(DAG, 0x3c1d8c17, dl));
5458     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5459     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5460                              getF32Constant(DAG, 0x3d634a1d, dl));
5461     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5462     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5463                              getF32Constant(DAG, 0x3e75fe14, dl));
5464     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5465     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5466                               getF32Constant(DAG, 0x3f317234, dl));
5467     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5468     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5469                                          getF32Constant(DAG, 0x3f800000, dl));
5470   }
5471 
5472   // Add the exponent into the result in integer domain.
5473   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5474   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5475                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5476 }
5477 
5478 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5479 /// limited-precision mode.
5480 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5481                          const TargetLowering &TLI, SDNodeFlags Flags) {
5482   if (Op.getValueType() == MVT::f32 &&
5483       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5484 
5485     // Put the exponent in the right bit position for later addition to the
5486     // final result:
5487     //
5488     // t0 = Op * log2(e)
5489 
5490     // TODO: What fast-math-flags should be set here?
5491     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5492                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5493     return getLimitedPrecisionExp2(t0, dl, DAG);
5494   }
5495 
5496   // No special expansion.
5497   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5498 }
5499 
5500 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5501 /// limited-precision mode.
5502 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5503                          const TargetLowering &TLI, SDNodeFlags Flags) {
5504   // TODO: What fast-math-flags should be set on the floating-point nodes?
5505 
5506   if (Op.getValueType() == MVT::f32 &&
5507       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5508     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5509 
5510     // Scale the exponent by log(2).
5511     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5512     SDValue LogOfExponent =
5513         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5514                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5515 
5516     // Get the significand and build it into a floating-point number with
5517     // exponent of 1.
5518     SDValue X = GetSignificand(DAG, Op1, dl);
5519 
5520     SDValue LogOfMantissa;
5521     if (LimitFloatPrecision <= 6) {
5522       // For floating-point precision of 6:
5523       //
5524       //   LogofMantissa =
5525       //     -1.1609546f +
5526       //       (1.4034025f - 0.23903021f * x) * x;
5527       //
5528       // error 0.0034276066, which is better than 8 bits
5529       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5530                                getF32Constant(DAG, 0xbe74c456, dl));
5531       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5532                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5533       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5534       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5535                                   getF32Constant(DAG, 0x3f949a29, dl));
5536     } else if (LimitFloatPrecision <= 12) {
5537       // For floating-point precision of 12:
5538       //
5539       //   LogOfMantissa =
5540       //     -1.7417939f +
5541       //       (2.8212026f +
5542       //         (-1.4699568f +
5543       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5544       //
5545       // error 0.000061011436, which is 14 bits
5546       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5547                                getF32Constant(DAG, 0xbd67b6d6, dl));
5548       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5549                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5550       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5551       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5552                                getF32Constant(DAG, 0x3fbc278b, dl));
5553       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5554       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5555                                getF32Constant(DAG, 0x40348e95, dl));
5556       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5557       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5558                                   getF32Constant(DAG, 0x3fdef31a, dl));
5559     } else { // LimitFloatPrecision <= 18
5560       // For floating-point precision of 18:
5561       //
5562       //   LogOfMantissa =
5563       //     -2.1072184f +
5564       //       (4.2372794f +
5565       //         (-3.7029485f +
5566       //           (2.2781945f +
5567       //             (-0.87823314f +
5568       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5569       //
5570       // error 0.0000023660568, which is better than 18 bits
5571       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5572                                getF32Constant(DAG, 0xbc91e5ac, dl));
5573       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5574                                getF32Constant(DAG, 0x3e4350aa, dl));
5575       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5576       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5577                                getF32Constant(DAG, 0x3f60d3e3, dl));
5578       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5579       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5580                                getF32Constant(DAG, 0x4011cdf0, dl));
5581       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5582       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5583                                getF32Constant(DAG, 0x406cfd1c, dl));
5584       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5585       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5586                                getF32Constant(DAG, 0x408797cb, dl));
5587       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5588       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5589                                   getF32Constant(DAG, 0x4006dcab, dl));
5590     }
5591 
5592     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5593   }
5594 
5595   // No special expansion.
5596   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5597 }
5598 
5599 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5600 /// limited-precision mode.
5601 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5602                           const TargetLowering &TLI, SDNodeFlags Flags) {
5603   // TODO: What fast-math-flags should be set on the floating-point nodes?
5604 
5605   if (Op.getValueType() == MVT::f32 &&
5606       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5607     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5608 
5609     // Get the exponent.
5610     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5611 
5612     // Get the significand and build it into a floating-point number with
5613     // exponent of 1.
5614     SDValue X = GetSignificand(DAG, Op1, dl);
5615 
5616     // Different possible minimax approximations of significand in
5617     // floating-point for various degrees of accuracy over [1,2].
5618     SDValue Log2ofMantissa;
5619     if (LimitFloatPrecision <= 6) {
5620       // For floating-point precision of 6:
5621       //
5622       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5623       //
5624       // error 0.0049451742, which is more than 7 bits
5625       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5626                                getF32Constant(DAG, 0xbeb08fe0, dl));
5627       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5628                                getF32Constant(DAG, 0x40019463, dl));
5629       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5630       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5631                                    getF32Constant(DAG, 0x3fd6633d, dl));
5632     } else if (LimitFloatPrecision <= 12) {
5633       // For floating-point precision of 12:
5634       //
5635       //   Log2ofMantissa =
5636       //     -2.51285454f +
5637       //       (4.07009056f +
5638       //         (-2.12067489f +
5639       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5640       //
5641       // error 0.0000876136000, which is better than 13 bits
5642       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5643                                getF32Constant(DAG, 0xbda7262e, dl));
5644       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5645                                getF32Constant(DAG, 0x3f25280b, dl));
5646       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5647       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5648                                getF32Constant(DAG, 0x4007b923, dl));
5649       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5650       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5651                                getF32Constant(DAG, 0x40823e2f, dl));
5652       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5653       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5654                                    getF32Constant(DAG, 0x4020d29c, dl));
5655     } else { // LimitFloatPrecision <= 18
5656       // For floating-point precision of 18:
5657       //
5658       //   Log2ofMantissa =
5659       //     -3.0400495f +
5660       //       (6.1129976f +
5661       //         (-5.3420409f +
5662       //           (3.2865683f +
5663       //             (-1.2669343f +
5664       //               (0.27515199f -
5665       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5666       //
5667       // error 0.0000018516, which is better than 18 bits
5668       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5669                                getF32Constant(DAG, 0xbcd2769e, dl));
5670       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5671                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5672       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5673       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5674                                getF32Constant(DAG, 0x3fa22ae7, dl));
5675       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5676       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5677                                getF32Constant(DAG, 0x40525723, dl));
5678       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5679       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5680                                getF32Constant(DAG, 0x40aaf200, dl));
5681       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5682       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5683                                getF32Constant(DAG, 0x40c39dad, dl));
5684       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5685       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5686                                    getF32Constant(DAG, 0x4042902c, dl));
5687     }
5688 
5689     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5690   }
5691 
5692   // No special expansion.
5693   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5694 }
5695 
5696 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5697 /// limited-precision mode.
5698 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5699                            const TargetLowering &TLI, SDNodeFlags Flags) {
5700   // TODO: What fast-math-flags should be set on the floating-point nodes?
5701 
5702   if (Op.getValueType() == MVT::f32 &&
5703       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5704     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5705 
5706     // Scale the exponent by log10(2) [0.30102999f].
5707     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5708     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5709                                         getF32Constant(DAG, 0x3e9a209a, dl));
5710 
5711     // Get the significand and build it into a floating-point number with
5712     // exponent of 1.
5713     SDValue X = GetSignificand(DAG, Op1, dl);
5714 
5715     SDValue Log10ofMantissa;
5716     if (LimitFloatPrecision <= 6) {
5717       // For floating-point precision of 6:
5718       //
5719       //   Log10ofMantissa =
5720       //     -0.50419619f +
5721       //       (0.60948995f - 0.10380950f * x) * x;
5722       //
5723       // error 0.0014886165, which is 6 bits
5724       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5725                                getF32Constant(DAG, 0xbdd49a13, dl));
5726       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5727                                getF32Constant(DAG, 0x3f1c0789, dl));
5728       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5729       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5730                                     getF32Constant(DAG, 0x3f011300, dl));
5731     } else if (LimitFloatPrecision <= 12) {
5732       // For floating-point precision of 12:
5733       //
5734       //   Log10ofMantissa =
5735       //     -0.64831180f +
5736       //       (0.91751397f +
5737       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5738       //
5739       // error 0.00019228036, which is better than 12 bits
5740       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5741                                getF32Constant(DAG, 0x3d431f31, dl));
5742       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5743                                getF32Constant(DAG, 0x3ea21fb2, dl));
5744       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5745       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5746                                getF32Constant(DAG, 0x3f6ae232, dl));
5747       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5748       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5749                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5750     } else { // LimitFloatPrecision <= 18
5751       // For floating-point precision of 18:
5752       //
5753       //   Log10ofMantissa =
5754       //     -0.84299375f +
5755       //       (1.5327582f +
5756       //         (-1.0688956f +
5757       //           (0.49102474f +
5758       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5759       //
5760       // error 0.0000037995730, which is better than 18 bits
5761       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5762                                getF32Constant(DAG, 0x3c5d51ce, dl));
5763       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5764                                getF32Constant(DAG, 0x3e00685a, dl));
5765       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5766       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5767                                getF32Constant(DAG, 0x3efb6798, dl));
5768       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5769       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5770                                getF32Constant(DAG, 0x3f88d192, dl));
5771       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5772       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5773                                getF32Constant(DAG, 0x3fc4316c, dl));
5774       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5775       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5776                                     getF32Constant(DAG, 0x3f57ce70, dl));
5777     }
5778 
5779     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5780   }
5781 
5782   // No special expansion.
5783   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5784 }
5785 
5786 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5787 /// limited-precision mode.
5788 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5789                           const TargetLowering &TLI, SDNodeFlags Flags) {
5790   if (Op.getValueType() == MVT::f32 &&
5791       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5792     return getLimitedPrecisionExp2(Op, dl, DAG);
5793 
5794   // No special expansion.
5795   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5796 }
5797 
5798 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5799 /// limited-precision mode with x == 10.0f.
5800 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5801                          SelectionDAG &DAG, const TargetLowering &TLI,
5802                          SDNodeFlags Flags) {
5803   bool IsExp10 = false;
5804   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5805       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5806     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5807       APFloat Ten(10.0f);
5808       IsExp10 = LHSC->isExactlyValue(Ten);
5809     }
5810   }
5811 
5812   // TODO: What fast-math-flags should be set on the FMUL node?
5813   if (IsExp10) {
5814     // Put the exponent in the right bit position for later addition to the
5815     // final result:
5816     //
5817     //   #define LOG2OF10 3.3219281f
5818     //   t0 = Op * LOG2OF10;
5819     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5820                              getF32Constant(DAG, 0x40549a78, dl));
5821     return getLimitedPrecisionExp2(t0, dl, DAG);
5822   }
5823 
5824   // No special expansion.
5825   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5826 }
5827 
5828 /// ExpandPowI - Expand a llvm.powi intrinsic.
5829 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5830                           SelectionDAG &DAG) {
5831   // If RHS is a constant, we can expand this out to a multiplication tree if
5832   // it's beneficial on the target, otherwise we end up lowering to a call to
5833   // __powidf2 (for example).
5834   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5835     unsigned Val = RHSC->getSExtValue();
5836 
5837     // powi(x, 0) -> 1.0
5838     if (Val == 0)
5839       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5840 
5841     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5842             Val, DAG.shouldOptForSize())) {
5843       // Get the exponent as a positive value.
5844       if ((int)Val < 0)
5845         Val = -Val;
5846       // We use the simple binary decomposition method to generate the multiply
5847       // sequence.  There are more optimal ways to do this (for example,
5848       // powi(x,15) generates one more multiply than it should), but this has
5849       // the benefit of being both really simple and much better than a libcall.
5850       SDValue Res; // Logically starts equal to 1.0
5851       SDValue CurSquare = LHS;
5852       // TODO: Intrinsics should have fast-math-flags that propagate to these
5853       // nodes.
5854       while (Val) {
5855         if (Val & 1) {
5856           if (Res.getNode())
5857             Res =
5858                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5859           else
5860             Res = CurSquare; // 1.0*CurSquare.
5861         }
5862 
5863         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5864                                 CurSquare, CurSquare);
5865         Val >>= 1;
5866       }
5867 
5868       // If the original was negative, invert the result, producing 1/(x*x*x).
5869       if (RHSC->getSExtValue() < 0)
5870         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5871                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5872       return Res;
5873     }
5874   }
5875 
5876   // Otherwise, expand to a libcall.
5877   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5878 }
5879 
5880 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5881                             SDValue LHS, SDValue RHS, SDValue Scale,
5882                             SelectionDAG &DAG, const TargetLowering &TLI) {
5883   EVT VT = LHS.getValueType();
5884   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5885   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5886   LLVMContext &Ctx = *DAG.getContext();
5887 
5888   // If the type is legal but the operation isn't, this node might survive all
5889   // the way to operation legalization. If we end up there and we do not have
5890   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5891   // node.
5892 
5893   // Coax the legalizer into expanding the node during type legalization instead
5894   // by bumping the size by one bit. This will force it to Promote, enabling the
5895   // early expansion and avoiding the need to expand later.
5896 
5897   // We don't have to do this if Scale is 0; that can always be expanded, unless
5898   // it's a saturating signed operation. Those can experience true integer
5899   // division overflow, a case which we must avoid.
5900 
5901   // FIXME: We wouldn't have to do this (or any of the early
5902   // expansion/promotion) if it was possible to expand a libcall of an
5903   // illegal type during operation legalization. But it's not, so things
5904   // get a bit hacky.
5905   unsigned ScaleInt = Scale->getAsZExtVal();
5906   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5907       (TLI.isTypeLegal(VT) ||
5908        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5909     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5910         Opcode, VT, ScaleInt);
5911     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5912       EVT PromVT;
5913       if (VT.isScalarInteger())
5914         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5915       else if (VT.isVector()) {
5916         PromVT = VT.getVectorElementType();
5917         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5918         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5919       } else
5920         llvm_unreachable("Wrong VT for DIVFIX?");
5921       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5922       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5923       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5924       // For saturating operations, we need to shift up the LHS to get the
5925       // proper saturation width, and then shift down again afterwards.
5926       if (Saturating)
5927         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5928                           DAG.getConstant(1, DL, ShiftTy));
5929       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5930       if (Saturating)
5931         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5932                           DAG.getConstant(1, DL, ShiftTy));
5933       return DAG.getZExtOrTrunc(Res, DL, VT);
5934     }
5935   }
5936 
5937   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5938 }
5939 
5940 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5941 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5942 static void
5943 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5944                      const SDValue &N) {
5945   switch (N.getOpcode()) {
5946   case ISD::CopyFromReg: {
5947     SDValue Op = N.getOperand(1);
5948     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5949                       Op.getValueType().getSizeInBits());
5950     return;
5951   }
5952   case ISD::BITCAST:
5953   case ISD::AssertZext:
5954   case ISD::AssertSext:
5955   case ISD::TRUNCATE:
5956     getUnderlyingArgRegs(Regs, N.getOperand(0));
5957     return;
5958   case ISD::BUILD_PAIR:
5959   case ISD::BUILD_VECTOR:
5960   case ISD::CONCAT_VECTORS:
5961     for (SDValue Op : N->op_values())
5962       getUnderlyingArgRegs(Regs, Op);
5963     return;
5964   default:
5965     return;
5966   }
5967 }
5968 
5969 /// If the DbgValueInst is a dbg_value of a function argument, create the
5970 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5971 /// instruction selection, they will be inserted to the entry BB.
5972 /// We don't currently support this for variadic dbg_values, as they shouldn't
5973 /// appear for function arguments or in the prologue.
5974 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5975     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5976     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5977   const Argument *Arg = dyn_cast<Argument>(V);
5978   if (!Arg)
5979     return false;
5980 
5981   MachineFunction &MF = DAG.getMachineFunction();
5982   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5983 
5984   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5985   // we've been asked to pursue.
5986   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5987                               bool Indirect) {
5988     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5989       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5990       // pointing at the VReg, which will be patched up later.
5991       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
5992       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
5993           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
5994           /* isKill */ false, /* isDead */ false,
5995           /* isUndef */ false, /* isEarlyClobber */ false,
5996           /* SubReg */ 0, /* isDebug */ true)});
5997 
5998       auto *NewDIExpr = FragExpr;
5999       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6000       // the DIExpression.
6001       if (Indirect)
6002         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6003       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6004       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6005       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6006     } else {
6007       // Create a completely standard DBG_VALUE.
6008       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6009       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6010     }
6011   };
6012 
6013   if (Kind == FuncArgumentDbgValueKind::Value) {
6014     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6015     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6016     // the entry block.
6017     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6018     if (!IsInEntryBlock)
6019       return false;
6020 
6021     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6022     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6023     // variable that also is a param.
6024     //
6025     // Although, if we are at the top of the entry block already, we can still
6026     // emit using ArgDbgValue. This might catch some situations when the
6027     // dbg.value refers to an argument that isn't used in the entry block, so
6028     // any CopyToReg node would be optimized out and the only way to express
6029     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6030     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6031     // we should only emit as ArgDbgValue if the Variable is an argument to the
6032     // current function, and the dbg.value intrinsic is found in the entry
6033     // block.
6034     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6035         !DL->getInlinedAt();
6036     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6037     if (!IsInPrologue && !VariableIsFunctionInputArg)
6038       return false;
6039 
6040     // Here we assume that a function argument on IR level only can be used to
6041     // describe one input parameter on source level. If we for example have
6042     // source code like this
6043     //
6044     //    struct A { long x, y; };
6045     //    void foo(struct A a, long b) {
6046     //      ...
6047     //      b = a.x;
6048     //      ...
6049     //    }
6050     //
6051     // and IR like this
6052     //
6053     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6054     //  entry:
6055     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6056     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6057     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6058     //    ...
6059     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6060     //    ...
6061     //
6062     // then the last dbg.value is describing a parameter "b" using a value that
6063     // is an argument. But since we already has used %a1 to describe a parameter
6064     // we should not handle that last dbg.value here (that would result in an
6065     // incorrect hoisting of the DBG_VALUE to the function entry).
6066     // Notice that we allow one dbg.value per IR level argument, to accommodate
6067     // for the situation with fragments above.
6068     // If there is no node for the value being handled, we return true to skip
6069     // the normal generation of debug info, as it would kill existing debug
6070     // info for the parameter in case of duplicates.
6071     if (VariableIsFunctionInputArg) {
6072       unsigned ArgNo = Arg->getArgNo();
6073       if (ArgNo >= FuncInfo.DescribedArgs.size())
6074         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6075       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6076         return !NodeMap[V].getNode();
6077       FuncInfo.DescribedArgs.set(ArgNo);
6078     }
6079   }
6080 
6081   bool IsIndirect = false;
6082   std::optional<MachineOperand> Op;
6083   // Some arguments' frame index is recorded during argument lowering.
6084   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6085   if (FI != std::numeric_limits<int>::max())
6086     Op = MachineOperand::CreateFI(FI);
6087 
6088   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
6089   if (!Op && N.getNode()) {
6090     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6091     Register Reg;
6092     if (ArgRegsAndSizes.size() == 1)
6093       Reg = ArgRegsAndSizes.front().first;
6094 
6095     if (Reg && Reg.isVirtual()) {
6096       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6097       Register PR = RegInfo.getLiveInPhysReg(Reg);
6098       if (PR)
6099         Reg = PR;
6100     }
6101     if (Reg) {
6102       Op = MachineOperand::CreateReg(Reg, false);
6103       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6104     }
6105   }
6106 
6107   if (!Op && N.getNode()) {
6108     // Check if frame index is available.
6109     SDValue LCandidate = peekThroughBitcasts(N);
6110     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6111       if (FrameIndexSDNode *FINode =
6112           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6113         Op = MachineOperand::CreateFI(FINode->getIndex());
6114   }
6115 
6116   if (!Op) {
6117     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6118     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
6119                                          SplitRegs) {
6120       unsigned Offset = 0;
6121       for (const auto &RegAndSize : SplitRegs) {
6122         // If the expression is already a fragment, the current register
6123         // offset+size might extend beyond the fragment. In this case, only
6124         // the register bits that are inside the fragment are relevant.
6125         int RegFragmentSizeInBits = RegAndSize.second;
6126         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6127           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6128           // The register is entirely outside the expression fragment,
6129           // so is irrelevant for debug info.
6130           if (Offset >= ExprFragmentSizeInBits)
6131             break;
6132           // The register is partially outside the expression fragment, only
6133           // the low bits within the fragment are relevant for debug info.
6134           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6135             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6136           }
6137         }
6138 
6139         auto FragmentExpr = DIExpression::createFragmentExpression(
6140             Expr, Offset, RegFragmentSizeInBits);
6141         Offset += RegAndSize.second;
6142         // If a valid fragment expression cannot be created, the variable's
6143         // correct value cannot be determined and so it is set as Undef.
6144         if (!FragmentExpr) {
6145           SDDbgValue *SDV = DAG.getConstantDbgValue(
6146               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6147           DAG.AddDbgValue(SDV, false);
6148           continue;
6149         }
6150         MachineInstr *NewMI =
6151             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6152                              Kind != FuncArgumentDbgValueKind::Value);
6153         FuncInfo.ArgDbgValues.push_back(NewMI);
6154       }
6155     };
6156 
6157     // Check if ValueMap has reg number.
6158     DenseMap<const Value *, Register>::const_iterator
6159       VMI = FuncInfo.ValueMap.find(V);
6160     if (VMI != FuncInfo.ValueMap.end()) {
6161       const auto &TLI = DAG.getTargetLoweringInfo();
6162       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6163                        V->getType(), std::nullopt);
6164       if (RFV.occupiesMultipleRegs()) {
6165         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6166         return true;
6167       }
6168 
6169       Op = MachineOperand::CreateReg(VMI->second, false);
6170       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6171     } else if (ArgRegsAndSizes.size() > 1) {
6172       // This was split due to the calling convention, and no virtual register
6173       // mapping exists for the value.
6174       splitMultiRegDbgValue(ArgRegsAndSizes);
6175       return true;
6176     }
6177   }
6178 
6179   if (!Op)
6180     return false;
6181 
6182   assert(Variable->isValidLocationForIntrinsic(DL) &&
6183          "Expected inlined-at fields to agree");
6184   MachineInstr *NewMI = nullptr;
6185 
6186   if (Op->isReg())
6187     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6188   else
6189     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6190                     Variable, Expr);
6191 
6192   // Otherwise, use ArgDbgValues.
6193   FuncInfo.ArgDbgValues.push_back(NewMI);
6194   return true;
6195 }
6196 
6197 /// Return the appropriate SDDbgValue based on N.
6198 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6199                                              DILocalVariable *Variable,
6200                                              DIExpression *Expr,
6201                                              const DebugLoc &dl,
6202                                              unsigned DbgSDNodeOrder) {
6203   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6204     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6205     // stack slot locations.
6206     //
6207     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6208     // debug values here after optimization:
6209     //
6210     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6211     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6212     //
6213     // Both describe the direct values of their associated variables.
6214     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6215                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6216   }
6217   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6218                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6219 }
6220 
6221 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6222   switch (Intrinsic) {
6223   case Intrinsic::smul_fix:
6224     return ISD::SMULFIX;
6225   case Intrinsic::umul_fix:
6226     return ISD::UMULFIX;
6227   case Intrinsic::smul_fix_sat:
6228     return ISD::SMULFIXSAT;
6229   case Intrinsic::umul_fix_sat:
6230     return ISD::UMULFIXSAT;
6231   case Intrinsic::sdiv_fix:
6232     return ISD::SDIVFIX;
6233   case Intrinsic::udiv_fix:
6234     return ISD::UDIVFIX;
6235   case Intrinsic::sdiv_fix_sat:
6236     return ISD::SDIVFIXSAT;
6237   case Intrinsic::udiv_fix_sat:
6238     return ISD::UDIVFIXSAT;
6239   default:
6240     llvm_unreachable("Unhandled fixed point intrinsic");
6241   }
6242 }
6243 
6244 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6245                                            const char *FunctionName) {
6246   assert(FunctionName && "FunctionName must not be nullptr");
6247   SDValue Callee = DAG.getExternalSymbol(
6248       FunctionName,
6249       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6250   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6251 }
6252 
6253 /// Given a @llvm.call.preallocated.setup, return the corresponding
6254 /// preallocated call.
6255 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6256   assert(cast<CallBase>(PreallocatedSetup)
6257                  ->getCalledFunction()
6258                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6259          "expected call_preallocated_setup Value");
6260   for (const auto *U : PreallocatedSetup->users()) {
6261     auto *UseCall = cast<CallBase>(U);
6262     const Function *Fn = UseCall->getCalledFunction();
6263     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6264       return UseCall;
6265     }
6266   }
6267   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6268 }
6269 
6270 /// If DI is a debug value with an EntryValue expression, lower it using the
6271 /// corresponding physical register of the associated Argument value
6272 /// (guaranteed to exist by the verifier).
6273 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6274     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6275     DIExpression *Expr, DebugLoc DbgLoc) {
6276   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6277     return false;
6278 
6279   // These properties are guaranteed by the verifier.
6280   const Argument *Arg = cast<Argument>(Values[0]);
6281   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6282 
6283   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6284   if (ArgIt == FuncInfo.ValueMap.end()) {
6285     LLVM_DEBUG(
6286         dbgs() << "Dropping dbg.value: expression is entry_value but "
6287                   "couldn't find an associated register for the Argument\n");
6288     return true;
6289   }
6290   Register ArgVReg = ArgIt->getSecond();
6291 
6292   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6293     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6294       SDDbgValue *SDV = DAG.getVRegDbgValue(
6295           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6296       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6297       return true;
6298     }
6299   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6300                        "couldn't find a physical register\n");
6301   return true;
6302 }
6303 
6304 /// Lower the call to the specified intrinsic function.
6305 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6306                                                   unsigned Intrinsic) {
6307   SDLoc sdl = getCurSDLoc();
6308   switch (Intrinsic) {
6309   case Intrinsic::experimental_convergence_anchor:
6310     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6311     break;
6312   case Intrinsic::experimental_convergence_entry:
6313     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6314     break;
6315   case Intrinsic::experimental_convergence_loop: {
6316     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6317     auto *Token = Bundle->Inputs[0].get();
6318     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6319                              getValue(Token)));
6320     break;
6321   }
6322   }
6323 }
6324 
6325 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6326                                                unsigned IntrinsicID) {
6327   // For now, we're only lowering an 'add' histogram.
6328   // We can add others later, e.g. saturating adds, min/max.
6329   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6330          "Tried to lower unsupported histogram type");
6331   SDLoc sdl = getCurSDLoc();
6332   Value *Ptr = I.getOperand(0);
6333   SDValue Inc = getValue(I.getOperand(1));
6334   SDValue Mask = getValue(I.getOperand(2));
6335 
6336   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6337   DataLayout TargetDL = DAG.getDataLayout();
6338   EVT VT = Inc.getValueType();
6339   Align Alignment = DAG.getEVTAlign(VT);
6340 
6341   const MDNode *Ranges = getRangeMetadata(I);
6342 
6343   SDValue Root = DAG.getRoot();
6344   SDValue Base;
6345   SDValue Index;
6346   ISD::MemIndexType IndexType;
6347   SDValue Scale;
6348   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6349                                     I.getParent(), VT.getScalarStoreSize());
6350 
6351   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6352 
6353   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6354       MachinePointerInfo(AS),
6355       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6356       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6357 
6358   if (!UniformBase) {
6359     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6360     Index = getValue(Ptr);
6361     IndexType = ISD::SIGNED_SCALED;
6362     Scale =
6363         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6364   }
6365 
6366   EVT IdxVT = Index.getValueType();
6367   EVT EltTy = IdxVT.getVectorElementType();
6368   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6369     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6370     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6371   }
6372 
6373   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6374 
6375   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6376   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6377                                              Ops, MMO, IndexType);
6378 
6379   setValue(&I, Histogram);
6380   DAG.setRoot(Histogram);
6381 }
6382 
6383 /// Lower the call to the specified intrinsic function.
6384 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6385                                              unsigned Intrinsic) {
6386   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6387   SDLoc sdl = getCurSDLoc();
6388   DebugLoc dl = getCurDebugLoc();
6389   SDValue Res;
6390 
6391   SDNodeFlags Flags;
6392   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6393     Flags.copyFMF(*FPOp);
6394 
6395   switch (Intrinsic) {
6396   default:
6397     // By default, turn this into a target intrinsic node.
6398     visitTargetIntrinsic(I, Intrinsic);
6399     return;
6400   case Intrinsic::vscale: {
6401     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6402     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6403     return;
6404   }
6405   case Intrinsic::vastart:  visitVAStart(I); return;
6406   case Intrinsic::vaend:    visitVAEnd(I); return;
6407   case Intrinsic::vacopy:   visitVACopy(I); return;
6408   case Intrinsic::returnaddress:
6409     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6410                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6411                              getValue(I.getArgOperand(0))));
6412     return;
6413   case Intrinsic::addressofreturnaddress:
6414     setValue(&I,
6415              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6416                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6417     return;
6418   case Intrinsic::sponentry:
6419     setValue(&I,
6420              DAG.getNode(ISD::SPONENTRY, sdl,
6421                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6422     return;
6423   case Intrinsic::frameaddress:
6424     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6425                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6426                              getValue(I.getArgOperand(0))));
6427     return;
6428   case Intrinsic::read_volatile_register:
6429   case Intrinsic::read_register: {
6430     Value *Reg = I.getArgOperand(0);
6431     SDValue Chain = getRoot();
6432     SDValue RegName =
6433         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6434     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6435     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6436       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6437     setValue(&I, Res);
6438     DAG.setRoot(Res.getValue(1));
6439     return;
6440   }
6441   case Intrinsic::write_register: {
6442     Value *Reg = I.getArgOperand(0);
6443     Value *RegValue = I.getArgOperand(1);
6444     SDValue Chain = getRoot();
6445     SDValue RegName =
6446         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6447     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6448                             RegName, getValue(RegValue)));
6449     return;
6450   }
6451   case Intrinsic::memcpy: {
6452     const auto &MCI = cast<MemCpyInst>(I);
6453     SDValue Op1 = getValue(I.getArgOperand(0));
6454     SDValue Op2 = getValue(I.getArgOperand(1));
6455     SDValue Op3 = getValue(I.getArgOperand(2));
6456     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6457     Align DstAlign = MCI.getDestAlign().valueOrOne();
6458     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6459     Align Alignment = std::min(DstAlign, SrcAlign);
6460     bool isVol = MCI.isVolatile();
6461     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6462     // node.
6463     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6464     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6465                                /* AlwaysInline */ false, &I, std::nullopt,
6466                                MachinePointerInfo(I.getArgOperand(0)),
6467                                MachinePointerInfo(I.getArgOperand(1)),
6468                                I.getAAMetadata(), AA);
6469     updateDAGForMaybeTailCall(MC);
6470     return;
6471   }
6472   case Intrinsic::memcpy_inline: {
6473     const auto &MCI = cast<MemCpyInlineInst>(I);
6474     SDValue Dst = getValue(I.getArgOperand(0));
6475     SDValue Src = getValue(I.getArgOperand(1));
6476     SDValue Size = getValue(I.getArgOperand(2));
6477     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6478     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6479     Align DstAlign = MCI.getDestAlign().valueOrOne();
6480     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6481     Align Alignment = std::min(DstAlign, SrcAlign);
6482     bool isVol = MCI.isVolatile();
6483     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6484     // node.
6485     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6486                                /* AlwaysInline */ true, &I, std::nullopt,
6487                                MachinePointerInfo(I.getArgOperand(0)),
6488                                MachinePointerInfo(I.getArgOperand(1)),
6489                                I.getAAMetadata(), AA);
6490     updateDAGForMaybeTailCall(MC);
6491     return;
6492   }
6493   case Intrinsic::memset: {
6494     const auto &MSI = cast<MemSetInst>(I);
6495     SDValue Op1 = getValue(I.getArgOperand(0));
6496     SDValue Op2 = getValue(I.getArgOperand(1));
6497     SDValue Op3 = getValue(I.getArgOperand(2));
6498     // @llvm.memset defines 0 and 1 to both mean no alignment.
6499     Align Alignment = MSI.getDestAlign().valueOrOne();
6500     bool isVol = MSI.isVolatile();
6501     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6502     SDValue MS = DAG.getMemset(
6503         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6504         &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6505     updateDAGForMaybeTailCall(MS);
6506     return;
6507   }
6508   case Intrinsic::memset_inline: {
6509     const auto &MSII = cast<MemSetInlineInst>(I);
6510     SDValue Dst = getValue(I.getArgOperand(0));
6511     SDValue Value = getValue(I.getArgOperand(1));
6512     SDValue Size = getValue(I.getArgOperand(2));
6513     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6514     // @llvm.memset defines 0 and 1 to both mean no alignment.
6515     Align DstAlign = MSII.getDestAlign().valueOrOne();
6516     bool isVol = MSII.isVolatile();
6517     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6518     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6519                                /* AlwaysInline */ true, &I,
6520                                MachinePointerInfo(I.getArgOperand(0)),
6521                                I.getAAMetadata());
6522     updateDAGForMaybeTailCall(MC);
6523     return;
6524   }
6525   case Intrinsic::memmove: {
6526     const auto &MMI = cast<MemMoveInst>(I);
6527     SDValue Op1 = getValue(I.getArgOperand(0));
6528     SDValue Op2 = getValue(I.getArgOperand(1));
6529     SDValue Op3 = getValue(I.getArgOperand(2));
6530     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6531     Align DstAlign = MMI.getDestAlign().valueOrOne();
6532     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6533     Align Alignment = std::min(DstAlign, SrcAlign);
6534     bool isVol = MMI.isVolatile();
6535     // FIXME: Support passing different dest/src alignments to the memmove DAG
6536     // node.
6537     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6538     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I,
6539                                 /* OverrideTailCall */ std::nullopt,
6540                                 MachinePointerInfo(I.getArgOperand(0)),
6541                                 MachinePointerInfo(I.getArgOperand(1)),
6542                                 I.getAAMetadata(), AA);
6543     updateDAGForMaybeTailCall(MM);
6544     return;
6545   }
6546   case Intrinsic::memcpy_element_unordered_atomic: {
6547     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6548     SDValue Dst = getValue(MI.getRawDest());
6549     SDValue Src = getValue(MI.getRawSource());
6550     SDValue Length = getValue(MI.getLength());
6551 
6552     Type *LengthTy = MI.getLength()->getType();
6553     unsigned ElemSz = MI.getElementSizeInBytes();
6554     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6555     SDValue MC =
6556         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6557                             isTC, MachinePointerInfo(MI.getRawDest()),
6558                             MachinePointerInfo(MI.getRawSource()));
6559     updateDAGForMaybeTailCall(MC);
6560     return;
6561   }
6562   case Intrinsic::memmove_element_unordered_atomic: {
6563     auto &MI = cast<AtomicMemMoveInst>(I);
6564     SDValue Dst = getValue(MI.getRawDest());
6565     SDValue Src = getValue(MI.getRawSource());
6566     SDValue Length = getValue(MI.getLength());
6567 
6568     Type *LengthTy = MI.getLength()->getType();
6569     unsigned ElemSz = MI.getElementSizeInBytes();
6570     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6571     SDValue MC =
6572         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6573                              isTC, MachinePointerInfo(MI.getRawDest()),
6574                              MachinePointerInfo(MI.getRawSource()));
6575     updateDAGForMaybeTailCall(MC);
6576     return;
6577   }
6578   case Intrinsic::memset_element_unordered_atomic: {
6579     auto &MI = cast<AtomicMemSetInst>(I);
6580     SDValue Dst = getValue(MI.getRawDest());
6581     SDValue Val = getValue(MI.getValue());
6582     SDValue Length = getValue(MI.getLength());
6583 
6584     Type *LengthTy = MI.getLength()->getType();
6585     unsigned ElemSz = MI.getElementSizeInBytes();
6586     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6587     SDValue MC =
6588         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6589                             isTC, MachinePointerInfo(MI.getRawDest()));
6590     updateDAGForMaybeTailCall(MC);
6591     return;
6592   }
6593   case Intrinsic::call_preallocated_setup: {
6594     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6595     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6596     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6597                               getRoot(), SrcValue);
6598     setValue(&I, Res);
6599     DAG.setRoot(Res);
6600     return;
6601   }
6602   case Intrinsic::call_preallocated_arg: {
6603     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6604     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6605     SDValue Ops[3];
6606     Ops[0] = getRoot();
6607     Ops[1] = SrcValue;
6608     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6609                                    MVT::i32); // arg index
6610     SDValue Res = DAG.getNode(
6611         ISD::PREALLOCATED_ARG, sdl,
6612         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6613     setValue(&I, Res);
6614     DAG.setRoot(Res.getValue(1));
6615     return;
6616   }
6617   case Intrinsic::dbg_declare: {
6618     const auto &DI = cast<DbgDeclareInst>(I);
6619     // Debug intrinsics are handled separately in assignment tracking mode.
6620     // Some intrinsics are handled right after Argument lowering.
6621     if (AssignmentTrackingEnabled ||
6622         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6623       return;
6624     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6625     DILocalVariable *Variable = DI.getVariable();
6626     DIExpression *Expression = DI.getExpression();
6627     dropDanglingDebugInfo(Variable, Expression);
6628     // Assume dbg.declare can not currently use DIArgList, i.e.
6629     // it is non-variadic.
6630     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6631     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6632                        DI.getDebugLoc());
6633     return;
6634   }
6635   case Intrinsic::dbg_label: {
6636     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6637     DILabel *Label = DI.getLabel();
6638     assert(Label && "Missing label");
6639 
6640     SDDbgLabel *SDV;
6641     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6642     DAG.AddDbgLabel(SDV);
6643     return;
6644   }
6645   case Intrinsic::dbg_assign: {
6646     // Debug intrinsics are handled separately in assignment tracking mode.
6647     if (AssignmentTrackingEnabled)
6648       return;
6649     // If assignment tracking hasn't been enabled then fall through and treat
6650     // the dbg.assign as a dbg.value.
6651     [[fallthrough]];
6652   }
6653   case Intrinsic::dbg_value: {
6654     // Debug intrinsics are handled separately in assignment tracking mode.
6655     if (AssignmentTrackingEnabled)
6656       return;
6657     const DbgValueInst &DI = cast<DbgValueInst>(I);
6658     assert(DI.getVariable() && "Missing variable");
6659 
6660     DILocalVariable *Variable = DI.getVariable();
6661     DIExpression *Expression = DI.getExpression();
6662     dropDanglingDebugInfo(Variable, Expression);
6663 
6664     if (DI.isKillLocation()) {
6665       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6666       return;
6667     }
6668 
6669     SmallVector<Value *, 4> Values(DI.getValues());
6670     if (Values.empty())
6671       return;
6672 
6673     bool IsVariadic = DI.hasArgList();
6674     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6675                           SDNodeOrder, IsVariadic))
6676       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6677                            DI.getDebugLoc(), SDNodeOrder);
6678     return;
6679   }
6680 
6681   case Intrinsic::eh_typeid_for: {
6682     // Find the type id for the given typeinfo.
6683     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6684     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6685     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6686     setValue(&I, Res);
6687     return;
6688   }
6689 
6690   case Intrinsic::eh_return_i32:
6691   case Intrinsic::eh_return_i64:
6692     DAG.getMachineFunction().setCallsEHReturn(true);
6693     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6694                             MVT::Other,
6695                             getControlRoot(),
6696                             getValue(I.getArgOperand(0)),
6697                             getValue(I.getArgOperand(1))));
6698     return;
6699   case Intrinsic::eh_unwind_init:
6700     DAG.getMachineFunction().setCallsUnwindInit(true);
6701     return;
6702   case Intrinsic::eh_dwarf_cfa:
6703     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6704                              TLI.getPointerTy(DAG.getDataLayout()),
6705                              getValue(I.getArgOperand(0))));
6706     return;
6707   case Intrinsic::eh_sjlj_callsite: {
6708     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6709     assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6710 
6711     FuncInfo.setCurrentCallSite(CI->getZExtValue());
6712     return;
6713   }
6714   case Intrinsic::eh_sjlj_functioncontext: {
6715     // Get and store the index of the function context.
6716     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6717     AllocaInst *FnCtx =
6718       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6719     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6720     MFI.setFunctionContextIndex(FI);
6721     return;
6722   }
6723   case Intrinsic::eh_sjlj_setjmp: {
6724     SDValue Ops[2];
6725     Ops[0] = getRoot();
6726     Ops[1] = getValue(I.getArgOperand(0));
6727     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6728                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6729     setValue(&I, Op.getValue(0));
6730     DAG.setRoot(Op.getValue(1));
6731     return;
6732   }
6733   case Intrinsic::eh_sjlj_longjmp:
6734     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6735                             getRoot(), getValue(I.getArgOperand(0))));
6736     return;
6737   case Intrinsic::eh_sjlj_setup_dispatch:
6738     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6739                             getRoot()));
6740     return;
6741   case Intrinsic::masked_gather:
6742     visitMaskedGather(I);
6743     return;
6744   case Intrinsic::masked_load:
6745     visitMaskedLoad(I);
6746     return;
6747   case Intrinsic::masked_scatter:
6748     visitMaskedScatter(I);
6749     return;
6750   case Intrinsic::masked_store:
6751     visitMaskedStore(I);
6752     return;
6753   case Intrinsic::masked_expandload:
6754     visitMaskedLoad(I, true /* IsExpanding */);
6755     return;
6756   case Intrinsic::masked_compressstore:
6757     visitMaskedStore(I, true /* IsCompressing */);
6758     return;
6759   case Intrinsic::powi:
6760     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6761                             getValue(I.getArgOperand(1)), DAG));
6762     return;
6763   case Intrinsic::log:
6764     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6765     return;
6766   case Intrinsic::log2:
6767     setValue(&I,
6768              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6769     return;
6770   case Intrinsic::log10:
6771     setValue(&I,
6772              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6773     return;
6774   case Intrinsic::exp:
6775     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6776     return;
6777   case Intrinsic::exp2:
6778     setValue(&I,
6779              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6780     return;
6781   case Intrinsic::pow:
6782     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6783                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6784     return;
6785   case Intrinsic::sqrt:
6786   case Intrinsic::fabs:
6787   case Intrinsic::sin:
6788   case Intrinsic::cos:
6789   case Intrinsic::tan:
6790   case Intrinsic::asin:
6791   case Intrinsic::acos:
6792   case Intrinsic::atan:
6793   case Intrinsic::sinh:
6794   case Intrinsic::cosh:
6795   case Intrinsic::tanh:
6796   case Intrinsic::exp10:
6797   case Intrinsic::floor:
6798   case Intrinsic::ceil:
6799   case Intrinsic::trunc:
6800   case Intrinsic::rint:
6801   case Intrinsic::nearbyint:
6802   case Intrinsic::round:
6803   case Intrinsic::roundeven:
6804   case Intrinsic::canonicalize: {
6805     unsigned Opcode;
6806     // clang-format off
6807     switch (Intrinsic) {
6808     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6809     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6810     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6811     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6812     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6813     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6814     case Intrinsic::asin:         Opcode = ISD::FASIN;         break;
6815     case Intrinsic::acos:         Opcode = ISD::FACOS;         break;
6816     case Intrinsic::atan:         Opcode = ISD::FATAN;         break;
6817     case Intrinsic::sinh:         Opcode = ISD::FSINH;         break;
6818     case Intrinsic::cosh:         Opcode = ISD::FCOSH;         break;
6819     case Intrinsic::tanh:         Opcode = ISD::FTANH;         break;
6820     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6821     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6822     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6823     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6824     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6825     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6826     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6827     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6828     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6829     }
6830     // clang-format on
6831 
6832     setValue(&I, DAG.getNode(Opcode, sdl,
6833                              getValue(I.getArgOperand(0)).getValueType(),
6834                              getValue(I.getArgOperand(0)), Flags));
6835     return;
6836   }
6837   case Intrinsic::lround:
6838   case Intrinsic::llround:
6839   case Intrinsic::lrint:
6840   case Intrinsic::llrint: {
6841     unsigned Opcode;
6842     // clang-format off
6843     switch (Intrinsic) {
6844     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6845     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6846     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6847     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6848     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6849     }
6850     // clang-format on
6851 
6852     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6853     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6854                              getValue(I.getArgOperand(0))));
6855     return;
6856   }
6857   case Intrinsic::minnum:
6858     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6859                              getValue(I.getArgOperand(0)).getValueType(),
6860                              getValue(I.getArgOperand(0)),
6861                              getValue(I.getArgOperand(1)), Flags));
6862     return;
6863   case Intrinsic::maxnum:
6864     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6865                              getValue(I.getArgOperand(0)).getValueType(),
6866                              getValue(I.getArgOperand(0)),
6867                              getValue(I.getArgOperand(1)), Flags));
6868     return;
6869   case Intrinsic::minimum:
6870     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6871                              getValue(I.getArgOperand(0)).getValueType(),
6872                              getValue(I.getArgOperand(0)),
6873                              getValue(I.getArgOperand(1)), Flags));
6874     return;
6875   case Intrinsic::maximum:
6876     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6877                              getValue(I.getArgOperand(0)).getValueType(),
6878                              getValue(I.getArgOperand(0)),
6879                              getValue(I.getArgOperand(1)), Flags));
6880     return;
6881   case Intrinsic::copysign:
6882     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6883                              getValue(I.getArgOperand(0)).getValueType(),
6884                              getValue(I.getArgOperand(0)),
6885                              getValue(I.getArgOperand(1)), Flags));
6886     return;
6887   case Intrinsic::ldexp:
6888     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6889                              getValue(I.getArgOperand(0)).getValueType(),
6890                              getValue(I.getArgOperand(0)),
6891                              getValue(I.getArgOperand(1)), Flags));
6892     return;
6893   case Intrinsic::frexp: {
6894     SmallVector<EVT, 2> ValueVTs;
6895     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6896     SDVTList VTs = DAG.getVTList(ValueVTs);
6897     setValue(&I,
6898              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6899     return;
6900   }
6901   case Intrinsic::arithmetic_fence: {
6902     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6903                              getValue(I.getArgOperand(0)).getValueType(),
6904                              getValue(I.getArgOperand(0)), Flags));
6905     return;
6906   }
6907   case Intrinsic::fma:
6908     setValue(&I, DAG.getNode(
6909                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6910                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6911                      getValue(I.getArgOperand(2)), Flags));
6912     return;
6913 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6914   case Intrinsic::INTRINSIC:
6915 #include "llvm/IR/ConstrainedOps.def"
6916     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6917     return;
6918 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6919 #include "llvm/IR/VPIntrinsics.def"
6920     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6921     return;
6922   case Intrinsic::fptrunc_round: {
6923     // Get the last argument, the metadata and convert it to an integer in the
6924     // call
6925     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6926     std::optional<RoundingMode> RoundMode =
6927         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6928 
6929     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6930 
6931     // Propagate fast-math-flags from IR to node(s).
6932     SDNodeFlags Flags;
6933     Flags.copyFMF(*cast<FPMathOperator>(&I));
6934     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6935 
6936     SDValue Result;
6937     Result = DAG.getNode(
6938         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6939         DAG.getTargetConstant((int)*RoundMode, sdl,
6940                               TLI.getPointerTy(DAG.getDataLayout())));
6941     setValue(&I, Result);
6942 
6943     return;
6944   }
6945   case Intrinsic::fmuladd: {
6946     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6947     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6948         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6949       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6950                                getValue(I.getArgOperand(0)).getValueType(),
6951                                getValue(I.getArgOperand(0)),
6952                                getValue(I.getArgOperand(1)),
6953                                getValue(I.getArgOperand(2)), Flags));
6954     } else {
6955       // TODO: Intrinsic calls should have fast-math-flags.
6956       SDValue Mul = DAG.getNode(
6957           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6958           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6959       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6960                                 getValue(I.getArgOperand(0)).getValueType(),
6961                                 Mul, getValue(I.getArgOperand(2)), Flags);
6962       setValue(&I, Add);
6963     }
6964     return;
6965   }
6966   case Intrinsic::convert_to_fp16:
6967     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6968                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6969                                          getValue(I.getArgOperand(0)),
6970                                          DAG.getTargetConstant(0, sdl,
6971                                                                MVT::i32))));
6972     return;
6973   case Intrinsic::convert_from_fp16:
6974     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6975                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6976                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6977                                          getValue(I.getArgOperand(0)))));
6978     return;
6979   case Intrinsic::fptosi_sat: {
6980     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6981     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
6982                              getValue(I.getArgOperand(0)),
6983                              DAG.getValueType(VT.getScalarType())));
6984     return;
6985   }
6986   case Intrinsic::fptoui_sat: {
6987     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6988     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
6989                              getValue(I.getArgOperand(0)),
6990                              DAG.getValueType(VT.getScalarType())));
6991     return;
6992   }
6993   case Intrinsic::set_rounding:
6994     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
6995                       {getRoot(), getValue(I.getArgOperand(0))});
6996     setValue(&I, Res);
6997     DAG.setRoot(Res.getValue(0));
6998     return;
6999   case Intrinsic::is_fpclass: {
7000     const DataLayout DLayout = DAG.getDataLayout();
7001     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7002     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7003     FPClassTest Test = static_cast<FPClassTest>(
7004         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7005     MachineFunction &MF = DAG.getMachineFunction();
7006     const Function &F = MF.getFunction();
7007     SDValue Op = getValue(I.getArgOperand(0));
7008     SDNodeFlags Flags;
7009     Flags.setNoFPExcept(
7010         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7011     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7012     // expansion can use illegal types. Making expansion early allows
7013     // legalizing these types prior to selection.
7014     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
7015       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7016       setValue(&I, Result);
7017       return;
7018     }
7019 
7020     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7021     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7022     setValue(&I, V);
7023     return;
7024   }
7025   case Intrinsic::get_fpenv: {
7026     const DataLayout DLayout = DAG.getDataLayout();
7027     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7028     Align TempAlign = DAG.getEVTAlign(EnvVT);
7029     SDValue Chain = getRoot();
7030     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7031     // and temporary storage in stack.
7032     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7033       Res = DAG.getNode(
7034           ISD::GET_FPENV, sdl,
7035           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7036                         MVT::Other),
7037           Chain);
7038     } else {
7039       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7040       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7041       auto MPI =
7042           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7043       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7044           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7045           TempAlign);
7046       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7047       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7048     }
7049     setValue(&I, Res);
7050     DAG.setRoot(Res.getValue(1));
7051     return;
7052   }
7053   case Intrinsic::set_fpenv: {
7054     const DataLayout DLayout = DAG.getDataLayout();
7055     SDValue Env = getValue(I.getArgOperand(0));
7056     EVT EnvVT = Env.getValueType();
7057     Align TempAlign = DAG.getEVTAlign(EnvVT);
7058     SDValue Chain = getRoot();
7059     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7060     // environment from memory.
7061     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7062       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7063     } else {
7064       // Allocate space in stack, copy environment bits into it and use this
7065       // memory in SET_FPENV_MEM.
7066       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7067       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7068       auto MPI =
7069           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7070       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7071                            MachineMemOperand::MOStore);
7072       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7073           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7074           TempAlign);
7075       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7076     }
7077     DAG.setRoot(Chain);
7078     return;
7079   }
7080   case Intrinsic::reset_fpenv:
7081     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7082     return;
7083   case Intrinsic::get_fpmode:
7084     Res = DAG.getNode(
7085         ISD::GET_FPMODE, sdl,
7086         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7087                       MVT::Other),
7088         DAG.getRoot());
7089     setValue(&I, Res);
7090     DAG.setRoot(Res.getValue(1));
7091     return;
7092   case Intrinsic::set_fpmode:
7093     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7094                       getValue(I.getArgOperand(0)));
7095     DAG.setRoot(Res);
7096     return;
7097   case Intrinsic::reset_fpmode: {
7098     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7099     DAG.setRoot(Res);
7100     return;
7101   }
7102   case Intrinsic::pcmarker: {
7103     SDValue Tmp = getValue(I.getArgOperand(0));
7104     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7105     return;
7106   }
7107   case Intrinsic::readcyclecounter: {
7108     SDValue Op = getRoot();
7109     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7110                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7111     setValue(&I, Res);
7112     DAG.setRoot(Res.getValue(1));
7113     return;
7114   }
7115   case Intrinsic::readsteadycounter: {
7116     SDValue Op = getRoot();
7117     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7118                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7119     setValue(&I, Res);
7120     DAG.setRoot(Res.getValue(1));
7121     return;
7122   }
7123   case Intrinsic::bitreverse:
7124     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7125                              getValue(I.getArgOperand(0)).getValueType(),
7126                              getValue(I.getArgOperand(0))));
7127     return;
7128   case Intrinsic::bswap:
7129     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7130                              getValue(I.getArgOperand(0)).getValueType(),
7131                              getValue(I.getArgOperand(0))));
7132     return;
7133   case Intrinsic::cttz: {
7134     SDValue Arg = getValue(I.getArgOperand(0));
7135     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7136     EVT Ty = Arg.getValueType();
7137     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7138                              sdl, Ty, Arg));
7139     return;
7140   }
7141   case Intrinsic::ctlz: {
7142     SDValue Arg = getValue(I.getArgOperand(0));
7143     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7144     EVT Ty = Arg.getValueType();
7145     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7146                              sdl, Ty, Arg));
7147     return;
7148   }
7149   case Intrinsic::ctpop: {
7150     SDValue Arg = getValue(I.getArgOperand(0));
7151     EVT Ty = Arg.getValueType();
7152     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7153     return;
7154   }
7155   case Intrinsic::fshl:
7156   case Intrinsic::fshr: {
7157     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7158     SDValue X = getValue(I.getArgOperand(0));
7159     SDValue Y = getValue(I.getArgOperand(1));
7160     SDValue Z = getValue(I.getArgOperand(2));
7161     EVT VT = X.getValueType();
7162 
7163     if (X == Y) {
7164       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7165       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7166     } else {
7167       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7168       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7169     }
7170     return;
7171   }
7172   case Intrinsic::sadd_sat: {
7173     SDValue Op1 = getValue(I.getArgOperand(0));
7174     SDValue Op2 = getValue(I.getArgOperand(1));
7175     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7176     return;
7177   }
7178   case Intrinsic::uadd_sat: {
7179     SDValue Op1 = getValue(I.getArgOperand(0));
7180     SDValue Op2 = getValue(I.getArgOperand(1));
7181     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7182     return;
7183   }
7184   case Intrinsic::ssub_sat: {
7185     SDValue Op1 = getValue(I.getArgOperand(0));
7186     SDValue Op2 = getValue(I.getArgOperand(1));
7187     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7188     return;
7189   }
7190   case Intrinsic::usub_sat: {
7191     SDValue Op1 = getValue(I.getArgOperand(0));
7192     SDValue Op2 = getValue(I.getArgOperand(1));
7193     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7194     return;
7195   }
7196   case Intrinsic::sshl_sat: {
7197     SDValue Op1 = getValue(I.getArgOperand(0));
7198     SDValue Op2 = getValue(I.getArgOperand(1));
7199     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7200     return;
7201   }
7202   case Intrinsic::ushl_sat: {
7203     SDValue Op1 = getValue(I.getArgOperand(0));
7204     SDValue Op2 = getValue(I.getArgOperand(1));
7205     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7206     return;
7207   }
7208   case Intrinsic::smul_fix:
7209   case Intrinsic::umul_fix:
7210   case Intrinsic::smul_fix_sat:
7211   case Intrinsic::umul_fix_sat: {
7212     SDValue Op1 = getValue(I.getArgOperand(0));
7213     SDValue Op2 = getValue(I.getArgOperand(1));
7214     SDValue Op3 = getValue(I.getArgOperand(2));
7215     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7216                              Op1.getValueType(), Op1, Op2, Op3));
7217     return;
7218   }
7219   case Intrinsic::sdiv_fix:
7220   case Intrinsic::udiv_fix:
7221   case Intrinsic::sdiv_fix_sat:
7222   case Intrinsic::udiv_fix_sat: {
7223     SDValue Op1 = getValue(I.getArgOperand(0));
7224     SDValue Op2 = getValue(I.getArgOperand(1));
7225     SDValue Op3 = getValue(I.getArgOperand(2));
7226     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7227                               Op1, Op2, Op3, DAG, TLI));
7228     return;
7229   }
7230   case Intrinsic::smax: {
7231     SDValue Op1 = getValue(I.getArgOperand(0));
7232     SDValue Op2 = getValue(I.getArgOperand(1));
7233     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7234     return;
7235   }
7236   case Intrinsic::smin: {
7237     SDValue Op1 = getValue(I.getArgOperand(0));
7238     SDValue Op2 = getValue(I.getArgOperand(1));
7239     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7240     return;
7241   }
7242   case Intrinsic::umax: {
7243     SDValue Op1 = getValue(I.getArgOperand(0));
7244     SDValue Op2 = getValue(I.getArgOperand(1));
7245     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7246     return;
7247   }
7248   case Intrinsic::umin: {
7249     SDValue Op1 = getValue(I.getArgOperand(0));
7250     SDValue Op2 = getValue(I.getArgOperand(1));
7251     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7252     return;
7253   }
7254   case Intrinsic::abs: {
7255     // TODO: Preserve "int min is poison" arg in SDAG?
7256     SDValue Op1 = getValue(I.getArgOperand(0));
7257     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7258     return;
7259   }
7260   case Intrinsic::scmp: {
7261     SDValue Op1 = getValue(I.getArgOperand(0));
7262     SDValue Op2 = getValue(I.getArgOperand(1));
7263     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7264     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7265     break;
7266   }
7267   case Intrinsic::ucmp: {
7268     SDValue Op1 = getValue(I.getArgOperand(0));
7269     SDValue Op2 = getValue(I.getArgOperand(1));
7270     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7271     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7272     break;
7273   }
7274   case Intrinsic::stacksave: {
7275     SDValue Op = getRoot();
7276     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7277     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7278     setValue(&I, Res);
7279     DAG.setRoot(Res.getValue(1));
7280     return;
7281   }
7282   case Intrinsic::stackrestore:
7283     Res = getValue(I.getArgOperand(0));
7284     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7285     return;
7286   case Intrinsic::get_dynamic_area_offset: {
7287     SDValue Op = getRoot();
7288     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7289     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7290     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7291     // target.
7292     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7293       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7294                          " intrinsic!");
7295     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7296                       Op);
7297     DAG.setRoot(Op);
7298     setValue(&I, Res);
7299     return;
7300   }
7301   case Intrinsic::stackguard: {
7302     MachineFunction &MF = DAG.getMachineFunction();
7303     const Module &M = *MF.getFunction().getParent();
7304     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7305     SDValue Chain = getRoot();
7306     if (TLI.useLoadStackGuardNode()) {
7307       Res = getLoadStackGuard(DAG, sdl, Chain);
7308       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7309     } else {
7310       const Value *Global = TLI.getSDagStackGuard(M);
7311       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7312       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7313                         MachinePointerInfo(Global, 0), Align,
7314                         MachineMemOperand::MOVolatile);
7315     }
7316     if (TLI.useStackGuardXorFP())
7317       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7318     DAG.setRoot(Chain);
7319     setValue(&I, Res);
7320     return;
7321   }
7322   case Intrinsic::stackprotector: {
7323     // Emit code into the DAG to store the stack guard onto the stack.
7324     MachineFunction &MF = DAG.getMachineFunction();
7325     MachineFrameInfo &MFI = MF.getFrameInfo();
7326     SDValue Src, Chain = getRoot();
7327 
7328     if (TLI.useLoadStackGuardNode())
7329       Src = getLoadStackGuard(DAG, sdl, Chain);
7330     else
7331       Src = getValue(I.getArgOperand(0));   // The guard's value.
7332 
7333     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7334 
7335     int FI = FuncInfo.StaticAllocaMap[Slot];
7336     MFI.setStackProtectorIndex(FI);
7337     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7338 
7339     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7340 
7341     // Store the stack protector onto the stack.
7342     Res = DAG.getStore(
7343         Chain, sdl, Src, FIN,
7344         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7345         MaybeAlign(), MachineMemOperand::MOVolatile);
7346     setValue(&I, Res);
7347     DAG.setRoot(Res);
7348     return;
7349   }
7350   case Intrinsic::objectsize:
7351     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7352 
7353   case Intrinsic::is_constant:
7354     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7355 
7356   case Intrinsic::annotation:
7357   case Intrinsic::ptr_annotation:
7358   case Intrinsic::launder_invariant_group:
7359   case Intrinsic::strip_invariant_group:
7360     // Drop the intrinsic, but forward the value
7361     setValue(&I, getValue(I.getOperand(0)));
7362     return;
7363 
7364   case Intrinsic::assume:
7365   case Intrinsic::experimental_noalias_scope_decl:
7366   case Intrinsic::var_annotation:
7367   case Intrinsic::sideeffect:
7368     // Discard annotate attributes, noalias scope declarations, assumptions, and
7369     // artificial side-effects.
7370     return;
7371 
7372   case Intrinsic::codeview_annotation: {
7373     // Emit a label associated with this metadata.
7374     MachineFunction &MF = DAG.getMachineFunction();
7375     MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7376     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7377     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7378     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7379     DAG.setRoot(Res);
7380     return;
7381   }
7382 
7383   case Intrinsic::init_trampoline: {
7384     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7385 
7386     SDValue Ops[6];
7387     Ops[0] = getRoot();
7388     Ops[1] = getValue(I.getArgOperand(0));
7389     Ops[2] = getValue(I.getArgOperand(1));
7390     Ops[3] = getValue(I.getArgOperand(2));
7391     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7392     Ops[5] = DAG.getSrcValue(F);
7393 
7394     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7395 
7396     DAG.setRoot(Res);
7397     return;
7398   }
7399   case Intrinsic::adjust_trampoline:
7400     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7401                              TLI.getPointerTy(DAG.getDataLayout()),
7402                              getValue(I.getArgOperand(0))));
7403     return;
7404   case Intrinsic::gcroot: {
7405     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7406            "only valid in functions with gc specified, enforced by Verifier");
7407     assert(GFI && "implied by previous");
7408     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7409     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7410 
7411     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7412     GFI->addStackRoot(FI->getIndex(), TypeMap);
7413     return;
7414   }
7415   case Intrinsic::gcread:
7416   case Intrinsic::gcwrite:
7417     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7418   case Intrinsic::get_rounding:
7419     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7420     setValue(&I, Res);
7421     DAG.setRoot(Res.getValue(1));
7422     return;
7423 
7424   case Intrinsic::expect:
7425     // Just replace __builtin_expect(exp, c) with EXP.
7426     setValue(&I, getValue(I.getArgOperand(0)));
7427     return;
7428 
7429   case Intrinsic::ubsantrap:
7430   case Intrinsic::debugtrap:
7431   case Intrinsic::trap: {
7432     StringRef TrapFuncName =
7433         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7434     if (TrapFuncName.empty()) {
7435       switch (Intrinsic) {
7436       case Intrinsic::trap:
7437         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7438         break;
7439       case Intrinsic::debugtrap:
7440         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7441         break;
7442       case Intrinsic::ubsantrap:
7443         DAG.setRoot(DAG.getNode(
7444             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7445             DAG.getTargetConstant(
7446                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7447                 MVT::i32)));
7448         break;
7449       default: llvm_unreachable("unknown trap intrinsic");
7450       }
7451       DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7452                              I.hasFnAttr(Attribute::NoMerge));
7453       return;
7454     }
7455     TargetLowering::ArgListTy Args;
7456     if (Intrinsic == Intrinsic::ubsantrap) {
7457       Args.push_back(TargetLoweringBase::ArgListEntry());
7458       Args[0].Val = I.getArgOperand(0);
7459       Args[0].Node = getValue(Args[0].Val);
7460       Args[0].Ty = Args[0].Val->getType();
7461     }
7462 
7463     TargetLowering::CallLoweringInfo CLI(DAG);
7464     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7465         CallingConv::C, I.getType(),
7466         DAG.getExternalSymbol(TrapFuncName.data(),
7467                               TLI.getPointerTy(DAG.getDataLayout())),
7468         std::move(Args));
7469     CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7470     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7471     DAG.setRoot(Result.second);
7472     return;
7473   }
7474 
7475   case Intrinsic::allow_runtime_check:
7476   case Intrinsic::allow_ubsan_check:
7477     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7478     return;
7479 
7480   case Intrinsic::uadd_with_overflow:
7481   case Intrinsic::sadd_with_overflow:
7482   case Intrinsic::usub_with_overflow:
7483   case Intrinsic::ssub_with_overflow:
7484   case Intrinsic::umul_with_overflow:
7485   case Intrinsic::smul_with_overflow: {
7486     ISD::NodeType Op;
7487     switch (Intrinsic) {
7488     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7489     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7490     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7491     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7492     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7493     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7494     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7495     }
7496     SDValue Op1 = getValue(I.getArgOperand(0));
7497     SDValue Op2 = getValue(I.getArgOperand(1));
7498 
7499     EVT ResultVT = Op1.getValueType();
7500     EVT OverflowVT = MVT::i1;
7501     if (ResultVT.isVector())
7502       OverflowVT = EVT::getVectorVT(
7503           *Context, OverflowVT, ResultVT.getVectorElementCount());
7504 
7505     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7506     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7507     return;
7508   }
7509   case Intrinsic::prefetch: {
7510     SDValue Ops[5];
7511     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7512     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7513     Ops[0] = DAG.getRoot();
7514     Ops[1] = getValue(I.getArgOperand(0));
7515     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7516                                    MVT::i32);
7517     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7518                                    MVT::i32);
7519     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7520                                    MVT::i32);
7521     SDValue Result = DAG.getMemIntrinsicNode(
7522         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7523         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7524         /* align */ std::nullopt, Flags);
7525 
7526     // Chain the prefetch in parallel with any pending loads, to stay out of
7527     // the way of later optimizations.
7528     PendingLoads.push_back(Result);
7529     Result = getRoot();
7530     DAG.setRoot(Result);
7531     return;
7532   }
7533   case Intrinsic::lifetime_start:
7534   case Intrinsic::lifetime_end: {
7535     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7536     // Stack coloring is not enabled in O0, discard region information.
7537     if (TM.getOptLevel() == CodeGenOptLevel::None)
7538       return;
7539 
7540     const int64_t ObjectSize =
7541         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7542     Value *const ObjectPtr = I.getArgOperand(1);
7543     SmallVector<const Value *, 4> Allocas;
7544     getUnderlyingObjects(ObjectPtr, Allocas);
7545 
7546     for (const Value *Alloca : Allocas) {
7547       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7548 
7549       // Could not find an Alloca.
7550       if (!LifetimeObject)
7551         continue;
7552 
7553       // First check that the Alloca is static, otherwise it won't have a
7554       // valid frame index.
7555       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7556       if (SI == FuncInfo.StaticAllocaMap.end())
7557         return;
7558 
7559       const int FrameIndex = SI->second;
7560       int64_t Offset;
7561       if (GetPointerBaseWithConstantOffset(
7562               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7563         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7564       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7565                                 Offset);
7566       DAG.setRoot(Res);
7567     }
7568     return;
7569   }
7570   case Intrinsic::pseudoprobe: {
7571     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7572     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7573     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7574     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7575     DAG.setRoot(Res);
7576     return;
7577   }
7578   case Intrinsic::invariant_start:
7579     // Discard region information.
7580     setValue(&I,
7581              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7582     return;
7583   case Intrinsic::invariant_end:
7584     // Discard region information.
7585     return;
7586   case Intrinsic::clear_cache: {
7587     SDValue InputChain = DAG.getRoot();
7588     SDValue StartVal = getValue(I.getArgOperand(0));
7589     SDValue EndVal = getValue(I.getArgOperand(1));
7590     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7591                       {InputChain, StartVal, EndVal});
7592     setValue(&I, Res);
7593     DAG.setRoot(Res);
7594     return;
7595   }
7596   case Intrinsic::donothing:
7597   case Intrinsic::seh_try_begin:
7598   case Intrinsic::seh_scope_begin:
7599   case Intrinsic::seh_try_end:
7600   case Intrinsic::seh_scope_end:
7601     // ignore
7602     return;
7603   case Intrinsic::experimental_stackmap:
7604     visitStackmap(I);
7605     return;
7606   case Intrinsic::experimental_patchpoint_void:
7607   case Intrinsic::experimental_patchpoint:
7608     visitPatchpoint(I);
7609     return;
7610   case Intrinsic::experimental_gc_statepoint:
7611     LowerStatepoint(cast<GCStatepointInst>(I));
7612     return;
7613   case Intrinsic::experimental_gc_result:
7614     visitGCResult(cast<GCResultInst>(I));
7615     return;
7616   case Intrinsic::experimental_gc_relocate:
7617     visitGCRelocate(cast<GCRelocateInst>(I));
7618     return;
7619   case Intrinsic::instrprof_cover:
7620     llvm_unreachable("instrprof failed to lower a cover");
7621   case Intrinsic::instrprof_increment:
7622     llvm_unreachable("instrprof failed to lower an increment");
7623   case Intrinsic::instrprof_timestamp:
7624     llvm_unreachable("instrprof failed to lower a timestamp");
7625   case Intrinsic::instrprof_value_profile:
7626     llvm_unreachable("instrprof failed to lower a value profiling call");
7627   case Intrinsic::instrprof_mcdc_parameters:
7628     llvm_unreachable("instrprof failed to lower mcdc parameters");
7629   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7630     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7631   case Intrinsic::localescape: {
7632     MachineFunction &MF = DAG.getMachineFunction();
7633     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7634 
7635     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7636     // is the same on all targets.
7637     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7638       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7639       if (isa<ConstantPointerNull>(Arg))
7640         continue; // Skip null pointers. They represent a hole in index space.
7641       AllocaInst *Slot = cast<AllocaInst>(Arg);
7642       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7643              "can only escape static allocas");
7644       int FI = FuncInfo.StaticAllocaMap[Slot];
7645       MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7646           GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7647       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7648               TII->get(TargetOpcode::LOCAL_ESCAPE))
7649           .addSym(FrameAllocSym)
7650           .addFrameIndex(FI);
7651     }
7652 
7653     return;
7654   }
7655 
7656   case Intrinsic::localrecover: {
7657     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7658     MachineFunction &MF = DAG.getMachineFunction();
7659 
7660     // Get the symbol that defines the frame offset.
7661     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7662     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7663     unsigned IdxVal =
7664         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7665     MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7666         GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7667 
7668     Value *FP = I.getArgOperand(1);
7669     SDValue FPVal = getValue(FP);
7670     EVT PtrVT = FPVal.getValueType();
7671 
7672     // Create a MCSymbol for the label to avoid any target lowering
7673     // that would make this PC relative.
7674     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7675     SDValue OffsetVal =
7676         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7677 
7678     // Add the offset to the FP.
7679     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7680     setValue(&I, Add);
7681 
7682     return;
7683   }
7684 
7685   case Intrinsic::eh_exceptionpointer:
7686   case Intrinsic::eh_exceptioncode: {
7687     // Get the exception pointer vreg, copy from it, and resize it to fit.
7688     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7689     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7690     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7691     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7692     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7693     if (Intrinsic == Intrinsic::eh_exceptioncode)
7694       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7695     setValue(&I, N);
7696     return;
7697   }
7698   case Intrinsic::xray_customevent: {
7699     // Here we want to make sure that the intrinsic behaves as if it has a
7700     // specific calling convention.
7701     const auto &Triple = DAG.getTarget().getTargetTriple();
7702     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7703       return;
7704 
7705     SmallVector<SDValue, 8> Ops;
7706 
7707     // We want to say that we always want the arguments in registers.
7708     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7709     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7710     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7711     SDValue Chain = getRoot();
7712     Ops.push_back(LogEntryVal);
7713     Ops.push_back(StrSizeVal);
7714     Ops.push_back(Chain);
7715 
7716     // We need to enforce the calling convention for the callsite, so that
7717     // argument ordering is enforced correctly, and that register allocation can
7718     // see that some registers may be assumed clobbered and have to preserve
7719     // them across calls to the intrinsic.
7720     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7721                                            sdl, NodeTys, Ops);
7722     SDValue patchableNode = SDValue(MN, 0);
7723     DAG.setRoot(patchableNode);
7724     setValue(&I, patchableNode);
7725     return;
7726   }
7727   case Intrinsic::xray_typedevent: {
7728     // Here we want to make sure that the intrinsic behaves as if it has a
7729     // specific calling convention.
7730     const auto &Triple = DAG.getTarget().getTargetTriple();
7731     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7732       return;
7733 
7734     SmallVector<SDValue, 8> Ops;
7735 
7736     // We want to say that we always want the arguments in registers.
7737     // It's unclear to me how manipulating the selection DAG here forces callers
7738     // to provide arguments in registers instead of on the stack.
7739     SDValue LogTypeId = getValue(I.getArgOperand(0));
7740     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7741     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7742     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7743     SDValue Chain = getRoot();
7744     Ops.push_back(LogTypeId);
7745     Ops.push_back(LogEntryVal);
7746     Ops.push_back(StrSizeVal);
7747     Ops.push_back(Chain);
7748 
7749     // We need to enforce the calling convention for the callsite, so that
7750     // argument ordering is enforced correctly, and that register allocation can
7751     // see that some registers may be assumed clobbered and have to preserve
7752     // them across calls to the intrinsic.
7753     MachineSDNode *MN = DAG.getMachineNode(
7754         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7755     SDValue patchableNode = SDValue(MN, 0);
7756     DAG.setRoot(patchableNode);
7757     setValue(&I, patchableNode);
7758     return;
7759   }
7760   case Intrinsic::experimental_deoptimize:
7761     LowerDeoptimizeCall(&I);
7762     return;
7763   case Intrinsic::experimental_stepvector:
7764     visitStepVector(I);
7765     return;
7766   case Intrinsic::vector_reduce_fadd:
7767   case Intrinsic::vector_reduce_fmul:
7768   case Intrinsic::vector_reduce_add:
7769   case Intrinsic::vector_reduce_mul:
7770   case Intrinsic::vector_reduce_and:
7771   case Intrinsic::vector_reduce_or:
7772   case Intrinsic::vector_reduce_xor:
7773   case Intrinsic::vector_reduce_smax:
7774   case Intrinsic::vector_reduce_smin:
7775   case Intrinsic::vector_reduce_umax:
7776   case Intrinsic::vector_reduce_umin:
7777   case Intrinsic::vector_reduce_fmax:
7778   case Intrinsic::vector_reduce_fmin:
7779   case Intrinsic::vector_reduce_fmaximum:
7780   case Intrinsic::vector_reduce_fminimum:
7781     visitVectorReduce(I, Intrinsic);
7782     return;
7783 
7784   case Intrinsic::icall_branch_funnel: {
7785     SmallVector<SDValue, 16> Ops;
7786     Ops.push_back(getValue(I.getArgOperand(0)));
7787 
7788     int64_t Offset;
7789     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7790         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7791     if (!Base)
7792       report_fatal_error(
7793           "llvm.icall.branch.funnel operand must be a GlobalValue");
7794     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7795 
7796     struct BranchFunnelTarget {
7797       int64_t Offset;
7798       SDValue Target;
7799     };
7800     SmallVector<BranchFunnelTarget, 8> Targets;
7801 
7802     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7803       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7804           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7805       if (ElemBase != Base)
7806         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7807                            "to the same GlobalValue");
7808 
7809       SDValue Val = getValue(I.getArgOperand(Op + 1));
7810       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7811       if (!GA)
7812         report_fatal_error(
7813             "llvm.icall.branch.funnel operand must be a GlobalValue");
7814       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7815                                      GA->getGlobal(), sdl, Val.getValueType(),
7816                                      GA->getOffset())});
7817     }
7818     llvm::sort(Targets,
7819                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7820                  return T1.Offset < T2.Offset;
7821                });
7822 
7823     for (auto &T : Targets) {
7824       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7825       Ops.push_back(T.Target);
7826     }
7827 
7828     Ops.push_back(DAG.getRoot()); // Chain
7829     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7830                                  MVT::Other, Ops),
7831               0);
7832     DAG.setRoot(N);
7833     setValue(&I, N);
7834     HasTailCall = true;
7835     return;
7836   }
7837 
7838   case Intrinsic::wasm_landingpad_index:
7839     // Information this intrinsic contained has been transferred to
7840     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7841     // delete it now.
7842     return;
7843 
7844   case Intrinsic::aarch64_settag:
7845   case Intrinsic::aarch64_settag_zero: {
7846     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7847     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7848     SDValue Val = TSI.EmitTargetCodeForSetTag(
7849         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7850         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7851         ZeroMemory);
7852     DAG.setRoot(Val);
7853     setValue(&I, Val);
7854     return;
7855   }
7856   case Intrinsic::amdgcn_cs_chain: {
7857     assert(I.arg_size() == 5 && "Additional args not supported yet");
7858     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7859            "Non-zero flags not supported yet");
7860 
7861     // At this point we don't care if it's amdgpu_cs_chain or
7862     // amdgpu_cs_chain_preserve.
7863     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7864 
7865     Type *RetTy = I.getType();
7866     assert(RetTy->isVoidTy() && "Should not return");
7867 
7868     SDValue Callee = getValue(I.getOperand(0));
7869 
7870     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7871     // We'll also tack the value of the EXEC mask at the end.
7872     TargetLowering::ArgListTy Args;
7873     Args.reserve(3);
7874 
7875     for (unsigned Idx : {2, 3, 1}) {
7876       TargetLowering::ArgListEntry Arg;
7877       Arg.Node = getValue(I.getOperand(Idx));
7878       Arg.Ty = I.getOperand(Idx)->getType();
7879       Arg.setAttributes(&I, Idx);
7880       Args.push_back(Arg);
7881     }
7882 
7883     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7884     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7885     Args[2].IsInReg = true; // EXEC should be inreg
7886 
7887     TargetLowering::CallLoweringInfo CLI(DAG);
7888     CLI.setDebugLoc(getCurSDLoc())
7889         .setChain(getRoot())
7890         .setCallee(CC, RetTy, Callee, std::move(Args))
7891         .setNoReturn(true)
7892         .setTailCall(true)
7893         .setConvergent(I.isConvergent());
7894     CLI.CB = &I;
7895     std::pair<SDValue, SDValue> Result =
7896         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7897     (void)Result;
7898     assert(!Result.first.getNode() && !Result.second.getNode() &&
7899            "Should've lowered as tail call");
7900 
7901     HasTailCall = true;
7902     return;
7903   }
7904   case Intrinsic::ptrmask: {
7905     SDValue Ptr = getValue(I.getOperand(0));
7906     SDValue Mask = getValue(I.getOperand(1));
7907 
7908     // On arm64_32, pointers are 32 bits when stored in memory, but
7909     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
7910     // match the index type, but the pointer is 64 bits, so the the mask must be
7911     // zero-extended up to 64 bits to match the pointer.
7912     EVT PtrVT =
7913         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7914     EVT MemVT =
7915         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7916     assert(PtrVT == Ptr.getValueType());
7917     assert(MemVT == Mask.getValueType());
7918     if (MemVT != PtrVT)
7919       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
7920 
7921     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7922     return;
7923   }
7924   case Intrinsic::threadlocal_address: {
7925     setValue(&I, getValue(I.getOperand(0)));
7926     return;
7927   }
7928   case Intrinsic::get_active_lane_mask: {
7929     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7930     SDValue Index = getValue(I.getOperand(0));
7931     EVT ElementVT = Index.getValueType();
7932 
7933     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7934       visitTargetIntrinsic(I, Intrinsic);
7935       return;
7936     }
7937 
7938     SDValue TripCount = getValue(I.getOperand(1));
7939     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7940                                  CCVT.getVectorElementCount());
7941 
7942     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7943     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7944     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7945     SDValue VectorInduction = DAG.getNode(
7946         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7947     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7948                                  VectorTripCount, ISD::CondCode::SETULT);
7949     setValue(&I, SetCC);
7950     return;
7951   }
7952   case Intrinsic::experimental_get_vector_length: {
7953     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7954            "Expected positive VF");
7955     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7956     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7957 
7958     SDValue Count = getValue(I.getOperand(0));
7959     EVT CountVT = Count.getValueType();
7960 
7961     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7962       visitTargetIntrinsic(I, Intrinsic);
7963       return;
7964     }
7965 
7966     // Expand to a umin between the trip count and the maximum elements the type
7967     // can hold.
7968     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7969 
7970     // Extend the trip count to at least the result VT.
7971     if (CountVT.bitsLT(VT)) {
7972       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7973       CountVT = VT;
7974     }
7975 
7976     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7977                                          ElementCount::get(VF, IsScalable));
7978 
7979     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
7980     // Clip to the result type if needed.
7981     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
7982 
7983     setValue(&I, Trunc);
7984     return;
7985   }
7986   case Intrinsic::experimental_vector_partial_reduce_add: {
7987     SDValue OpNode = getValue(I.getOperand(1));
7988     EVT ReducedTy = EVT::getEVT(I.getType());
7989     EVT FullTy = OpNode.getValueType();
7990 
7991     unsigned Stride = ReducedTy.getVectorMinNumElements();
7992     unsigned ScaleFactor = FullTy.getVectorMinNumElements() / Stride;
7993 
7994     // Collect all of the subvectors
7995     std::deque<SDValue> Subvectors;
7996     Subvectors.push_back(getValue(I.getOperand(0)));
7997     for (unsigned i = 0; i < ScaleFactor; i++) {
7998       auto SourceIndex = DAG.getVectorIdxConstant(i * Stride, sdl);
7999       Subvectors.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ReducedTy,
8000                                        {OpNode, SourceIndex}));
8001     }
8002 
8003     // Flatten the subvector tree
8004     while (Subvectors.size() > 1) {
8005       Subvectors.push_back(DAG.getNode(ISD::ADD, sdl, ReducedTy,
8006                                        {Subvectors[0], Subvectors[1]}));
8007       Subvectors.pop_front();
8008       Subvectors.pop_front();
8009     }
8010 
8011     assert(Subvectors.size() == 1 &&
8012            "There should only be one subvector after tree flattening");
8013 
8014     setValue(&I, Subvectors[0]);
8015     return;
8016   }
8017   case Intrinsic::experimental_cttz_elts: {
8018     auto DL = getCurSDLoc();
8019     SDValue Op = getValue(I.getOperand(0));
8020     EVT OpVT = Op.getValueType();
8021 
8022     if (!TLI.shouldExpandCttzElements(OpVT)) {
8023       visitTargetIntrinsic(I, Intrinsic);
8024       return;
8025     }
8026 
8027     if (OpVT.getScalarType() != MVT::i1) {
8028       // Compare the input vector elements to zero & use to count trailing zeros
8029       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8030       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8031                               OpVT.getVectorElementCount());
8032       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8033     }
8034 
8035     // If the zero-is-poison flag is set, we can assume the upper limit
8036     // of the result is VF-1.
8037     bool ZeroIsPoison =
8038         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8039     ConstantRange VScaleRange(1, true); // Dummy value.
8040     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8041       VScaleRange = getVScaleRange(I.getCaller(), 64);
8042     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8043         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8044 
8045     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8046 
8047     // Create the new vector type & get the vector length
8048     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8049                                  OpVT.getVectorElementCount());
8050 
8051     SDValue VL =
8052         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8053 
8054     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8055     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8056     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8057     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8058     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8059     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8060     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8061 
8062     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8063     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8064 
8065     setValue(&I, Ret);
8066     return;
8067   }
8068   case Intrinsic::vector_insert: {
8069     SDValue Vec = getValue(I.getOperand(0));
8070     SDValue SubVec = getValue(I.getOperand(1));
8071     SDValue Index = getValue(I.getOperand(2));
8072 
8073     // The intrinsic's index type is i64, but the SDNode requires an index type
8074     // suitable for the target. Convert the index as required.
8075     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8076     if (Index.getValueType() != VectorIdxTy)
8077       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8078 
8079     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8080     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8081                              Index));
8082     return;
8083   }
8084   case Intrinsic::vector_extract: {
8085     SDValue Vec = getValue(I.getOperand(0));
8086     SDValue Index = getValue(I.getOperand(1));
8087     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8088 
8089     // The intrinsic's index type is i64, but the SDNode requires an index type
8090     // suitable for the target. Convert the index as required.
8091     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8092     if (Index.getValueType() != VectorIdxTy)
8093       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8094 
8095     setValue(&I,
8096              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8097     return;
8098   }
8099   case Intrinsic::vector_reverse:
8100     visitVectorReverse(I);
8101     return;
8102   case Intrinsic::vector_splice:
8103     visitVectorSplice(I);
8104     return;
8105   case Intrinsic::callbr_landingpad:
8106     visitCallBrLandingPad(I);
8107     return;
8108   case Intrinsic::vector_interleave2:
8109     visitVectorInterleave(I);
8110     return;
8111   case Intrinsic::vector_deinterleave2:
8112     visitVectorDeinterleave(I);
8113     return;
8114   case Intrinsic::experimental_vector_compress:
8115     setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8116                              getValue(I.getArgOperand(0)).getValueType(),
8117                              getValue(I.getArgOperand(0)),
8118                              getValue(I.getArgOperand(1)),
8119                              getValue(I.getArgOperand(2)), Flags));
8120     return;
8121   case Intrinsic::experimental_convergence_anchor:
8122   case Intrinsic::experimental_convergence_entry:
8123   case Intrinsic::experimental_convergence_loop:
8124     visitConvergenceControl(I, Intrinsic);
8125     return;
8126   case Intrinsic::experimental_vector_histogram_add: {
8127     visitVectorHistogram(I, Intrinsic);
8128     return;
8129   }
8130   }
8131 }
8132 
8133 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8134     const ConstrainedFPIntrinsic &FPI) {
8135   SDLoc sdl = getCurSDLoc();
8136 
8137   // We do not need to serialize constrained FP intrinsics against
8138   // each other or against (nonvolatile) loads, so they can be
8139   // chained like loads.
8140   SDValue Chain = DAG.getRoot();
8141   SmallVector<SDValue, 4> Opers;
8142   Opers.push_back(Chain);
8143   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8144     Opers.push_back(getValue(FPI.getArgOperand(I)));
8145 
8146   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8147     assert(Result.getNode()->getNumValues() == 2);
8148 
8149     // Push node to the appropriate list so that future instructions can be
8150     // chained up correctly.
8151     SDValue OutChain = Result.getValue(1);
8152     switch (EB) {
8153     case fp::ExceptionBehavior::ebIgnore:
8154       // The only reason why ebIgnore nodes still need to be chained is that
8155       // they might depend on the current rounding mode, and therefore must
8156       // not be moved across instruction that may change that mode.
8157       [[fallthrough]];
8158     case fp::ExceptionBehavior::ebMayTrap:
8159       // These must not be moved across calls or instructions that may change
8160       // floating-point exception masks.
8161       PendingConstrainedFP.push_back(OutChain);
8162       break;
8163     case fp::ExceptionBehavior::ebStrict:
8164       // These must not be moved across calls or instructions that may change
8165       // floating-point exception masks or read floating-point exception flags.
8166       // In addition, they cannot be optimized out even if unused.
8167       PendingConstrainedFPStrict.push_back(OutChain);
8168       break;
8169     }
8170   };
8171 
8172   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8173   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8174   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8175   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8176 
8177   SDNodeFlags Flags;
8178   if (EB == fp::ExceptionBehavior::ebIgnore)
8179     Flags.setNoFPExcept(true);
8180 
8181   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8182     Flags.copyFMF(*FPOp);
8183 
8184   unsigned Opcode;
8185   switch (FPI.getIntrinsicID()) {
8186   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8187 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8188   case Intrinsic::INTRINSIC:                                                   \
8189     Opcode = ISD::STRICT_##DAGN;                                               \
8190     break;
8191 #include "llvm/IR/ConstrainedOps.def"
8192   case Intrinsic::experimental_constrained_fmuladd: {
8193     Opcode = ISD::STRICT_FMA;
8194     // Break fmuladd into fmul and fadd.
8195     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8196         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8197       Opers.pop_back();
8198       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8199       pushOutChain(Mul, EB);
8200       Opcode = ISD::STRICT_FADD;
8201       Opers.clear();
8202       Opers.push_back(Mul.getValue(1));
8203       Opers.push_back(Mul.getValue(0));
8204       Opers.push_back(getValue(FPI.getArgOperand(2)));
8205     }
8206     break;
8207   }
8208   }
8209 
8210   // A few strict DAG nodes carry additional operands that are not
8211   // set up by the default code above.
8212   switch (Opcode) {
8213   default: break;
8214   case ISD::STRICT_FP_ROUND:
8215     Opers.push_back(
8216         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8217     break;
8218   case ISD::STRICT_FSETCC:
8219   case ISD::STRICT_FSETCCS: {
8220     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8221     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8222     if (TM.Options.NoNaNsFPMath)
8223       Condition = getFCmpCodeWithoutNaN(Condition);
8224     Opers.push_back(DAG.getCondCode(Condition));
8225     break;
8226   }
8227   }
8228 
8229   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8230   pushOutChain(Result, EB);
8231 
8232   SDValue FPResult = Result.getValue(0);
8233   setValue(&FPI, FPResult);
8234 }
8235 
8236 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8237   std::optional<unsigned> ResOPC;
8238   switch (VPIntrin.getIntrinsicID()) {
8239   case Intrinsic::vp_ctlz: {
8240     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8241     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8242     break;
8243   }
8244   case Intrinsic::vp_cttz: {
8245     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8246     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8247     break;
8248   }
8249   case Intrinsic::vp_cttz_elts: {
8250     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8251     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8252     break;
8253   }
8254 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8255   case Intrinsic::VPID:                                                        \
8256     ResOPC = ISD::VPSD;                                                        \
8257     break;
8258 #include "llvm/IR/VPIntrinsics.def"
8259   }
8260 
8261   if (!ResOPC)
8262     llvm_unreachable(
8263         "Inconsistency: no SDNode available for this VPIntrinsic!");
8264 
8265   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8266       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8267     if (VPIntrin.getFastMathFlags().allowReassoc())
8268       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8269                                                 : ISD::VP_REDUCE_FMUL;
8270   }
8271 
8272   return *ResOPC;
8273 }
8274 
8275 void SelectionDAGBuilder::visitVPLoad(
8276     const VPIntrinsic &VPIntrin, EVT VT,
8277     const SmallVectorImpl<SDValue> &OpValues) {
8278   SDLoc DL = getCurSDLoc();
8279   Value *PtrOperand = VPIntrin.getArgOperand(0);
8280   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8281   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8282   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8283   SDValue LD;
8284   // Do not serialize variable-length loads of constant memory with
8285   // anything.
8286   if (!Alignment)
8287     Alignment = DAG.getEVTAlign(VT);
8288   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8289   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8290   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8291   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8292       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8293       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8294   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8295                      MMO, false /*IsExpanding */);
8296   if (AddToChain)
8297     PendingLoads.push_back(LD.getValue(1));
8298   setValue(&VPIntrin, LD);
8299 }
8300 
8301 void SelectionDAGBuilder::visitVPGather(
8302     const VPIntrinsic &VPIntrin, EVT VT,
8303     const SmallVectorImpl<SDValue> &OpValues) {
8304   SDLoc DL = getCurSDLoc();
8305   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8306   Value *PtrOperand = VPIntrin.getArgOperand(0);
8307   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8308   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8309   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8310   SDValue LD;
8311   if (!Alignment)
8312     Alignment = DAG.getEVTAlign(VT.getScalarType());
8313   unsigned AS =
8314     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8315   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8316       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8317       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8318   SDValue Base, Index, Scale;
8319   ISD::MemIndexType IndexType;
8320   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8321                                     this, VPIntrin.getParent(),
8322                                     VT.getScalarStoreSize());
8323   if (!UniformBase) {
8324     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8325     Index = getValue(PtrOperand);
8326     IndexType = ISD::SIGNED_SCALED;
8327     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8328   }
8329   EVT IdxVT = Index.getValueType();
8330   EVT EltTy = IdxVT.getVectorElementType();
8331   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8332     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8333     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8334   }
8335   LD = DAG.getGatherVP(
8336       DAG.getVTList(VT, MVT::Other), VT, DL,
8337       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8338       IndexType);
8339   PendingLoads.push_back(LD.getValue(1));
8340   setValue(&VPIntrin, LD);
8341 }
8342 
8343 void SelectionDAGBuilder::visitVPStore(
8344     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8345   SDLoc DL = getCurSDLoc();
8346   Value *PtrOperand = VPIntrin.getArgOperand(1);
8347   EVT VT = OpValues[0].getValueType();
8348   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8349   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8350   SDValue ST;
8351   if (!Alignment)
8352     Alignment = DAG.getEVTAlign(VT);
8353   SDValue Ptr = OpValues[1];
8354   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8355   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8356       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8357       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8358   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8359                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8360                       /* IsTruncating */ false, /*IsCompressing*/ false);
8361   DAG.setRoot(ST);
8362   setValue(&VPIntrin, ST);
8363 }
8364 
8365 void SelectionDAGBuilder::visitVPScatter(
8366     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8367   SDLoc DL = getCurSDLoc();
8368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8369   Value *PtrOperand = VPIntrin.getArgOperand(1);
8370   EVT VT = OpValues[0].getValueType();
8371   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8372   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8373   SDValue ST;
8374   if (!Alignment)
8375     Alignment = DAG.getEVTAlign(VT.getScalarType());
8376   unsigned AS =
8377       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8378   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8379       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8380       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8381   SDValue Base, Index, Scale;
8382   ISD::MemIndexType IndexType;
8383   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8384                                     this, VPIntrin.getParent(),
8385                                     VT.getScalarStoreSize());
8386   if (!UniformBase) {
8387     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8388     Index = getValue(PtrOperand);
8389     IndexType = ISD::SIGNED_SCALED;
8390     Scale =
8391       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8392   }
8393   EVT IdxVT = Index.getValueType();
8394   EVT EltTy = IdxVT.getVectorElementType();
8395   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8396     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8397     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8398   }
8399   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8400                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8401                          OpValues[2], OpValues[3]},
8402                         MMO, IndexType);
8403   DAG.setRoot(ST);
8404   setValue(&VPIntrin, ST);
8405 }
8406 
8407 void SelectionDAGBuilder::visitVPStridedLoad(
8408     const VPIntrinsic &VPIntrin, EVT VT,
8409     const SmallVectorImpl<SDValue> &OpValues) {
8410   SDLoc DL = getCurSDLoc();
8411   Value *PtrOperand = VPIntrin.getArgOperand(0);
8412   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8413   if (!Alignment)
8414     Alignment = DAG.getEVTAlign(VT.getScalarType());
8415   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8416   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8417   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8418   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8419   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8420   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8421   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8422       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8423       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8424 
8425   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8426                                     OpValues[2], OpValues[3], MMO,
8427                                     false /*IsExpanding*/);
8428 
8429   if (AddToChain)
8430     PendingLoads.push_back(LD.getValue(1));
8431   setValue(&VPIntrin, LD);
8432 }
8433 
8434 void SelectionDAGBuilder::visitVPStridedStore(
8435     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8436   SDLoc DL = getCurSDLoc();
8437   Value *PtrOperand = VPIntrin.getArgOperand(1);
8438   EVT VT = OpValues[0].getValueType();
8439   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8440   if (!Alignment)
8441     Alignment = DAG.getEVTAlign(VT.getScalarType());
8442   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8443   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8444   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8445       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8446       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8447 
8448   SDValue ST = DAG.getStridedStoreVP(
8449       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8450       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8451       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8452       /*IsCompressing*/ false);
8453 
8454   DAG.setRoot(ST);
8455   setValue(&VPIntrin, ST);
8456 }
8457 
8458 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8459   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8460   SDLoc DL = getCurSDLoc();
8461 
8462   ISD::CondCode Condition;
8463   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8464   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8465   if (IsFP) {
8466     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8467     // flags, but calls that don't return floating-point types can't be
8468     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8469     Condition = getFCmpCondCode(CondCode);
8470     if (TM.Options.NoNaNsFPMath)
8471       Condition = getFCmpCodeWithoutNaN(Condition);
8472   } else {
8473     Condition = getICmpCondCode(CondCode);
8474   }
8475 
8476   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8477   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8478   // #2 is the condition code
8479   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8480   SDValue EVL = getValue(VPIntrin.getOperand(4));
8481   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8482   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8483          "Unexpected target EVL type");
8484   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8485 
8486   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8487                                                         VPIntrin.getType());
8488   setValue(&VPIntrin,
8489            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8490 }
8491 
8492 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8493     const VPIntrinsic &VPIntrin) {
8494   SDLoc DL = getCurSDLoc();
8495   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8496 
8497   auto IID = VPIntrin.getIntrinsicID();
8498 
8499   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8500     return visitVPCmp(*CmpI);
8501 
8502   SmallVector<EVT, 4> ValueVTs;
8503   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8504   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8505   SDVTList VTs = DAG.getVTList(ValueVTs);
8506 
8507   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8508 
8509   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8510   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8511          "Unexpected target EVL type");
8512 
8513   // Request operands.
8514   SmallVector<SDValue, 7> OpValues;
8515   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8516     auto Op = getValue(VPIntrin.getArgOperand(I));
8517     if (I == EVLParamPos)
8518       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8519     OpValues.push_back(Op);
8520   }
8521 
8522   switch (Opcode) {
8523   default: {
8524     SDNodeFlags SDFlags;
8525     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8526       SDFlags.copyFMF(*FPMO);
8527     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8528     setValue(&VPIntrin, Result);
8529     break;
8530   }
8531   case ISD::VP_LOAD:
8532     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8533     break;
8534   case ISD::VP_GATHER:
8535     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8536     break;
8537   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8538     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8539     break;
8540   case ISD::VP_STORE:
8541     visitVPStore(VPIntrin, OpValues);
8542     break;
8543   case ISD::VP_SCATTER:
8544     visitVPScatter(VPIntrin, OpValues);
8545     break;
8546   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8547     visitVPStridedStore(VPIntrin, OpValues);
8548     break;
8549   case ISD::VP_FMULADD: {
8550     assert(OpValues.size() == 5 && "Unexpected number of operands");
8551     SDNodeFlags SDFlags;
8552     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8553       SDFlags.copyFMF(*FPMO);
8554     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8555         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8556       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8557     } else {
8558       SDValue Mul = DAG.getNode(
8559           ISD::VP_FMUL, DL, VTs,
8560           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8561       SDValue Add =
8562           DAG.getNode(ISD::VP_FADD, DL, VTs,
8563                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8564       setValue(&VPIntrin, Add);
8565     }
8566     break;
8567   }
8568   case ISD::VP_IS_FPCLASS: {
8569     const DataLayout DLayout = DAG.getDataLayout();
8570     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8571     auto Constant = OpValues[1]->getAsZExtVal();
8572     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8573     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8574                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8575     setValue(&VPIntrin, V);
8576     return;
8577   }
8578   case ISD::VP_INTTOPTR: {
8579     SDValue N = OpValues[0];
8580     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8581     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8582     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8583                                OpValues[2]);
8584     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8585                              OpValues[2]);
8586     setValue(&VPIntrin, N);
8587     break;
8588   }
8589   case ISD::VP_PTRTOINT: {
8590     SDValue N = OpValues[0];
8591     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8592                                                           VPIntrin.getType());
8593     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8594                                        VPIntrin.getOperand(0)->getType());
8595     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8596                                OpValues[2]);
8597     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8598                              OpValues[2]);
8599     setValue(&VPIntrin, N);
8600     break;
8601   }
8602   case ISD::VP_ABS:
8603   case ISD::VP_CTLZ:
8604   case ISD::VP_CTLZ_ZERO_UNDEF:
8605   case ISD::VP_CTTZ:
8606   case ISD::VP_CTTZ_ZERO_UNDEF:
8607   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8608   case ISD::VP_CTTZ_ELTS: {
8609     SDValue Result =
8610         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8611     setValue(&VPIntrin, Result);
8612     break;
8613   }
8614   }
8615 }
8616 
8617 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8618                                           const BasicBlock *EHPadBB,
8619                                           MCSymbol *&BeginLabel) {
8620   MachineFunction &MF = DAG.getMachineFunction();
8621 
8622   // Insert a label before the invoke call to mark the try range.  This can be
8623   // used to detect deletion of the invoke via the MachineModuleInfo.
8624   BeginLabel = MF.getContext().createTempSymbol();
8625 
8626   // For SjLj, keep track of which landing pads go with which invokes
8627   // so as to maintain the ordering of pads in the LSDA.
8628   unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
8629   if (CallSiteIndex) {
8630     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8631     LPadToCallSiteMap[FuncInfo.MBBMap[EHPadBB]].push_back(CallSiteIndex);
8632 
8633     // Now that the call site is handled, stop tracking it.
8634     FuncInfo.setCurrentCallSite(0);
8635   }
8636 
8637   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8638 }
8639 
8640 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8641                                         const BasicBlock *EHPadBB,
8642                                         MCSymbol *BeginLabel) {
8643   assert(BeginLabel && "BeginLabel should've been set");
8644 
8645   MachineFunction &MF = DAG.getMachineFunction();
8646 
8647   // Insert a label at the end of the invoke call to mark the try range.  This
8648   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8649   MCSymbol *EndLabel = MF.getContext().createTempSymbol();
8650   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8651 
8652   // Inform MachineModuleInfo of range.
8653   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8654   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8655   // actually use outlined funclets and their LSDA info style.
8656   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8657     assert(II && "II should've been set");
8658     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8659     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8660   } else if (!isScopedEHPersonality(Pers)) {
8661     assert(EHPadBB);
8662     MF.addInvoke(FuncInfo.MBBMap[EHPadBB], BeginLabel, EndLabel);
8663   }
8664 
8665   return Chain;
8666 }
8667 
8668 std::pair<SDValue, SDValue>
8669 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8670                                     const BasicBlock *EHPadBB) {
8671   MCSymbol *BeginLabel = nullptr;
8672 
8673   if (EHPadBB) {
8674     // Both PendingLoads and PendingExports must be flushed here;
8675     // this call might not return.
8676     (void)getRoot();
8677     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8678     CLI.setChain(getRoot());
8679   }
8680 
8681   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8682   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8683 
8684   assert((CLI.IsTailCall || Result.second.getNode()) &&
8685          "Non-null chain expected with non-tail call!");
8686   assert((Result.second.getNode() || !Result.first.getNode()) &&
8687          "Null value expected with tail call!");
8688 
8689   if (!Result.second.getNode()) {
8690     // As a special case, a null chain means that a tail call has been emitted
8691     // and the DAG root is already updated.
8692     HasTailCall = true;
8693 
8694     // Since there's no actual continuation from this block, nothing can be
8695     // relying on us setting vregs for them.
8696     PendingExports.clear();
8697   } else {
8698     DAG.setRoot(Result.second);
8699   }
8700 
8701   if (EHPadBB) {
8702     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8703                            BeginLabel));
8704     Result.second = getRoot();
8705   }
8706 
8707   return Result;
8708 }
8709 
8710 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8711                                       bool isTailCall, bool isMustTailCall,
8712                                       const BasicBlock *EHPadBB,
8713                                       const TargetLowering::PtrAuthInfo *PAI) {
8714   auto &DL = DAG.getDataLayout();
8715   FunctionType *FTy = CB.getFunctionType();
8716   Type *RetTy = CB.getType();
8717 
8718   TargetLowering::ArgListTy Args;
8719   Args.reserve(CB.arg_size());
8720 
8721   const Value *SwiftErrorVal = nullptr;
8722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8723 
8724   if (isTailCall) {
8725     // Avoid emitting tail calls in functions with the disable-tail-calls
8726     // attribute.
8727     auto *Caller = CB.getParent()->getParent();
8728     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8729         "true" && !isMustTailCall)
8730       isTailCall = false;
8731 
8732     // We can't tail call inside a function with a swifterror argument. Lowering
8733     // does not support this yet. It would have to move into the swifterror
8734     // register before the call.
8735     if (TLI.supportSwiftError() &&
8736         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8737       isTailCall = false;
8738   }
8739 
8740   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8741     TargetLowering::ArgListEntry Entry;
8742     const Value *V = *I;
8743 
8744     // Skip empty types
8745     if (V->getType()->isEmptyTy())
8746       continue;
8747 
8748     SDValue ArgNode = getValue(V);
8749     Entry.Node = ArgNode; Entry.Ty = V->getType();
8750 
8751     Entry.setAttributes(&CB, I - CB.arg_begin());
8752 
8753     // Use swifterror virtual register as input to the call.
8754     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8755       SwiftErrorVal = V;
8756       // We find the virtual register for the actual swifterror argument.
8757       // Instead of using the Value, we use the virtual register instead.
8758       Entry.Node =
8759           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8760                           EVT(TLI.getPointerTy(DL)));
8761     }
8762 
8763     Args.push_back(Entry);
8764 
8765     // If we have an explicit sret argument that is an Instruction, (i.e., it
8766     // might point to function-local memory), we can't meaningfully tail-call.
8767     if (Entry.IsSRet && isa<Instruction>(V))
8768       isTailCall = false;
8769   }
8770 
8771   // If call site has a cfguardtarget operand bundle, create and add an
8772   // additional ArgListEntry.
8773   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8774     TargetLowering::ArgListEntry Entry;
8775     Value *V = Bundle->Inputs[0];
8776     SDValue ArgNode = getValue(V);
8777     Entry.Node = ArgNode;
8778     Entry.Ty = V->getType();
8779     Entry.IsCFGuardTarget = true;
8780     Args.push_back(Entry);
8781   }
8782 
8783   // Check if target-independent constraints permit a tail call here.
8784   // Target-dependent constraints are checked within TLI->LowerCallTo.
8785   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8786     isTailCall = false;
8787 
8788   // Disable tail calls if there is an swifterror argument. Targets have not
8789   // been updated to support tail calls.
8790   if (TLI.supportSwiftError() && SwiftErrorVal)
8791     isTailCall = false;
8792 
8793   ConstantInt *CFIType = nullptr;
8794   if (CB.isIndirectCall()) {
8795     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8796       if (!TLI.supportKCFIBundles())
8797         report_fatal_error(
8798             "Target doesn't support calls with kcfi operand bundles.");
8799       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8800       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8801     }
8802   }
8803 
8804   SDValue ConvControlToken;
8805   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8806     auto *Token = Bundle->Inputs[0].get();
8807     ConvControlToken = getValue(Token);
8808   }
8809 
8810   TargetLowering::CallLoweringInfo CLI(DAG);
8811   CLI.setDebugLoc(getCurSDLoc())
8812       .setChain(getRoot())
8813       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8814       .setTailCall(isTailCall)
8815       .setConvergent(CB.isConvergent())
8816       .setIsPreallocated(
8817           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8818       .setCFIType(CFIType)
8819       .setConvergenceControlToken(ConvControlToken);
8820 
8821   // Set the pointer authentication info if we have it.
8822   if (PAI) {
8823     if (!TLI.supportPtrAuthBundles())
8824       report_fatal_error(
8825           "This target doesn't support calls with ptrauth operand bundles.");
8826     CLI.setPtrAuth(*PAI);
8827   }
8828 
8829   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8830 
8831   if (Result.first.getNode()) {
8832     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8833     setValue(&CB, Result.first);
8834   }
8835 
8836   // The last element of CLI.InVals has the SDValue for swifterror return.
8837   // Here we copy it to a virtual register and update SwiftErrorMap for
8838   // book-keeping.
8839   if (SwiftErrorVal && TLI.supportSwiftError()) {
8840     // Get the last element of InVals.
8841     SDValue Src = CLI.InVals.back();
8842     Register VReg =
8843         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8844     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8845     DAG.setRoot(CopyNode);
8846   }
8847 }
8848 
8849 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8850                              SelectionDAGBuilder &Builder) {
8851   // Check to see if this load can be trivially constant folded, e.g. if the
8852   // input is from a string literal.
8853   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8854     // Cast pointer to the type we really want to load.
8855     Type *LoadTy =
8856         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8857     if (LoadVT.isVector())
8858       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8859 
8860     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8861                                          PointerType::getUnqual(LoadTy));
8862 
8863     if (const Constant *LoadCst =
8864             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8865                                          LoadTy, Builder.DAG.getDataLayout()))
8866       return Builder.getValue(LoadCst);
8867   }
8868 
8869   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8870   // still constant memory, the input chain can be the entry node.
8871   SDValue Root;
8872   bool ConstantMemory = false;
8873 
8874   // Do not serialize (non-volatile) loads of constant memory with anything.
8875   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8876     Root = Builder.DAG.getEntryNode();
8877     ConstantMemory = true;
8878   } else {
8879     // Do not serialize non-volatile loads against each other.
8880     Root = Builder.DAG.getRoot();
8881   }
8882 
8883   SDValue Ptr = Builder.getValue(PtrVal);
8884   SDValue LoadVal =
8885       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8886                           MachinePointerInfo(PtrVal), Align(1));
8887 
8888   if (!ConstantMemory)
8889     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8890   return LoadVal;
8891 }
8892 
8893 /// Record the value for an instruction that produces an integer result,
8894 /// converting the type where necessary.
8895 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8896                                                   SDValue Value,
8897                                                   bool IsSigned) {
8898   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8899                                                     I.getType(), true);
8900   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8901   setValue(&I, Value);
8902 }
8903 
8904 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8905 /// true and lower it. Otherwise return false, and it will be lowered like a
8906 /// normal call.
8907 /// The caller already checked that \p I calls the appropriate LibFunc with a
8908 /// correct prototype.
8909 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8910   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8911   const Value *Size = I.getArgOperand(2);
8912   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8913   if (CSize && CSize->getZExtValue() == 0) {
8914     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8915                                                           I.getType(), true);
8916     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8917     return true;
8918   }
8919 
8920   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8921   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8922       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8923       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8924   if (Res.first.getNode()) {
8925     processIntegerCallValue(I, Res.first, true);
8926     PendingLoads.push_back(Res.second);
8927     return true;
8928   }
8929 
8930   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8931   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8932   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8933     return false;
8934 
8935   // If the target has a fast compare for the given size, it will return a
8936   // preferred load type for that size. Require that the load VT is legal and
8937   // that the target supports unaligned loads of that type. Otherwise, return
8938   // INVALID.
8939   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8940     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8941     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8942     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8943       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8944       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8945       // TODO: Check alignment of src and dest ptrs.
8946       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8947       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8948       if (!TLI.isTypeLegal(LVT) ||
8949           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8950           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8951         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8952     }
8953 
8954     return LVT;
8955   };
8956 
8957   // This turns into unaligned loads. We only do this if the target natively
8958   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8959   // we'll only produce a small number of byte loads.
8960   MVT LoadVT;
8961   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8962   switch (NumBitsToCompare) {
8963   default:
8964     return false;
8965   case 16:
8966     LoadVT = MVT::i16;
8967     break;
8968   case 32:
8969     LoadVT = MVT::i32;
8970     break;
8971   case 64:
8972   case 128:
8973   case 256:
8974     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8975     break;
8976   }
8977 
8978   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8979     return false;
8980 
8981   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
8982   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
8983 
8984   // Bitcast to a wide integer type if the loads are vectors.
8985   if (LoadVT.isVector()) {
8986     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
8987     LoadL = DAG.getBitcast(CmpVT, LoadL);
8988     LoadR = DAG.getBitcast(CmpVT, LoadR);
8989   }
8990 
8991   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
8992   processIntegerCallValue(I, Cmp, false);
8993   return true;
8994 }
8995 
8996 /// See if we can lower a memchr call into an optimized form. If so, return
8997 /// true and lower it. Otherwise return false, and it will be lowered like a
8998 /// normal call.
8999 /// The caller already checked that \p I calls the appropriate LibFunc with a
9000 /// correct prototype.
9001 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9002   const Value *Src = I.getArgOperand(0);
9003   const Value *Char = I.getArgOperand(1);
9004   const Value *Length = I.getArgOperand(2);
9005 
9006   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9007   std::pair<SDValue, SDValue> Res =
9008     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9009                                 getValue(Src), getValue(Char), getValue(Length),
9010                                 MachinePointerInfo(Src));
9011   if (Res.first.getNode()) {
9012     setValue(&I, Res.first);
9013     PendingLoads.push_back(Res.second);
9014     return true;
9015   }
9016 
9017   return false;
9018 }
9019 
9020 /// See if we can lower a mempcpy call into an optimized form. If so, return
9021 /// true and lower it. Otherwise return false, and it will be lowered like a
9022 /// normal call.
9023 /// The caller already checked that \p I calls the appropriate LibFunc with a
9024 /// correct prototype.
9025 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9026   SDValue Dst = getValue(I.getArgOperand(0));
9027   SDValue Src = getValue(I.getArgOperand(1));
9028   SDValue Size = getValue(I.getArgOperand(2));
9029 
9030   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9031   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9032   // DAG::getMemcpy needs Alignment to be defined.
9033   Align Alignment = std::min(DstAlign, SrcAlign);
9034 
9035   SDLoc sdl = getCurSDLoc();
9036 
9037   // In the mempcpy context we need to pass in a false value for isTailCall
9038   // because the return pointer needs to be adjusted by the size of
9039   // the copied memory.
9040   SDValue Root = getMemoryRoot();
9041   SDValue MC = DAG.getMemcpy(
9042       Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr,
9043       std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9044       MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9045   assert(MC.getNode() != nullptr &&
9046          "** memcpy should not be lowered as TailCall in mempcpy context **");
9047   DAG.setRoot(MC);
9048 
9049   // Check if Size needs to be truncated or extended.
9050   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9051 
9052   // Adjust return pointer to point just past the last dst byte.
9053   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9054                                     Dst, Size);
9055   setValue(&I, DstPlusSize);
9056   return true;
9057 }
9058 
9059 /// See if we can lower a strcpy call into an optimized form.  If so, return
9060 /// true and lower it, otherwise return false and it will be lowered like a
9061 /// normal call.
9062 /// The caller already checked that \p I calls the appropriate LibFunc with a
9063 /// correct prototype.
9064 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9065   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9066 
9067   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9068   std::pair<SDValue, SDValue> Res =
9069     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9070                                 getValue(Arg0), getValue(Arg1),
9071                                 MachinePointerInfo(Arg0),
9072                                 MachinePointerInfo(Arg1), isStpcpy);
9073   if (Res.first.getNode()) {
9074     setValue(&I, Res.first);
9075     DAG.setRoot(Res.second);
9076     return true;
9077   }
9078 
9079   return false;
9080 }
9081 
9082 /// See if we can lower a strcmp call into an optimized form.  If so, return
9083 /// true and lower it, otherwise return false and it will be lowered like a
9084 /// normal call.
9085 /// The caller already checked that \p I calls the appropriate LibFunc with a
9086 /// correct prototype.
9087 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9088   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9089 
9090   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9091   std::pair<SDValue, SDValue> Res =
9092     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9093                                 getValue(Arg0), getValue(Arg1),
9094                                 MachinePointerInfo(Arg0),
9095                                 MachinePointerInfo(Arg1));
9096   if (Res.first.getNode()) {
9097     processIntegerCallValue(I, Res.first, true);
9098     PendingLoads.push_back(Res.second);
9099     return true;
9100   }
9101 
9102   return false;
9103 }
9104 
9105 /// See if we can lower a strlen call into an optimized form.  If so, return
9106 /// true and lower it, otherwise return false and it will be lowered like a
9107 /// normal call.
9108 /// The caller already checked that \p I calls the appropriate LibFunc with a
9109 /// correct prototype.
9110 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9111   const Value *Arg0 = I.getArgOperand(0);
9112 
9113   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9114   std::pair<SDValue, SDValue> Res =
9115     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9116                                 getValue(Arg0), MachinePointerInfo(Arg0));
9117   if (Res.first.getNode()) {
9118     processIntegerCallValue(I, Res.first, false);
9119     PendingLoads.push_back(Res.second);
9120     return true;
9121   }
9122 
9123   return false;
9124 }
9125 
9126 /// See if we can lower a strnlen call into an optimized form.  If so, return
9127 /// true and lower it, otherwise return false and it will be lowered like a
9128 /// normal call.
9129 /// The caller already checked that \p I calls the appropriate LibFunc with a
9130 /// correct prototype.
9131 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9132   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9133 
9134   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9135   std::pair<SDValue, SDValue> Res =
9136     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9137                                  getValue(Arg0), getValue(Arg1),
9138                                  MachinePointerInfo(Arg0));
9139   if (Res.first.getNode()) {
9140     processIntegerCallValue(I, Res.first, false);
9141     PendingLoads.push_back(Res.second);
9142     return true;
9143   }
9144 
9145   return false;
9146 }
9147 
9148 /// See if we can lower a unary floating-point operation into an SDNode with
9149 /// the specified Opcode.  If so, return true and lower it, otherwise return
9150 /// false and it will be lowered like a normal call.
9151 /// The caller already checked that \p I calls the appropriate LibFunc with a
9152 /// correct prototype.
9153 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9154                                               unsigned Opcode) {
9155   // We already checked this call's prototype; verify it doesn't modify errno.
9156   if (!I.onlyReadsMemory())
9157     return false;
9158 
9159   SDNodeFlags Flags;
9160   Flags.copyFMF(cast<FPMathOperator>(I));
9161 
9162   SDValue Tmp = getValue(I.getArgOperand(0));
9163   setValue(&I,
9164            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9165   return true;
9166 }
9167 
9168 /// See if we can lower a binary floating-point operation into an SDNode with
9169 /// the specified Opcode. If so, return true and lower it. Otherwise return
9170 /// false, and it will be lowered like a normal call.
9171 /// The caller already checked that \p I calls the appropriate LibFunc with a
9172 /// correct prototype.
9173 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9174                                                unsigned Opcode) {
9175   // We already checked this call's prototype; verify it doesn't modify errno.
9176   if (!I.onlyReadsMemory())
9177     return false;
9178 
9179   SDNodeFlags Flags;
9180   Flags.copyFMF(cast<FPMathOperator>(I));
9181 
9182   SDValue Tmp0 = getValue(I.getArgOperand(0));
9183   SDValue Tmp1 = getValue(I.getArgOperand(1));
9184   EVT VT = Tmp0.getValueType();
9185   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9186   return true;
9187 }
9188 
9189 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9190   // Handle inline assembly differently.
9191   if (I.isInlineAsm()) {
9192     visitInlineAsm(I);
9193     return;
9194   }
9195 
9196   diagnoseDontCall(I);
9197 
9198   if (Function *F = I.getCalledFunction()) {
9199     if (F->isDeclaration()) {
9200       // Is this an LLVM intrinsic or a target-specific intrinsic?
9201       unsigned IID = F->getIntrinsicID();
9202       if (!IID)
9203         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9204           IID = II->getIntrinsicID(F);
9205 
9206       if (IID) {
9207         visitIntrinsicCall(I, IID);
9208         return;
9209       }
9210     }
9211 
9212     // Check for well-known libc/libm calls.  If the function is internal, it
9213     // can't be a library call.  Don't do the check if marked as nobuiltin for
9214     // some reason or the call site requires strict floating point semantics.
9215     LibFunc Func;
9216     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9217         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9218         LibInfo->hasOptimizedCodeGen(Func)) {
9219       switch (Func) {
9220       default: break;
9221       case LibFunc_bcmp:
9222         if (visitMemCmpBCmpCall(I))
9223           return;
9224         break;
9225       case LibFunc_copysign:
9226       case LibFunc_copysignf:
9227       case LibFunc_copysignl:
9228         // We already checked this call's prototype; verify it doesn't modify
9229         // errno.
9230         if (I.onlyReadsMemory()) {
9231           SDValue LHS = getValue(I.getArgOperand(0));
9232           SDValue RHS = getValue(I.getArgOperand(1));
9233           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9234                                    LHS.getValueType(), LHS, RHS));
9235           return;
9236         }
9237         break;
9238       case LibFunc_fabs:
9239       case LibFunc_fabsf:
9240       case LibFunc_fabsl:
9241         if (visitUnaryFloatCall(I, ISD::FABS))
9242           return;
9243         break;
9244       case LibFunc_fmin:
9245       case LibFunc_fminf:
9246       case LibFunc_fminl:
9247         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9248           return;
9249         break;
9250       case LibFunc_fmax:
9251       case LibFunc_fmaxf:
9252       case LibFunc_fmaxl:
9253         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9254           return;
9255         break;
9256       case LibFunc_sin:
9257       case LibFunc_sinf:
9258       case LibFunc_sinl:
9259         if (visitUnaryFloatCall(I, ISD::FSIN))
9260           return;
9261         break;
9262       case LibFunc_cos:
9263       case LibFunc_cosf:
9264       case LibFunc_cosl:
9265         if (visitUnaryFloatCall(I, ISD::FCOS))
9266           return;
9267         break;
9268       case LibFunc_tan:
9269       case LibFunc_tanf:
9270       case LibFunc_tanl:
9271         if (visitUnaryFloatCall(I, ISD::FTAN))
9272           return;
9273         break;
9274       case LibFunc_asin:
9275       case LibFunc_asinf:
9276       case LibFunc_asinl:
9277         if (visitUnaryFloatCall(I, ISD::FASIN))
9278           return;
9279         break;
9280       case LibFunc_acos:
9281       case LibFunc_acosf:
9282       case LibFunc_acosl:
9283         if (visitUnaryFloatCall(I, ISD::FACOS))
9284           return;
9285         break;
9286       case LibFunc_atan:
9287       case LibFunc_atanf:
9288       case LibFunc_atanl:
9289         if (visitUnaryFloatCall(I, ISD::FATAN))
9290           return;
9291         break;
9292       case LibFunc_sinh:
9293       case LibFunc_sinhf:
9294       case LibFunc_sinhl:
9295         if (visitUnaryFloatCall(I, ISD::FSINH))
9296           return;
9297         break;
9298       case LibFunc_cosh:
9299       case LibFunc_coshf:
9300       case LibFunc_coshl:
9301         if (visitUnaryFloatCall(I, ISD::FCOSH))
9302           return;
9303         break;
9304       case LibFunc_tanh:
9305       case LibFunc_tanhf:
9306       case LibFunc_tanhl:
9307         if (visitUnaryFloatCall(I, ISD::FTANH))
9308           return;
9309         break;
9310       case LibFunc_sqrt:
9311       case LibFunc_sqrtf:
9312       case LibFunc_sqrtl:
9313       case LibFunc_sqrt_finite:
9314       case LibFunc_sqrtf_finite:
9315       case LibFunc_sqrtl_finite:
9316         if (visitUnaryFloatCall(I, ISD::FSQRT))
9317           return;
9318         break;
9319       case LibFunc_floor:
9320       case LibFunc_floorf:
9321       case LibFunc_floorl:
9322         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9323           return;
9324         break;
9325       case LibFunc_nearbyint:
9326       case LibFunc_nearbyintf:
9327       case LibFunc_nearbyintl:
9328         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9329           return;
9330         break;
9331       case LibFunc_ceil:
9332       case LibFunc_ceilf:
9333       case LibFunc_ceill:
9334         if (visitUnaryFloatCall(I, ISD::FCEIL))
9335           return;
9336         break;
9337       case LibFunc_rint:
9338       case LibFunc_rintf:
9339       case LibFunc_rintl:
9340         if (visitUnaryFloatCall(I, ISD::FRINT))
9341           return;
9342         break;
9343       case LibFunc_round:
9344       case LibFunc_roundf:
9345       case LibFunc_roundl:
9346         if (visitUnaryFloatCall(I, ISD::FROUND))
9347           return;
9348         break;
9349       case LibFunc_trunc:
9350       case LibFunc_truncf:
9351       case LibFunc_truncl:
9352         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9353           return;
9354         break;
9355       case LibFunc_log2:
9356       case LibFunc_log2f:
9357       case LibFunc_log2l:
9358         if (visitUnaryFloatCall(I, ISD::FLOG2))
9359           return;
9360         break;
9361       case LibFunc_exp2:
9362       case LibFunc_exp2f:
9363       case LibFunc_exp2l:
9364         if (visitUnaryFloatCall(I, ISD::FEXP2))
9365           return;
9366         break;
9367       case LibFunc_exp10:
9368       case LibFunc_exp10f:
9369       case LibFunc_exp10l:
9370         if (visitUnaryFloatCall(I, ISD::FEXP10))
9371           return;
9372         break;
9373       case LibFunc_ldexp:
9374       case LibFunc_ldexpf:
9375       case LibFunc_ldexpl:
9376         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9377           return;
9378         break;
9379       case LibFunc_memcmp:
9380         if (visitMemCmpBCmpCall(I))
9381           return;
9382         break;
9383       case LibFunc_mempcpy:
9384         if (visitMemPCpyCall(I))
9385           return;
9386         break;
9387       case LibFunc_memchr:
9388         if (visitMemChrCall(I))
9389           return;
9390         break;
9391       case LibFunc_strcpy:
9392         if (visitStrCpyCall(I, false))
9393           return;
9394         break;
9395       case LibFunc_stpcpy:
9396         if (visitStrCpyCall(I, true))
9397           return;
9398         break;
9399       case LibFunc_strcmp:
9400         if (visitStrCmpCall(I))
9401           return;
9402         break;
9403       case LibFunc_strlen:
9404         if (visitStrLenCall(I))
9405           return;
9406         break;
9407       case LibFunc_strnlen:
9408         if (visitStrNLenCall(I))
9409           return;
9410         break;
9411       }
9412     }
9413   }
9414 
9415   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9416     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9417     return;
9418   }
9419 
9420   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9421   // have to do anything here to lower funclet bundles.
9422   // CFGuardTarget bundles are lowered in LowerCallTo.
9423   assert(!I.hasOperandBundlesOtherThan(
9424              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9425               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9426               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9427               LLVMContext::OB_convergencectrl}) &&
9428          "Cannot lower calls with arbitrary operand bundles!");
9429 
9430   SDValue Callee = getValue(I.getCalledOperand());
9431 
9432   if (I.hasDeoptState())
9433     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9434   else
9435     // Check if we can potentially perform a tail call. More detailed checking
9436     // is be done within LowerCallTo, after more information about the call is
9437     // known.
9438     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9439 }
9440 
9441 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9442     const CallBase &CB, const BasicBlock *EHPadBB) {
9443   auto PAB = CB.getOperandBundle("ptrauth");
9444   const Value *CalleeV = CB.getCalledOperand();
9445 
9446   // Gather the call ptrauth data from the operand bundle:
9447   //   [ i32 <key>, i64 <discriminator> ]
9448   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9449   const Value *Discriminator = PAB->Inputs[1];
9450 
9451   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9452   assert(Discriminator->getType()->isIntegerTy(64) &&
9453          "Invalid ptrauth discriminator");
9454 
9455   // Look through ptrauth constants to find the raw callee.
9456   // Do a direct unauthenticated call if we found it and everything matches.
9457   if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9458     if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9459                                          DAG.getDataLayout()))
9460       return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9461                          CB.isMustTailCall(), EHPadBB);
9462 
9463   // Functions should never be ptrauth-called directly.
9464   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9465 
9466   // Otherwise, do an authenticated indirect call.
9467   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9468                                      getValue(Discriminator)};
9469 
9470   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9471               EHPadBB, &PAI);
9472 }
9473 
9474 namespace {
9475 
9476 /// AsmOperandInfo - This contains information for each constraint that we are
9477 /// lowering.
9478 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9479 public:
9480   /// CallOperand - If this is the result output operand or a clobber
9481   /// this is null, otherwise it is the incoming operand to the CallInst.
9482   /// This gets modified as the asm is processed.
9483   SDValue CallOperand;
9484 
9485   /// AssignedRegs - If this is a register or register class operand, this
9486   /// contains the set of register corresponding to the operand.
9487   RegsForValue AssignedRegs;
9488 
9489   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9490     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9491   }
9492 
9493   /// Whether or not this operand accesses memory
9494   bool hasMemory(const TargetLowering &TLI) const {
9495     // Indirect operand accesses access memory.
9496     if (isIndirect)
9497       return true;
9498 
9499     for (const auto &Code : Codes)
9500       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9501         return true;
9502 
9503     return false;
9504   }
9505 };
9506 
9507 
9508 } // end anonymous namespace
9509 
9510 /// Make sure that the output operand \p OpInfo and its corresponding input
9511 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9512 /// out).
9513 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9514                                SDISelAsmOperandInfo &MatchingOpInfo,
9515                                SelectionDAG &DAG) {
9516   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9517     return;
9518 
9519   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9520   const auto &TLI = DAG.getTargetLoweringInfo();
9521 
9522   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9523       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9524                                        OpInfo.ConstraintVT);
9525   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9526       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9527                                        MatchingOpInfo.ConstraintVT);
9528   if ((OpInfo.ConstraintVT.isInteger() !=
9529        MatchingOpInfo.ConstraintVT.isInteger()) ||
9530       (MatchRC.second != InputRC.second)) {
9531     // FIXME: error out in a more elegant fashion
9532     report_fatal_error("Unsupported asm: input constraint"
9533                        " with a matching output constraint of"
9534                        " incompatible type!");
9535   }
9536   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9537 }
9538 
9539 /// Get a direct memory input to behave well as an indirect operand.
9540 /// This may introduce stores, hence the need for a \p Chain.
9541 /// \return The (possibly updated) chain.
9542 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9543                                         SDISelAsmOperandInfo &OpInfo,
9544                                         SelectionDAG &DAG) {
9545   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9546 
9547   // If we don't have an indirect input, put it in the constpool if we can,
9548   // otherwise spill it to a stack slot.
9549   // TODO: This isn't quite right. We need to handle these according to
9550   // the addressing mode that the constraint wants. Also, this may take
9551   // an additional register for the computation and we don't want that
9552   // either.
9553 
9554   // If the operand is a float, integer, or vector constant, spill to a
9555   // constant pool entry to get its address.
9556   const Value *OpVal = OpInfo.CallOperandVal;
9557   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9558       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9559     OpInfo.CallOperand = DAG.getConstantPool(
9560         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9561     return Chain;
9562   }
9563 
9564   // Otherwise, create a stack slot and emit a store to it before the asm.
9565   Type *Ty = OpVal->getType();
9566   auto &DL = DAG.getDataLayout();
9567   TypeSize TySize = DL.getTypeAllocSize(Ty);
9568   MachineFunction &MF = DAG.getMachineFunction();
9569   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9570   int StackID = 0;
9571   if (TySize.isScalable())
9572     StackID = TFI->getStackIDForScalableVectors();
9573   int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
9574                                                  DL.getPrefTypeAlign(Ty), false,
9575                                                  nullptr, StackID);
9576   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9577   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9578                             MachinePointerInfo::getFixedStack(MF, SSFI),
9579                             TLI.getMemValueType(DL, Ty));
9580   OpInfo.CallOperand = StackSlot;
9581 
9582   return Chain;
9583 }
9584 
9585 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9586 /// specified operand.  We prefer to assign virtual registers, to allow the
9587 /// register allocator to handle the assignment process.  However, if the asm
9588 /// uses features that we can't model on machineinstrs, we have SDISel do the
9589 /// allocation.  This produces generally horrible, but correct, code.
9590 ///
9591 ///   OpInfo describes the operand
9592 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9593 static std::optional<unsigned>
9594 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9595                      SDISelAsmOperandInfo &OpInfo,
9596                      SDISelAsmOperandInfo &RefOpInfo) {
9597   LLVMContext &Context = *DAG.getContext();
9598   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9599 
9600   MachineFunction &MF = DAG.getMachineFunction();
9601   SmallVector<unsigned, 4> Regs;
9602   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9603 
9604   // No work to do for memory/address operands.
9605   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9606       OpInfo.ConstraintType == TargetLowering::C_Address)
9607     return std::nullopt;
9608 
9609   // If this is a constraint for a single physreg, or a constraint for a
9610   // register class, find it.
9611   unsigned AssignedReg;
9612   const TargetRegisterClass *RC;
9613   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9614       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9615   // RC is unset only on failure. Return immediately.
9616   if (!RC)
9617     return std::nullopt;
9618 
9619   // Get the actual register value type.  This is important, because the user
9620   // may have asked for (e.g.) the AX register in i32 type.  We need to
9621   // remember that AX is actually i16 to get the right extension.
9622   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9623 
9624   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9625     // If this is an FP operand in an integer register (or visa versa), or more
9626     // generally if the operand value disagrees with the register class we plan
9627     // to stick it in, fix the operand type.
9628     //
9629     // If this is an input value, the bitcast to the new type is done now.
9630     // Bitcast for output value is done at the end of visitInlineAsm().
9631     if ((OpInfo.Type == InlineAsm::isOutput ||
9632          OpInfo.Type == InlineAsm::isInput) &&
9633         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9634       // Try to convert to the first EVT that the reg class contains.  If the
9635       // types are identical size, use a bitcast to convert (e.g. two differing
9636       // vector types).  Note: output bitcast is done at the end of
9637       // visitInlineAsm().
9638       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9639         // Exclude indirect inputs while they are unsupported because the code
9640         // to perform the load is missing and thus OpInfo.CallOperand still
9641         // refers to the input address rather than the pointed-to value.
9642         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9643           OpInfo.CallOperand =
9644               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9645         OpInfo.ConstraintVT = RegVT;
9646         // If the operand is an FP value and we want it in integer registers,
9647         // use the corresponding integer type. This turns an f64 value into
9648         // i64, which can be passed with two i32 values on a 32-bit machine.
9649       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9650         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9651         if (OpInfo.Type == InlineAsm::isInput)
9652           OpInfo.CallOperand =
9653               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9654         OpInfo.ConstraintVT = VT;
9655       }
9656     }
9657   }
9658 
9659   // No need to allocate a matching input constraint since the constraint it's
9660   // matching to has already been allocated.
9661   if (OpInfo.isMatchingInputConstraint())
9662     return std::nullopt;
9663 
9664   EVT ValueVT = OpInfo.ConstraintVT;
9665   if (OpInfo.ConstraintVT == MVT::Other)
9666     ValueVT = RegVT;
9667 
9668   // Initialize NumRegs.
9669   unsigned NumRegs = 1;
9670   if (OpInfo.ConstraintVT != MVT::Other)
9671     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9672 
9673   // If this is a constraint for a specific physical register, like {r17},
9674   // assign it now.
9675 
9676   // If this associated to a specific register, initialize iterator to correct
9677   // place. If virtual, make sure we have enough registers
9678 
9679   // Initialize iterator if necessary
9680   TargetRegisterClass::iterator I = RC->begin();
9681   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9682 
9683   // Do not check for single registers.
9684   if (AssignedReg) {
9685     I = std::find(I, RC->end(), AssignedReg);
9686     if (I == RC->end()) {
9687       // RC does not contain the selected register, which indicates a
9688       // mismatch between the register and the required type/bitwidth.
9689       return {AssignedReg};
9690     }
9691   }
9692 
9693   for (; NumRegs; --NumRegs, ++I) {
9694     assert(I != RC->end() && "Ran out of registers to allocate!");
9695     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9696     Regs.push_back(R);
9697   }
9698 
9699   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9700   return std::nullopt;
9701 }
9702 
9703 static unsigned
9704 findMatchingInlineAsmOperand(unsigned OperandNo,
9705                              const std::vector<SDValue> &AsmNodeOperands) {
9706   // Scan until we find the definition we already emitted of this operand.
9707   unsigned CurOp = InlineAsm::Op_FirstOperand;
9708   for (; OperandNo; --OperandNo) {
9709     // Advance to the next operand.
9710     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9711     const InlineAsm::Flag F(OpFlag);
9712     assert(
9713         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9714         "Skipped past definitions?");
9715     CurOp += F.getNumOperandRegisters() + 1;
9716   }
9717   return CurOp;
9718 }
9719 
9720 namespace {
9721 
9722 class ExtraFlags {
9723   unsigned Flags = 0;
9724 
9725 public:
9726   explicit ExtraFlags(const CallBase &Call) {
9727     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9728     if (IA->hasSideEffects())
9729       Flags |= InlineAsm::Extra_HasSideEffects;
9730     if (IA->isAlignStack())
9731       Flags |= InlineAsm::Extra_IsAlignStack;
9732     if (Call.isConvergent())
9733       Flags |= InlineAsm::Extra_IsConvergent;
9734     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9735   }
9736 
9737   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9738     // Ideally, we would only check against memory constraints.  However, the
9739     // meaning of an Other constraint can be target-specific and we can't easily
9740     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9741     // for Other constraints as well.
9742     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9743         OpInfo.ConstraintType == TargetLowering::C_Other) {
9744       if (OpInfo.Type == InlineAsm::isInput)
9745         Flags |= InlineAsm::Extra_MayLoad;
9746       else if (OpInfo.Type == InlineAsm::isOutput)
9747         Flags |= InlineAsm::Extra_MayStore;
9748       else if (OpInfo.Type == InlineAsm::isClobber)
9749         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9750     }
9751   }
9752 
9753   unsigned get() const { return Flags; }
9754 };
9755 
9756 } // end anonymous namespace
9757 
9758 static bool isFunction(SDValue Op) {
9759   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9760     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9761       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9762 
9763       // In normal "call dllimport func" instruction (non-inlineasm) it force
9764       // indirect access by specifing call opcode. And usually specially print
9765       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9766       // not do in this way now. (In fact, this is similar with "Data Access"
9767       // action). So here we ignore dllimport function.
9768       if (Fn && !Fn->hasDLLImportStorageClass())
9769         return true;
9770     }
9771   }
9772   return false;
9773 }
9774 
9775 /// visitInlineAsm - Handle a call to an InlineAsm object.
9776 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9777                                          const BasicBlock *EHPadBB) {
9778   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9779 
9780   /// ConstraintOperands - Information about all of the constraints.
9781   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9782 
9783   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9784   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9785       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9786 
9787   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9788   // AsmDialect, MayLoad, MayStore).
9789   bool HasSideEffect = IA->hasSideEffects();
9790   ExtraFlags ExtraInfo(Call);
9791 
9792   for (auto &T : TargetConstraints) {
9793     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9794     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9795 
9796     if (OpInfo.CallOperandVal)
9797       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9798 
9799     if (!HasSideEffect)
9800       HasSideEffect = OpInfo.hasMemory(TLI);
9801 
9802     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9803     // FIXME: Could we compute this on OpInfo rather than T?
9804 
9805     // Compute the constraint code and ConstraintType to use.
9806     TLI.ComputeConstraintToUse(T, SDValue());
9807 
9808     if (T.ConstraintType == TargetLowering::C_Immediate &&
9809         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9810       // We've delayed emitting a diagnostic like the "n" constraint because
9811       // inlining could cause an integer showing up.
9812       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9813                                           "' expects an integer constant "
9814                                           "expression");
9815 
9816     ExtraInfo.update(T);
9817   }
9818 
9819   // We won't need to flush pending loads if this asm doesn't touch
9820   // memory and is nonvolatile.
9821   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9822 
9823   bool EmitEHLabels = isa<InvokeInst>(Call);
9824   if (EmitEHLabels) {
9825     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9826   }
9827   bool IsCallBr = isa<CallBrInst>(Call);
9828 
9829   if (IsCallBr || EmitEHLabels) {
9830     // If this is a callbr or invoke we need to flush pending exports since
9831     // inlineasm_br and invoke are terminators.
9832     // We need to do this before nodes are glued to the inlineasm_br node.
9833     Chain = getControlRoot();
9834   }
9835 
9836   MCSymbol *BeginLabel = nullptr;
9837   if (EmitEHLabels) {
9838     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9839   }
9840 
9841   int OpNo = -1;
9842   SmallVector<StringRef> AsmStrs;
9843   IA->collectAsmStrs(AsmStrs);
9844 
9845   // Second pass over the constraints: compute which constraint option to use.
9846   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9847     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9848       OpNo++;
9849 
9850     // If this is an output operand with a matching input operand, look up the
9851     // matching input. If their types mismatch, e.g. one is an integer, the
9852     // other is floating point, or their sizes are different, flag it as an
9853     // error.
9854     if (OpInfo.hasMatchingInput()) {
9855       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9856       patchMatchingInput(OpInfo, Input, DAG);
9857     }
9858 
9859     // Compute the constraint code and ConstraintType to use.
9860     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9861 
9862     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9863          OpInfo.Type == InlineAsm::isClobber) ||
9864         OpInfo.ConstraintType == TargetLowering::C_Address)
9865       continue;
9866 
9867     // In Linux PIC model, there are 4 cases about value/label addressing:
9868     //
9869     // 1: Function call or Label jmp inside the module.
9870     // 2: Data access (such as global variable, static variable) inside module.
9871     // 3: Function call or Label jmp outside the module.
9872     // 4: Data access (such as global variable) outside the module.
9873     //
9874     // Due to current llvm inline asm architecture designed to not "recognize"
9875     // the asm code, there are quite troubles for us to treat mem addressing
9876     // differently for same value/adress used in different instuctions.
9877     // For example, in pic model, call a func may in plt way or direclty
9878     // pc-related, but lea/mov a function adress may use got.
9879     //
9880     // Here we try to "recognize" function call for the case 1 and case 3 in
9881     // inline asm. And try to adjust the constraint for them.
9882     //
9883     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9884     // label, so here we don't handle jmp function label now, but we need to
9885     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9886     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9887         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9888         TM.getCodeModel() != CodeModel::Large) {
9889       OpInfo.isIndirect = false;
9890       OpInfo.ConstraintType = TargetLowering::C_Address;
9891     }
9892 
9893     // If this is a memory input, and if the operand is not indirect, do what we
9894     // need to provide an address for the memory input.
9895     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9896         !OpInfo.isIndirect) {
9897       assert((OpInfo.isMultipleAlternative ||
9898               (OpInfo.Type == InlineAsm::isInput)) &&
9899              "Can only indirectify direct input operands!");
9900 
9901       // Memory operands really want the address of the value.
9902       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9903 
9904       // There is no longer a Value* corresponding to this operand.
9905       OpInfo.CallOperandVal = nullptr;
9906 
9907       // It is now an indirect operand.
9908       OpInfo.isIndirect = true;
9909     }
9910 
9911   }
9912 
9913   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9914   std::vector<SDValue> AsmNodeOperands;
9915   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9916   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9917       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9918 
9919   // If we have a !srcloc metadata node associated with it, we want to attach
9920   // this to the ultimately generated inline asm machineinstr.  To do this, we
9921   // pass in the third operand as this (potentially null) inline asm MDNode.
9922   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9923   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9924 
9925   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9926   // bits as operand 3.
9927   AsmNodeOperands.push_back(DAG.getTargetConstant(
9928       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9929 
9930   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9931   // this, assign virtual and physical registers for inputs and otput.
9932   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9933     // Assign Registers.
9934     SDISelAsmOperandInfo &RefOpInfo =
9935         OpInfo.isMatchingInputConstraint()
9936             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9937             : OpInfo;
9938     const auto RegError =
9939         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9940     if (RegError) {
9941       const MachineFunction &MF = DAG.getMachineFunction();
9942       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9943       const char *RegName = TRI.getName(*RegError);
9944       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9945                                    "' allocated for constraint '" +
9946                                    Twine(OpInfo.ConstraintCode) +
9947                                    "' does not match required type");
9948       return;
9949     }
9950 
9951     auto DetectWriteToReservedRegister = [&]() {
9952       const MachineFunction &MF = DAG.getMachineFunction();
9953       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9954       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9955         if (Register::isPhysicalRegister(Reg) &&
9956             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9957           const char *RegName = TRI.getName(Reg);
9958           emitInlineAsmError(Call, "write to reserved register '" +
9959                                        Twine(RegName) + "'");
9960           return true;
9961         }
9962       }
9963       return false;
9964     };
9965     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9966             (OpInfo.Type == InlineAsm::isInput &&
9967              !OpInfo.isMatchingInputConstraint())) &&
9968            "Only address as input operand is allowed.");
9969 
9970     switch (OpInfo.Type) {
9971     case InlineAsm::isOutput:
9972       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
9973         const InlineAsm::ConstraintCode ConstraintID =
9974             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
9975         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
9976                "Failed to convert memory constraint code to constraint id.");
9977 
9978         // Add information to the INLINEASM node to know about this output.
9979         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
9980         OpFlags.setMemConstraint(ConstraintID);
9981         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
9982                                                         MVT::i32));
9983         AsmNodeOperands.push_back(OpInfo.CallOperand);
9984       } else {
9985         // Otherwise, this outputs to a register (directly for C_Register /
9986         // C_RegisterClass, and a target-defined fashion for
9987         // C_Immediate/C_Other). Find a register that we can use.
9988         if (OpInfo.AssignedRegs.Regs.empty()) {
9989           emitInlineAsmError(
9990               Call, "couldn't allocate output register for constraint '" +
9991                         Twine(OpInfo.ConstraintCode) + "'");
9992           return;
9993         }
9994 
9995         if (DetectWriteToReservedRegister())
9996           return;
9997 
9998         // Add information to the INLINEASM node to know that this register is
9999         // set.
10000         OpInfo.AssignedRegs.AddInlineAsmOperands(
10001             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10002                                   : InlineAsm::Kind::RegDef,
10003             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
10004       }
10005       break;
10006 
10007     case InlineAsm::isInput:
10008     case InlineAsm::isLabel: {
10009       SDValue InOperandVal = OpInfo.CallOperand;
10010 
10011       if (OpInfo.isMatchingInputConstraint()) {
10012         // If this is required to match an output register we have already set,
10013         // just use its register.
10014         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10015                                                   AsmNodeOperands);
10016         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10017         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10018           if (OpInfo.isIndirect) {
10019             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10020             emitInlineAsmError(Call, "inline asm not supported yet: "
10021                                      "don't know how to handle tied "
10022                                      "indirect register inputs");
10023             return;
10024           }
10025 
10026           SmallVector<unsigned, 4> Regs;
10027           MachineFunction &MF = DAG.getMachineFunction();
10028           MachineRegisterInfo &MRI = MF.getRegInfo();
10029           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10030           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
10031           Register TiedReg = R->getReg();
10032           MVT RegVT = R->getSimpleValueType(0);
10033           const TargetRegisterClass *RC =
10034               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
10035               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10036                                       : TRI.getMinimalPhysRegClass(TiedReg);
10037           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10038             Regs.push_back(MRI.createVirtualRegister(RC));
10039 
10040           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10041 
10042           SDLoc dl = getCurSDLoc();
10043           // Use the produced MatchedRegs object to
10044           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
10045           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
10046                                            OpInfo.getMatchedOperand(), dl, DAG,
10047                                            AsmNodeOperands);
10048           break;
10049         }
10050 
10051         assert(Flag.isMemKind() && "Unknown matching constraint!");
10052         assert(Flag.getNumOperandRegisters() == 1 &&
10053                "Unexpected number of operands");
10054         // Add information to the INLINEASM node to know about this input.
10055         // See InlineAsm.h isUseOperandTiedToDef.
10056         Flag.clearMemConstraint();
10057         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10058         AsmNodeOperands.push_back(DAG.getTargetConstant(
10059             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10060         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10061         break;
10062       }
10063 
10064       // Treat indirect 'X' constraint as memory.
10065       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10066           OpInfo.isIndirect)
10067         OpInfo.ConstraintType = TargetLowering::C_Memory;
10068 
10069       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10070           OpInfo.ConstraintType == TargetLowering::C_Other) {
10071         std::vector<SDValue> Ops;
10072         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10073                                           Ops, DAG);
10074         if (Ops.empty()) {
10075           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10076             if (isa<ConstantSDNode>(InOperandVal)) {
10077               emitInlineAsmError(Call, "value out of range for constraint '" +
10078                                            Twine(OpInfo.ConstraintCode) + "'");
10079               return;
10080             }
10081 
10082           emitInlineAsmError(Call,
10083                              "invalid operand for inline asm constraint '" +
10084                                  Twine(OpInfo.ConstraintCode) + "'");
10085           return;
10086         }
10087 
10088         // Add information to the INLINEASM node to know about this input.
10089         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10090         AsmNodeOperands.push_back(DAG.getTargetConstant(
10091             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10092         llvm::append_range(AsmNodeOperands, Ops);
10093         break;
10094       }
10095 
10096       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10097         assert((OpInfo.isIndirect ||
10098                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10099                "Operand must be indirect to be a mem!");
10100         assert(InOperandVal.getValueType() ==
10101                    TLI.getPointerTy(DAG.getDataLayout()) &&
10102                "Memory operands expect pointer values");
10103 
10104         const InlineAsm::ConstraintCode ConstraintID =
10105             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10106         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10107                "Failed to convert memory constraint code to constraint id.");
10108 
10109         // Add information to the INLINEASM node to know about this input.
10110         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10111         ResOpType.setMemConstraint(ConstraintID);
10112         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10113                                                         getCurSDLoc(),
10114                                                         MVT::i32));
10115         AsmNodeOperands.push_back(InOperandVal);
10116         break;
10117       }
10118 
10119       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10120         const InlineAsm::ConstraintCode ConstraintID =
10121             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10122         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10123                "Failed to convert memory constraint code to constraint id.");
10124 
10125         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10126 
10127         SDValue AsmOp = InOperandVal;
10128         if (isFunction(InOperandVal)) {
10129           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10130           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10131           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10132                                              InOperandVal.getValueType(),
10133                                              GA->getOffset());
10134         }
10135 
10136         // Add information to the INLINEASM node to know about this input.
10137         ResOpType.setMemConstraint(ConstraintID);
10138 
10139         AsmNodeOperands.push_back(
10140             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10141 
10142         AsmNodeOperands.push_back(AsmOp);
10143         break;
10144       }
10145 
10146       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10147           OpInfo.ConstraintType != TargetLowering::C_Register) {
10148         emitInlineAsmError(Call, "unknown asm constraint '" +
10149                                      Twine(OpInfo.ConstraintCode) + "'");
10150         return;
10151       }
10152 
10153       // TODO: Support this.
10154       if (OpInfo.isIndirect) {
10155         emitInlineAsmError(
10156             Call, "Don't know how to handle indirect register inputs yet "
10157                   "for constraint '" +
10158                       Twine(OpInfo.ConstraintCode) + "'");
10159         return;
10160       }
10161 
10162       // Copy the input into the appropriate registers.
10163       if (OpInfo.AssignedRegs.Regs.empty()) {
10164         emitInlineAsmError(Call,
10165                            "couldn't allocate input reg for constraint '" +
10166                                Twine(OpInfo.ConstraintCode) + "'");
10167         return;
10168       }
10169 
10170       if (DetectWriteToReservedRegister())
10171         return;
10172 
10173       SDLoc dl = getCurSDLoc();
10174 
10175       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10176                                         &Call);
10177 
10178       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10179                                                0, dl, DAG, AsmNodeOperands);
10180       break;
10181     }
10182     case InlineAsm::isClobber:
10183       // Add the clobbered value to the operand list, so that the register
10184       // allocator is aware that the physreg got clobbered.
10185       if (!OpInfo.AssignedRegs.Regs.empty())
10186         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10187                                                  false, 0, getCurSDLoc(), DAG,
10188                                                  AsmNodeOperands);
10189       break;
10190     }
10191   }
10192 
10193   // Finish up input operands.  Set the input chain and add the flag last.
10194   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10195   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10196 
10197   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10198   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10199                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10200   Glue = Chain.getValue(1);
10201 
10202   // Do additional work to generate outputs.
10203 
10204   SmallVector<EVT, 1> ResultVTs;
10205   SmallVector<SDValue, 1> ResultValues;
10206   SmallVector<SDValue, 8> OutChains;
10207 
10208   llvm::Type *CallResultType = Call.getType();
10209   ArrayRef<Type *> ResultTypes;
10210   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10211     ResultTypes = StructResult->elements();
10212   else if (!CallResultType->isVoidTy())
10213     ResultTypes = ArrayRef(CallResultType);
10214 
10215   auto CurResultType = ResultTypes.begin();
10216   auto handleRegAssign = [&](SDValue V) {
10217     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10218     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10219     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10220     ++CurResultType;
10221     // If the type of the inline asm call site return value is different but has
10222     // same size as the type of the asm output bitcast it.  One example of this
10223     // is for vectors with different width / number of elements.  This can
10224     // happen for register classes that can contain multiple different value
10225     // types.  The preg or vreg allocated may not have the same VT as was
10226     // expected.
10227     //
10228     // This can also happen for a return value that disagrees with the register
10229     // class it is put in, eg. a double in a general-purpose register on a
10230     // 32-bit machine.
10231     if (ResultVT != V.getValueType() &&
10232         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10233       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10234     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10235              V.getValueType().isInteger()) {
10236       // If a result value was tied to an input value, the computed result
10237       // may have a wider width than the expected result.  Extract the
10238       // relevant portion.
10239       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10240     }
10241     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10242     ResultVTs.push_back(ResultVT);
10243     ResultValues.push_back(V);
10244   };
10245 
10246   // Deal with output operands.
10247   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10248     if (OpInfo.Type == InlineAsm::isOutput) {
10249       SDValue Val;
10250       // Skip trivial output operands.
10251       if (OpInfo.AssignedRegs.Regs.empty())
10252         continue;
10253 
10254       switch (OpInfo.ConstraintType) {
10255       case TargetLowering::C_Register:
10256       case TargetLowering::C_RegisterClass:
10257         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10258                                                   Chain, &Glue, &Call);
10259         break;
10260       case TargetLowering::C_Immediate:
10261       case TargetLowering::C_Other:
10262         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10263                                               OpInfo, DAG);
10264         break;
10265       case TargetLowering::C_Memory:
10266         break; // Already handled.
10267       case TargetLowering::C_Address:
10268         break; // Silence warning.
10269       case TargetLowering::C_Unknown:
10270         assert(false && "Unexpected unknown constraint");
10271       }
10272 
10273       // Indirect output manifest as stores. Record output chains.
10274       if (OpInfo.isIndirect) {
10275         const Value *Ptr = OpInfo.CallOperandVal;
10276         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10277         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10278                                      MachinePointerInfo(Ptr));
10279         OutChains.push_back(Store);
10280       } else {
10281         // generate CopyFromRegs to associated registers.
10282         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10283         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10284           for (const SDValue &V : Val->op_values())
10285             handleRegAssign(V);
10286         } else
10287           handleRegAssign(Val);
10288       }
10289     }
10290   }
10291 
10292   // Set results.
10293   if (!ResultValues.empty()) {
10294     assert(CurResultType == ResultTypes.end() &&
10295            "Mismatch in number of ResultTypes");
10296     assert(ResultValues.size() == ResultTypes.size() &&
10297            "Mismatch in number of output operands in asm result");
10298 
10299     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10300                             DAG.getVTList(ResultVTs), ResultValues);
10301     setValue(&Call, V);
10302   }
10303 
10304   // Collect store chains.
10305   if (!OutChains.empty())
10306     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10307 
10308   if (EmitEHLabels) {
10309     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10310   }
10311 
10312   // Only Update Root if inline assembly has a memory effect.
10313   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10314       EmitEHLabels)
10315     DAG.setRoot(Chain);
10316 }
10317 
10318 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10319                                              const Twine &Message) {
10320   LLVMContext &Ctx = *DAG.getContext();
10321   Ctx.emitError(&Call, Message);
10322 
10323   // Make sure we leave the DAG in a valid state
10324   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10325   SmallVector<EVT, 1> ValueVTs;
10326   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10327 
10328   if (ValueVTs.empty())
10329     return;
10330 
10331   SmallVector<SDValue, 1> Ops;
10332   for (const EVT &VT : ValueVTs)
10333     Ops.push_back(DAG.getUNDEF(VT));
10334 
10335   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10336 }
10337 
10338 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10339   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10340                           MVT::Other, getRoot(),
10341                           getValue(I.getArgOperand(0)),
10342                           DAG.getSrcValue(I.getArgOperand(0))));
10343 }
10344 
10345 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10347   const DataLayout &DL = DAG.getDataLayout();
10348   SDValue V = DAG.getVAArg(
10349       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10350       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10351       DL.getABITypeAlign(I.getType()).value());
10352   DAG.setRoot(V.getValue(1));
10353 
10354   if (I.getType()->isPointerTy())
10355     V = DAG.getPtrExtOrTrunc(
10356         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10357   setValue(&I, V);
10358 }
10359 
10360 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10361   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10362                           MVT::Other, getRoot(),
10363                           getValue(I.getArgOperand(0)),
10364                           DAG.getSrcValue(I.getArgOperand(0))));
10365 }
10366 
10367 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10368   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10369                           MVT::Other, getRoot(),
10370                           getValue(I.getArgOperand(0)),
10371                           getValue(I.getArgOperand(1)),
10372                           DAG.getSrcValue(I.getArgOperand(0)),
10373                           DAG.getSrcValue(I.getArgOperand(1))));
10374 }
10375 
10376 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10377                                                     const Instruction &I,
10378                                                     SDValue Op) {
10379   std::optional<ConstantRange> CR = getRange(I);
10380 
10381   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10382     return Op;
10383 
10384   APInt Lo = CR->getUnsignedMin();
10385   if (!Lo.isMinValue())
10386     return Op;
10387 
10388   APInt Hi = CR->getUnsignedMax();
10389   unsigned Bits = std::max(Hi.getActiveBits(),
10390                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10391 
10392   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10393 
10394   SDLoc SL = getCurSDLoc();
10395 
10396   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10397                              DAG.getValueType(SmallVT));
10398   unsigned NumVals = Op.getNode()->getNumValues();
10399   if (NumVals == 1)
10400     return ZExt;
10401 
10402   SmallVector<SDValue, 4> Ops;
10403 
10404   Ops.push_back(ZExt);
10405   for (unsigned I = 1; I != NumVals; ++I)
10406     Ops.push_back(Op.getValue(I));
10407 
10408   return DAG.getMergeValues(Ops, SL);
10409 }
10410 
10411 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10412 /// the call being lowered.
10413 ///
10414 /// This is a helper for lowering intrinsics that follow a target calling
10415 /// convention or require stack pointer adjustment. Only a subset of the
10416 /// intrinsic's operands need to participate in the calling convention.
10417 void SelectionDAGBuilder::populateCallLoweringInfo(
10418     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10419     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10420     AttributeSet RetAttrs, bool IsPatchPoint) {
10421   TargetLowering::ArgListTy Args;
10422   Args.reserve(NumArgs);
10423 
10424   // Populate the argument list.
10425   // Attributes for args start at offset 1, after the return attribute.
10426   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10427        ArgI != ArgE; ++ArgI) {
10428     const Value *V = Call->getOperand(ArgI);
10429 
10430     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10431 
10432     TargetLowering::ArgListEntry Entry;
10433     Entry.Node = getValue(V);
10434     Entry.Ty = V->getType();
10435     Entry.setAttributes(Call, ArgI);
10436     Args.push_back(Entry);
10437   }
10438 
10439   CLI.setDebugLoc(getCurSDLoc())
10440       .setChain(getRoot())
10441       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10442                  RetAttrs)
10443       .setDiscardResult(Call->use_empty())
10444       .setIsPatchPoint(IsPatchPoint)
10445       .setIsPreallocated(
10446           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10447 }
10448 
10449 /// Add a stack map intrinsic call's live variable operands to a stackmap
10450 /// or patchpoint target node's operand list.
10451 ///
10452 /// Constants are converted to TargetConstants purely as an optimization to
10453 /// avoid constant materialization and register allocation.
10454 ///
10455 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10456 /// generate addess computation nodes, and so FinalizeISel can convert the
10457 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10458 /// address materialization and register allocation, but may also be required
10459 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10460 /// alloca in the entry block, then the runtime may assume that the alloca's
10461 /// StackMap location can be read immediately after compilation and that the
10462 /// location is valid at any point during execution (this is similar to the
10463 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10464 /// only available in a register, then the runtime would need to trap when
10465 /// execution reaches the StackMap in order to read the alloca's location.
10466 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10467                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10468                                 SelectionDAGBuilder &Builder) {
10469   SelectionDAG &DAG = Builder.DAG;
10470   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10471     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10472 
10473     // Things on the stack are pointer-typed, meaning that they are already
10474     // legal and can be emitted directly to target nodes.
10475     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10476       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10477     } else {
10478       // Otherwise emit a target independent node to be legalised.
10479       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10480     }
10481   }
10482 }
10483 
10484 /// Lower llvm.experimental.stackmap.
10485 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10486   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10487   //                                  [live variables...])
10488 
10489   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10490 
10491   SDValue Chain, InGlue, Callee;
10492   SmallVector<SDValue, 32> Ops;
10493 
10494   SDLoc DL = getCurSDLoc();
10495   Callee = getValue(CI.getCalledOperand());
10496 
10497   // The stackmap intrinsic only records the live variables (the arguments
10498   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10499   // intrinsic, this won't be lowered to a function call. This means we don't
10500   // have to worry about calling conventions and target specific lowering code.
10501   // Instead we perform the call lowering right here.
10502   //
10503   // chain, flag = CALLSEQ_START(chain, 0, 0)
10504   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10505   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10506   //
10507   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10508   InGlue = Chain.getValue(1);
10509 
10510   // Add the STACKMAP operands, starting with DAG house-keeping.
10511   Ops.push_back(Chain);
10512   Ops.push_back(InGlue);
10513 
10514   // Add the <id>, <numShadowBytes> operands.
10515   //
10516   // These do not require legalisation, and can be emitted directly to target
10517   // constant nodes.
10518   SDValue ID = getValue(CI.getArgOperand(0));
10519   assert(ID.getValueType() == MVT::i64);
10520   SDValue IDConst =
10521       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10522   Ops.push_back(IDConst);
10523 
10524   SDValue Shad = getValue(CI.getArgOperand(1));
10525   assert(Shad.getValueType() == MVT::i32);
10526   SDValue ShadConst =
10527       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10528   Ops.push_back(ShadConst);
10529 
10530   // Add the live variables.
10531   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10532 
10533   // Create the STACKMAP node.
10534   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10535   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10536   InGlue = Chain.getValue(1);
10537 
10538   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10539 
10540   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10541 
10542   // Set the root to the target-lowered call chain.
10543   DAG.setRoot(Chain);
10544 
10545   // Inform the Frame Information that we have a stackmap in this function.
10546   FuncInfo.MF->getFrameInfo().setHasStackMap();
10547 }
10548 
10549 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10550 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10551                                           const BasicBlock *EHPadBB) {
10552   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10553   //                                         i32 <numBytes>,
10554   //                                         i8* <target>,
10555   //                                         i32 <numArgs>,
10556   //                                         [Args...],
10557   //                                         [live variables...])
10558 
10559   CallingConv::ID CC = CB.getCallingConv();
10560   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10561   bool HasDef = !CB.getType()->isVoidTy();
10562   SDLoc dl = getCurSDLoc();
10563   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10564 
10565   // Handle immediate and symbolic callees.
10566   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10567     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10568                                    /*isTarget=*/true);
10569   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10570     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10571                                          SDLoc(SymbolicCallee),
10572                                          SymbolicCallee->getValueType(0));
10573 
10574   // Get the real number of arguments participating in the call <numArgs>
10575   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10576   unsigned NumArgs = NArgVal->getAsZExtVal();
10577 
10578   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10579   // Intrinsics include all meta-operands up to but not including CC.
10580   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10581   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10582          "Not enough arguments provided to the patchpoint intrinsic");
10583 
10584   // For AnyRegCC the arguments are lowered later on manually.
10585   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10586   Type *ReturnTy =
10587       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10588 
10589   TargetLowering::CallLoweringInfo CLI(DAG);
10590   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10591                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10592   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10593 
10594   SDNode *CallEnd = Result.second.getNode();
10595   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10596     CallEnd = CallEnd->getOperand(0).getNode();
10597   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10598     CallEnd = CallEnd->getOperand(0).getNode();
10599 
10600   /// Get a call instruction from the call sequence chain.
10601   /// Tail calls are not allowed.
10602   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10603          "Expected a callseq node.");
10604   SDNode *Call = CallEnd->getOperand(0).getNode();
10605   bool HasGlue = Call->getGluedNode();
10606 
10607   // Replace the target specific call node with the patchable intrinsic.
10608   SmallVector<SDValue, 8> Ops;
10609 
10610   // Push the chain.
10611   Ops.push_back(*(Call->op_begin()));
10612 
10613   // Optionally, push the glue (if any).
10614   if (HasGlue)
10615     Ops.push_back(*(Call->op_end() - 1));
10616 
10617   // Push the register mask info.
10618   if (HasGlue)
10619     Ops.push_back(*(Call->op_end() - 2));
10620   else
10621     Ops.push_back(*(Call->op_end() - 1));
10622 
10623   // Add the <id> and <numBytes> constants.
10624   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10625   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10626   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10627   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10628 
10629   // Add the callee.
10630   Ops.push_back(Callee);
10631 
10632   // Adjust <numArgs> to account for any arguments that have been passed on the
10633   // stack instead.
10634   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10635   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10636   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10637   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10638 
10639   // Add the calling convention
10640   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10641 
10642   // Add the arguments we omitted previously. The register allocator should
10643   // place these in any free register.
10644   if (IsAnyRegCC)
10645     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10646       Ops.push_back(getValue(CB.getArgOperand(i)));
10647 
10648   // Push the arguments from the call instruction.
10649   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10650   Ops.append(Call->op_begin() + 2, e);
10651 
10652   // Push live variables for the stack map.
10653   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10654 
10655   SDVTList NodeTys;
10656   if (IsAnyRegCC && HasDef) {
10657     // Create the return types based on the intrinsic definition
10658     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10659     SmallVector<EVT, 3> ValueVTs;
10660     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10661     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10662 
10663     // There is always a chain and a glue type at the end
10664     ValueVTs.push_back(MVT::Other);
10665     ValueVTs.push_back(MVT::Glue);
10666     NodeTys = DAG.getVTList(ValueVTs);
10667   } else
10668     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10669 
10670   // Replace the target specific call node with a PATCHPOINT node.
10671   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10672 
10673   // Update the NodeMap.
10674   if (HasDef) {
10675     if (IsAnyRegCC)
10676       setValue(&CB, SDValue(PPV.getNode(), 0));
10677     else
10678       setValue(&CB, Result.first);
10679   }
10680 
10681   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10682   // call sequence. Furthermore the location of the chain and glue can change
10683   // when the AnyReg calling convention is used and the intrinsic returns a
10684   // value.
10685   if (IsAnyRegCC && HasDef) {
10686     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10687     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10688     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10689   } else
10690     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10691   DAG.DeleteNode(Call);
10692 
10693   // Inform the Frame Information that we have a patchpoint in this function.
10694   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10695 }
10696 
10697 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10698                                             unsigned Intrinsic) {
10699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10700   SDValue Op1 = getValue(I.getArgOperand(0));
10701   SDValue Op2;
10702   if (I.arg_size() > 1)
10703     Op2 = getValue(I.getArgOperand(1));
10704   SDLoc dl = getCurSDLoc();
10705   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10706   SDValue Res;
10707   SDNodeFlags SDFlags;
10708   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10709     SDFlags.copyFMF(*FPMO);
10710 
10711   switch (Intrinsic) {
10712   case Intrinsic::vector_reduce_fadd:
10713     if (SDFlags.hasAllowReassociation())
10714       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10715                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10716                         SDFlags);
10717     else
10718       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10719     break;
10720   case Intrinsic::vector_reduce_fmul:
10721     if (SDFlags.hasAllowReassociation())
10722       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10723                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10724                         SDFlags);
10725     else
10726       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10727     break;
10728   case Intrinsic::vector_reduce_add:
10729     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10730     break;
10731   case Intrinsic::vector_reduce_mul:
10732     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10733     break;
10734   case Intrinsic::vector_reduce_and:
10735     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10736     break;
10737   case Intrinsic::vector_reduce_or:
10738     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10739     break;
10740   case Intrinsic::vector_reduce_xor:
10741     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10742     break;
10743   case Intrinsic::vector_reduce_smax:
10744     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10745     break;
10746   case Intrinsic::vector_reduce_smin:
10747     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10748     break;
10749   case Intrinsic::vector_reduce_umax:
10750     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10751     break;
10752   case Intrinsic::vector_reduce_umin:
10753     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10754     break;
10755   case Intrinsic::vector_reduce_fmax:
10756     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10757     break;
10758   case Intrinsic::vector_reduce_fmin:
10759     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10760     break;
10761   case Intrinsic::vector_reduce_fmaximum:
10762     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10763     break;
10764   case Intrinsic::vector_reduce_fminimum:
10765     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10766     break;
10767   default:
10768     llvm_unreachable("Unhandled vector reduce intrinsic");
10769   }
10770   setValue(&I, Res);
10771 }
10772 
10773 /// Returns an AttributeList representing the attributes applied to the return
10774 /// value of the given call.
10775 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10776   SmallVector<Attribute::AttrKind, 2> Attrs;
10777   if (CLI.RetSExt)
10778     Attrs.push_back(Attribute::SExt);
10779   if (CLI.RetZExt)
10780     Attrs.push_back(Attribute::ZExt);
10781   if (CLI.IsInReg)
10782     Attrs.push_back(Attribute::InReg);
10783 
10784   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10785                             Attrs);
10786 }
10787 
10788 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10789 /// implementation, which just calls LowerCall.
10790 /// FIXME: When all targets are
10791 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10792 std::pair<SDValue, SDValue>
10793 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10794   // Handle the incoming return values from the call.
10795   CLI.Ins.clear();
10796   Type *OrigRetTy = CLI.RetTy;
10797   SmallVector<EVT, 4> RetTys;
10798   SmallVector<TypeSize, 4> Offsets;
10799   auto &DL = CLI.DAG.getDataLayout();
10800   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10801 
10802   if (CLI.IsPostTypeLegalization) {
10803     // If we are lowering a libcall after legalization, split the return type.
10804     SmallVector<EVT, 4> OldRetTys;
10805     SmallVector<TypeSize, 4> OldOffsets;
10806     RetTys.swap(OldRetTys);
10807     Offsets.swap(OldOffsets);
10808 
10809     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10810       EVT RetVT = OldRetTys[i];
10811       uint64_t Offset = OldOffsets[i];
10812       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10813       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10814       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10815       RetTys.append(NumRegs, RegisterVT);
10816       for (unsigned j = 0; j != NumRegs; ++j)
10817         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10818     }
10819   }
10820 
10821   SmallVector<ISD::OutputArg, 4> Outs;
10822   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10823 
10824   bool CanLowerReturn =
10825       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10826                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10827 
10828   SDValue DemoteStackSlot;
10829   int DemoteStackIdx = -100;
10830   if (!CanLowerReturn) {
10831     // FIXME: equivalent assert?
10832     // assert(!CS.hasInAllocaArgument() &&
10833     //        "sret demotion is incompatible with inalloca");
10834     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10835     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10836     MachineFunction &MF = CLI.DAG.getMachineFunction();
10837     DemoteStackIdx =
10838         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10839     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10840                                               DL.getAllocaAddrSpace());
10841 
10842     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10843     ArgListEntry Entry;
10844     Entry.Node = DemoteStackSlot;
10845     Entry.Ty = StackSlotPtrType;
10846     Entry.IsSExt = false;
10847     Entry.IsZExt = false;
10848     Entry.IsInReg = false;
10849     Entry.IsSRet = true;
10850     Entry.IsNest = false;
10851     Entry.IsByVal = false;
10852     Entry.IsByRef = false;
10853     Entry.IsReturned = false;
10854     Entry.IsSwiftSelf = false;
10855     Entry.IsSwiftAsync = false;
10856     Entry.IsSwiftError = false;
10857     Entry.IsCFGuardTarget = false;
10858     Entry.Alignment = Alignment;
10859     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10860     CLI.NumFixedArgs += 1;
10861     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10862     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10863 
10864     // sret demotion isn't compatible with tail-calls, since the sret argument
10865     // points into the callers stack frame.
10866     CLI.IsTailCall = false;
10867   } else {
10868     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10869         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10870     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10871       ISD::ArgFlagsTy Flags;
10872       if (NeedsRegBlock) {
10873         Flags.setInConsecutiveRegs();
10874         if (I == RetTys.size() - 1)
10875           Flags.setInConsecutiveRegsLast();
10876       }
10877       EVT VT = RetTys[I];
10878       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10879                                                      CLI.CallConv, VT);
10880       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10881                                                        CLI.CallConv, VT);
10882       for (unsigned i = 0; i != NumRegs; ++i) {
10883         ISD::InputArg MyFlags;
10884         MyFlags.Flags = Flags;
10885         MyFlags.VT = RegisterVT;
10886         MyFlags.ArgVT = VT;
10887         MyFlags.Used = CLI.IsReturnValueUsed;
10888         if (CLI.RetTy->isPointerTy()) {
10889           MyFlags.Flags.setPointer();
10890           MyFlags.Flags.setPointerAddrSpace(
10891               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10892         }
10893         if (CLI.RetSExt)
10894           MyFlags.Flags.setSExt();
10895         if (CLI.RetZExt)
10896           MyFlags.Flags.setZExt();
10897         if (CLI.IsInReg)
10898           MyFlags.Flags.setInReg();
10899         CLI.Ins.push_back(MyFlags);
10900       }
10901     }
10902   }
10903 
10904   // We push in swifterror return as the last element of CLI.Ins.
10905   ArgListTy &Args = CLI.getArgs();
10906   if (supportSwiftError()) {
10907     for (const ArgListEntry &Arg : Args) {
10908       if (Arg.IsSwiftError) {
10909         ISD::InputArg MyFlags;
10910         MyFlags.VT = getPointerTy(DL);
10911         MyFlags.ArgVT = EVT(getPointerTy(DL));
10912         MyFlags.Flags.setSwiftError();
10913         CLI.Ins.push_back(MyFlags);
10914       }
10915     }
10916   }
10917 
10918   // Handle all of the outgoing arguments.
10919   CLI.Outs.clear();
10920   CLI.OutVals.clear();
10921   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10922     SmallVector<EVT, 4> ValueVTs;
10923     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10924     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10925     Type *FinalType = Args[i].Ty;
10926     if (Args[i].IsByVal)
10927       FinalType = Args[i].IndirectType;
10928     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10929         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10930     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10931          ++Value) {
10932       EVT VT = ValueVTs[Value];
10933       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10934       SDValue Op = SDValue(Args[i].Node.getNode(),
10935                            Args[i].Node.getResNo() + Value);
10936       ISD::ArgFlagsTy Flags;
10937 
10938       // Certain targets (such as MIPS), may have a different ABI alignment
10939       // for a type depending on the context. Give the target a chance to
10940       // specify the alignment it wants.
10941       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10942       Flags.setOrigAlign(OriginalAlignment);
10943 
10944       if (Args[i].Ty->isPointerTy()) {
10945         Flags.setPointer();
10946         Flags.setPointerAddrSpace(
10947             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10948       }
10949       if (Args[i].IsZExt)
10950         Flags.setZExt();
10951       if (Args[i].IsSExt)
10952         Flags.setSExt();
10953       if (Args[i].IsInReg) {
10954         // If we are using vectorcall calling convention, a structure that is
10955         // passed InReg - is surely an HVA
10956         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10957             isa<StructType>(FinalType)) {
10958           // The first value of a structure is marked
10959           if (0 == Value)
10960             Flags.setHvaStart();
10961           Flags.setHva();
10962         }
10963         // Set InReg Flag
10964         Flags.setInReg();
10965       }
10966       if (Args[i].IsSRet)
10967         Flags.setSRet();
10968       if (Args[i].IsSwiftSelf)
10969         Flags.setSwiftSelf();
10970       if (Args[i].IsSwiftAsync)
10971         Flags.setSwiftAsync();
10972       if (Args[i].IsSwiftError)
10973         Flags.setSwiftError();
10974       if (Args[i].IsCFGuardTarget)
10975         Flags.setCFGuardTarget();
10976       if (Args[i].IsByVal)
10977         Flags.setByVal();
10978       if (Args[i].IsByRef)
10979         Flags.setByRef();
10980       if (Args[i].IsPreallocated) {
10981         Flags.setPreallocated();
10982         // Set the byval flag for CCAssignFn callbacks that don't know about
10983         // preallocated.  This way we can know how many bytes we should've
10984         // allocated and how many bytes a callee cleanup function will pop.  If
10985         // we port preallocated to more targets, we'll have to add custom
10986         // preallocated handling in the various CC lowering callbacks.
10987         Flags.setByVal();
10988       }
10989       if (Args[i].IsInAlloca) {
10990         Flags.setInAlloca();
10991         // Set the byval flag for CCAssignFn callbacks that don't know about
10992         // inalloca.  This way we can know how many bytes we should've allocated
10993         // and how many bytes a callee cleanup function will pop.  If we port
10994         // inalloca to more targets, we'll have to add custom inalloca handling
10995         // in the various CC lowering callbacks.
10996         Flags.setByVal();
10997       }
10998       Align MemAlign;
10999       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11000         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11001         Flags.setByValSize(FrameSize);
11002 
11003         // info is not there but there are cases it cannot get right.
11004         if (auto MA = Args[i].Alignment)
11005           MemAlign = *MA;
11006         else
11007           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
11008       } else if (auto MA = Args[i].Alignment) {
11009         MemAlign = *MA;
11010       } else {
11011         MemAlign = OriginalAlignment;
11012       }
11013       Flags.setMemAlign(MemAlign);
11014       if (Args[i].IsNest)
11015         Flags.setNest();
11016       if (NeedsRegBlock)
11017         Flags.setInConsecutiveRegs();
11018 
11019       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11020                                                  CLI.CallConv, VT);
11021       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11022                                                         CLI.CallConv, VT);
11023       SmallVector<SDValue, 4> Parts(NumParts);
11024       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11025 
11026       if (Args[i].IsSExt)
11027         ExtendKind = ISD::SIGN_EXTEND;
11028       else if (Args[i].IsZExt)
11029         ExtendKind = ISD::ZERO_EXTEND;
11030 
11031       // Conservatively only handle 'returned' on non-vectors that can be lowered,
11032       // for now.
11033       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11034           CanLowerReturn) {
11035         assert((CLI.RetTy == Args[i].Ty ||
11036                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11037                  CLI.RetTy->getPointerAddressSpace() ==
11038                      Args[i].Ty->getPointerAddressSpace())) &&
11039                RetTys.size() == NumValues && "unexpected use of 'returned'");
11040         // Before passing 'returned' to the target lowering code, ensure that
11041         // either the register MVT and the actual EVT are the same size or that
11042         // the return value and argument are extended in the same way; in these
11043         // cases it's safe to pass the argument register value unchanged as the
11044         // return register value (although it's at the target's option whether
11045         // to do so)
11046         // TODO: allow code generation to take advantage of partially preserved
11047         // registers rather than clobbering the entire register when the
11048         // parameter extension method is not compatible with the return
11049         // extension method
11050         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11051             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11052              CLI.RetZExt == Args[i].IsZExt))
11053           Flags.setReturned();
11054       }
11055 
11056       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11057                      CLI.CallConv, ExtendKind);
11058 
11059       for (unsigned j = 0; j != NumParts; ++j) {
11060         // if it isn't first piece, alignment must be 1
11061         // For scalable vectors the scalable part is currently handled
11062         // by individual targets, so we just use the known minimum size here.
11063         ISD::OutputArg MyFlags(
11064             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11065             i < CLI.NumFixedArgs, i,
11066             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11067         if (NumParts > 1 && j == 0)
11068           MyFlags.Flags.setSplit();
11069         else if (j != 0) {
11070           MyFlags.Flags.setOrigAlign(Align(1));
11071           if (j == NumParts - 1)
11072             MyFlags.Flags.setSplitEnd();
11073         }
11074 
11075         CLI.Outs.push_back(MyFlags);
11076         CLI.OutVals.push_back(Parts[j]);
11077       }
11078 
11079       if (NeedsRegBlock && Value == NumValues - 1)
11080         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11081     }
11082   }
11083 
11084   SmallVector<SDValue, 4> InVals;
11085   CLI.Chain = LowerCall(CLI, InVals);
11086 
11087   // Update CLI.InVals to use outside of this function.
11088   CLI.InVals = InVals;
11089 
11090   // Verify that the target's LowerCall behaved as expected.
11091   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11092          "LowerCall didn't return a valid chain!");
11093   assert((!CLI.IsTailCall || InVals.empty()) &&
11094          "LowerCall emitted a return value for a tail call!");
11095   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11096          "LowerCall didn't emit the correct number of values!");
11097 
11098   // For a tail call, the return value is merely live-out and there aren't
11099   // any nodes in the DAG representing it. Return a special value to
11100   // indicate that a tail call has been emitted and no more Instructions
11101   // should be processed in the current block.
11102   if (CLI.IsTailCall) {
11103     CLI.DAG.setRoot(CLI.Chain);
11104     return std::make_pair(SDValue(), SDValue());
11105   }
11106 
11107 #ifndef NDEBUG
11108   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11109     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11110     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11111            "LowerCall emitted a value with the wrong type!");
11112   }
11113 #endif
11114 
11115   SmallVector<SDValue, 4> ReturnValues;
11116   if (!CanLowerReturn) {
11117     // The instruction result is the result of loading from the
11118     // hidden sret parameter.
11119     SmallVector<EVT, 1> PVTs;
11120     Type *PtrRetTy =
11121         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11122 
11123     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11124     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11125     EVT PtrVT = PVTs[0];
11126 
11127     unsigned NumValues = RetTys.size();
11128     ReturnValues.resize(NumValues);
11129     SmallVector<SDValue, 4> Chains(NumValues);
11130 
11131     // An aggregate return value cannot wrap around the address space, so
11132     // offsets to its parts don't wrap either.
11133     SDNodeFlags Flags;
11134     Flags.setNoUnsignedWrap(true);
11135 
11136     MachineFunction &MF = CLI.DAG.getMachineFunction();
11137     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11138     for (unsigned i = 0; i < NumValues; ++i) {
11139       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11140                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
11141                                                         PtrVT), Flags);
11142       SDValue L = CLI.DAG.getLoad(
11143           RetTys[i], CLI.DL, CLI.Chain, Add,
11144           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11145                                             DemoteStackIdx, Offsets[i]),
11146           HiddenSRetAlign);
11147       ReturnValues[i] = L;
11148       Chains[i] = L.getValue(1);
11149     }
11150 
11151     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11152   } else {
11153     // Collect the legal value parts into potentially illegal values
11154     // that correspond to the original function's return values.
11155     std::optional<ISD::NodeType> AssertOp;
11156     if (CLI.RetSExt)
11157       AssertOp = ISD::AssertSext;
11158     else if (CLI.RetZExt)
11159       AssertOp = ISD::AssertZext;
11160     unsigned CurReg = 0;
11161     for (EVT VT : RetTys) {
11162       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11163                                                      CLI.CallConv, VT);
11164       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11165                                                        CLI.CallConv, VT);
11166 
11167       ReturnValues.push_back(getCopyFromParts(
11168           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11169           CLI.Chain, CLI.CallConv, AssertOp));
11170       CurReg += NumRegs;
11171     }
11172 
11173     // For a function returning void, there is no return value. We can't create
11174     // such a node, so we just return a null return value in that case. In
11175     // that case, nothing will actually look at the value.
11176     if (ReturnValues.empty())
11177       return std::make_pair(SDValue(), CLI.Chain);
11178   }
11179 
11180   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11181                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11182   return std::make_pair(Res, CLI.Chain);
11183 }
11184 
11185 /// Places new result values for the node in Results (their number
11186 /// and types must exactly match those of the original return values of
11187 /// the node), or leaves Results empty, which indicates that the node is not
11188 /// to be custom lowered after all.
11189 void TargetLowering::LowerOperationWrapper(SDNode *N,
11190                                            SmallVectorImpl<SDValue> &Results,
11191                                            SelectionDAG &DAG) const {
11192   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11193 
11194   if (!Res.getNode())
11195     return;
11196 
11197   // If the original node has one result, take the return value from
11198   // LowerOperation as is. It might not be result number 0.
11199   if (N->getNumValues() == 1) {
11200     Results.push_back(Res);
11201     return;
11202   }
11203 
11204   // If the original node has multiple results, then the return node should
11205   // have the same number of results.
11206   assert((N->getNumValues() == Res->getNumValues()) &&
11207       "Lowering returned the wrong number of results!");
11208 
11209   // Places new result values base on N result number.
11210   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11211     Results.push_back(Res.getValue(I));
11212 }
11213 
11214 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11215   llvm_unreachable("LowerOperation not implemented for this target!");
11216 }
11217 
11218 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11219                                                      unsigned Reg,
11220                                                      ISD::NodeType ExtendType) {
11221   SDValue Op = getNonRegisterValue(V);
11222   assert((Op.getOpcode() != ISD::CopyFromReg ||
11223           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11224          "Copy from a reg to the same reg!");
11225   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11226 
11227   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11228   // If this is an InlineAsm we have to match the registers required, not the
11229   // notional registers required by the type.
11230 
11231   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11232                    std::nullopt); // This is not an ABI copy.
11233   SDValue Chain = DAG.getEntryNode();
11234 
11235   if (ExtendType == ISD::ANY_EXTEND) {
11236     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11237     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11238       ExtendType = PreferredExtendIt->second;
11239   }
11240   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11241   PendingExports.push_back(Chain);
11242 }
11243 
11244 #include "llvm/CodeGen/SelectionDAGISel.h"
11245 
11246 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11247 /// entry block, return true.  This includes arguments used by switches, since
11248 /// the switch may expand into multiple basic blocks.
11249 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11250   // With FastISel active, we may be splitting blocks, so force creation
11251   // of virtual registers for all non-dead arguments.
11252   if (FastISel)
11253     return A->use_empty();
11254 
11255   const BasicBlock &Entry = A->getParent()->front();
11256   for (const User *U : A->users())
11257     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11258       return false;  // Use not in entry block.
11259 
11260   return true;
11261 }
11262 
11263 using ArgCopyElisionMapTy =
11264     DenseMap<const Argument *,
11265              std::pair<const AllocaInst *, const StoreInst *>>;
11266 
11267 /// Scan the entry block of the function in FuncInfo for arguments that look
11268 /// like copies into a local alloca. Record any copied arguments in
11269 /// ArgCopyElisionCandidates.
11270 static void
11271 findArgumentCopyElisionCandidates(const DataLayout &DL,
11272                                   FunctionLoweringInfo *FuncInfo,
11273                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11274   // Record the state of every static alloca used in the entry block. Argument
11275   // allocas are all used in the entry block, so we need approximately as many
11276   // entries as we have arguments.
11277   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11278   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11279   unsigned NumArgs = FuncInfo->Fn->arg_size();
11280   StaticAllocas.reserve(NumArgs * 2);
11281 
11282   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11283     if (!V)
11284       return nullptr;
11285     V = V->stripPointerCasts();
11286     const auto *AI = dyn_cast<AllocaInst>(V);
11287     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11288       return nullptr;
11289     auto Iter = StaticAllocas.insert({AI, Unknown});
11290     return &Iter.first->second;
11291   };
11292 
11293   // Look for stores of arguments to static allocas. Look through bitcasts and
11294   // GEPs to handle type coercions, as long as the alloca is fully initialized
11295   // by the store. Any non-store use of an alloca escapes it and any subsequent
11296   // unanalyzed store might write it.
11297   // FIXME: Handle structs initialized with multiple stores.
11298   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11299     // Look for stores, and handle non-store uses conservatively.
11300     const auto *SI = dyn_cast<StoreInst>(&I);
11301     if (!SI) {
11302       // We will look through cast uses, so ignore them completely.
11303       if (I.isCast())
11304         continue;
11305       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11306       // to allocas.
11307       if (I.isDebugOrPseudoInst())
11308         continue;
11309       // This is an unknown instruction. Assume it escapes or writes to all
11310       // static alloca operands.
11311       for (const Use &U : I.operands()) {
11312         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11313           *Info = StaticAllocaInfo::Clobbered;
11314       }
11315       continue;
11316     }
11317 
11318     // If the stored value is a static alloca, mark it as escaped.
11319     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11320       *Info = StaticAllocaInfo::Clobbered;
11321 
11322     // Check if the destination is a static alloca.
11323     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11324     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11325     if (!Info)
11326       continue;
11327     const AllocaInst *AI = cast<AllocaInst>(Dst);
11328 
11329     // Skip allocas that have been initialized or clobbered.
11330     if (*Info != StaticAllocaInfo::Unknown)
11331       continue;
11332 
11333     // Check if the stored value is an argument, and that this store fully
11334     // initializes the alloca.
11335     // If the argument type has padding bits we can't directly forward a pointer
11336     // as the upper bits may contain garbage.
11337     // Don't elide copies from the same argument twice.
11338     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11339     const auto *Arg = dyn_cast<Argument>(Val);
11340     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11341         Arg->getType()->isEmptyTy() ||
11342         DL.getTypeStoreSize(Arg->getType()) !=
11343             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11344         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11345         ArgCopyElisionCandidates.count(Arg)) {
11346       *Info = StaticAllocaInfo::Clobbered;
11347       continue;
11348     }
11349 
11350     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11351                       << '\n');
11352 
11353     // Mark this alloca and store for argument copy elision.
11354     *Info = StaticAllocaInfo::Elidable;
11355     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11356 
11357     // Stop scanning if we've seen all arguments. This will happen early in -O0
11358     // builds, which is useful, because -O0 builds have large entry blocks and
11359     // many allocas.
11360     if (ArgCopyElisionCandidates.size() == NumArgs)
11361       break;
11362   }
11363 }
11364 
11365 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11366 /// ArgVal is a load from a suitable fixed stack object.
11367 static void tryToElideArgumentCopy(
11368     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11369     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11370     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11371     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11372     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11373   // Check if this is a load from a fixed stack object.
11374   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11375   if (!LNode)
11376     return;
11377   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11378   if (!FINode)
11379     return;
11380 
11381   // Check that the fixed stack object is the right size and alignment.
11382   // Look at the alignment that the user wrote on the alloca instead of looking
11383   // at the stack object.
11384   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11385   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11386   const AllocaInst *AI = ArgCopyIter->second.first;
11387   int FixedIndex = FINode->getIndex();
11388   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11389   int OldIndex = AllocaIndex;
11390   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11391   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11392     LLVM_DEBUG(
11393         dbgs() << "  argument copy elision failed due to bad fixed stack "
11394                   "object size\n");
11395     return;
11396   }
11397   Align RequiredAlignment = AI->getAlign();
11398   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11399     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11400                          "greater than stack argument alignment ("
11401                       << DebugStr(RequiredAlignment) << " vs "
11402                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11403     return;
11404   }
11405 
11406   // Perform the elision. Delete the old stack object and replace its only use
11407   // in the variable info map. Mark the stack object as mutable and aliased.
11408   LLVM_DEBUG({
11409     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11410            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11411            << '\n';
11412   });
11413   MFI.RemoveStackObject(OldIndex);
11414   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11415   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11416   AllocaIndex = FixedIndex;
11417   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11418   for (SDValue ArgVal : ArgVals)
11419     Chains.push_back(ArgVal.getValue(1));
11420 
11421   // Avoid emitting code for the store implementing the copy.
11422   const StoreInst *SI = ArgCopyIter->second.second;
11423   ElidedArgCopyInstrs.insert(SI);
11424 
11425   // Check for uses of the argument again so that we can avoid exporting ArgVal
11426   // if it is't used by anything other than the store.
11427   for (const Value *U : Arg.users()) {
11428     if (U != SI) {
11429       ArgHasUses = true;
11430       break;
11431     }
11432   }
11433 }
11434 
11435 void SelectionDAGISel::LowerArguments(const Function &F) {
11436   SelectionDAG &DAG = SDB->DAG;
11437   SDLoc dl = SDB->getCurSDLoc();
11438   const DataLayout &DL = DAG.getDataLayout();
11439   SmallVector<ISD::InputArg, 16> Ins;
11440 
11441   // In Naked functions we aren't going to save any registers.
11442   if (F.hasFnAttribute(Attribute::Naked))
11443     return;
11444 
11445   if (!FuncInfo->CanLowerReturn) {
11446     // Put in an sret pointer parameter before all the other parameters.
11447     SmallVector<EVT, 1> ValueVTs;
11448     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11449                     PointerType::get(F.getContext(),
11450                                      DAG.getDataLayout().getAllocaAddrSpace()),
11451                     ValueVTs);
11452 
11453     // NOTE: Assuming that a pointer will never break down to more than one VT
11454     // or one register.
11455     ISD::ArgFlagsTy Flags;
11456     Flags.setSRet();
11457     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11458     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11459                          ISD::InputArg::NoArgIndex, 0);
11460     Ins.push_back(RetArg);
11461   }
11462 
11463   // Look for stores of arguments to static allocas. Mark such arguments with a
11464   // flag to ask the target to give us the memory location of that argument if
11465   // available.
11466   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11467   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11468                                     ArgCopyElisionCandidates);
11469 
11470   // Set up the incoming argument description vector.
11471   for (const Argument &Arg : F.args()) {
11472     unsigned ArgNo = Arg.getArgNo();
11473     SmallVector<EVT, 4> ValueVTs;
11474     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11475     bool isArgValueUsed = !Arg.use_empty();
11476     unsigned PartBase = 0;
11477     Type *FinalType = Arg.getType();
11478     if (Arg.hasAttribute(Attribute::ByVal))
11479       FinalType = Arg.getParamByValType();
11480     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11481         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11482     for (unsigned Value = 0, NumValues = ValueVTs.size();
11483          Value != NumValues; ++Value) {
11484       EVT VT = ValueVTs[Value];
11485       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11486       ISD::ArgFlagsTy Flags;
11487 
11488 
11489       if (Arg.getType()->isPointerTy()) {
11490         Flags.setPointer();
11491         Flags.setPointerAddrSpace(
11492             cast<PointerType>(Arg.getType())->getAddressSpace());
11493       }
11494       if (Arg.hasAttribute(Attribute::ZExt))
11495         Flags.setZExt();
11496       if (Arg.hasAttribute(Attribute::SExt))
11497         Flags.setSExt();
11498       if (Arg.hasAttribute(Attribute::InReg)) {
11499         // If we are using vectorcall calling convention, a structure that is
11500         // passed InReg - is surely an HVA
11501         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11502             isa<StructType>(Arg.getType())) {
11503           // The first value of a structure is marked
11504           if (0 == Value)
11505             Flags.setHvaStart();
11506           Flags.setHva();
11507         }
11508         // Set InReg Flag
11509         Flags.setInReg();
11510       }
11511       if (Arg.hasAttribute(Attribute::StructRet))
11512         Flags.setSRet();
11513       if (Arg.hasAttribute(Attribute::SwiftSelf))
11514         Flags.setSwiftSelf();
11515       if (Arg.hasAttribute(Attribute::SwiftAsync))
11516         Flags.setSwiftAsync();
11517       if (Arg.hasAttribute(Attribute::SwiftError))
11518         Flags.setSwiftError();
11519       if (Arg.hasAttribute(Attribute::ByVal))
11520         Flags.setByVal();
11521       if (Arg.hasAttribute(Attribute::ByRef))
11522         Flags.setByRef();
11523       if (Arg.hasAttribute(Attribute::InAlloca)) {
11524         Flags.setInAlloca();
11525         // Set the byval flag for CCAssignFn callbacks that don't know about
11526         // inalloca.  This way we can know how many bytes we should've allocated
11527         // and how many bytes a callee cleanup function will pop.  If we port
11528         // inalloca to more targets, we'll have to add custom inalloca handling
11529         // in the various CC lowering callbacks.
11530         Flags.setByVal();
11531       }
11532       if (Arg.hasAttribute(Attribute::Preallocated)) {
11533         Flags.setPreallocated();
11534         // Set the byval flag for CCAssignFn callbacks that don't know about
11535         // preallocated.  This way we can know how many bytes we should've
11536         // allocated and how many bytes a callee cleanup function will pop.  If
11537         // we port preallocated to more targets, we'll have to add custom
11538         // preallocated handling in the various CC lowering callbacks.
11539         Flags.setByVal();
11540       }
11541 
11542       // Certain targets (such as MIPS), may have a different ABI alignment
11543       // for a type depending on the context. Give the target a chance to
11544       // specify the alignment it wants.
11545       const Align OriginalAlignment(
11546           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11547       Flags.setOrigAlign(OriginalAlignment);
11548 
11549       Align MemAlign;
11550       Type *ArgMemTy = nullptr;
11551       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11552           Flags.isByRef()) {
11553         if (!ArgMemTy)
11554           ArgMemTy = Arg.getPointeeInMemoryValueType();
11555 
11556         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11557 
11558         // For in-memory arguments, size and alignment should be passed from FE.
11559         // BE will guess if this info is not there but there are cases it cannot
11560         // get right.
11561         if (auto ParamAlign = Arg.getParamStackAlign())
11562           MemAlign = *ParamAlign;
11563         else if ((ParamAlign = Arg.getParamAlign()))
11564           MemAlign = *ParamAlign;
11565         else
11566           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11567         if (Flags.isByRef())
11568           Flags.setByRefSize(MemSize);
11569         else
11570           Flags.setByValSize(MemSize);
11571       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11572         MemAlign = *ParamAlign;
11573       } else {
11574         MemAlign = OriginalAlignment;
11575       }
11576       Flags.setMemAlign(MemAlign);
11577 
11578       if (Arg.hasAttribute(Attribute::Nest))
11579         Flags.setNest();
11580       if (NeedsRegBlock)
11581         Flags.setInConsecutiveRegs();
11582       if (ArgCopyElisionCandidates.count(&Arg))
11583         Flags.setCopyElisionCandidate();
11584       if (Arg.hasAttribute(Attribute::Returned))
11585         Flags.setReturned();
11586 
11587       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11588           *CurDAG->getContext(), F.getCallingConv(), VT);
11589       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11590           *CurDAG->getContext(), F.getCallingConv(), VT);
11591       for (unsigned i = 0; i != NumRegs; ++i) {
11592         // For scalable vectors, use the minimum size; individual targets
11593         // are responsible for handling scalable vector arguments and
11594         // return values.
11595         ISD::InputArg MyFlags(
11596             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11597             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11598         if (NumRegs > 1 && i == 0)
11599           MyFlags.Flags.setSplit();
11600         // if it isn't first piece, alignment must be 1
11601         else if (i > 0) {
11602           MyFlags.Flags.setOrigAlign(Align(1));
11603           if (i == NumRegs - 1)
11604             MyFlags.Flags.setSplitEnd();
11605         }
11606         Ins.push_back(MyFlags);
11607       }
11608       if (NeedsRegBlock && Value == NumValues - 1)
11609         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11610       PartBase += VT.getStoreSize().getKnownMinValue();
11611     }
11612   }
11613 
11614   // Call the target to set up the argument values.
11615   SmallVector<SDValue, 8> InVals;
11616   SDValue NewRoot = TLI->LowerFormalArguments(
11617       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11618 
11619   // Verify that the target's LowerFormalArguments behaved as expected.
11620   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11621          "LowerFormalArguments didn't return a valid chain!");
11622   assert(InVals.size() == Ins.size() &&
11623          "LowerFormalArguments didn't emit the correct number of values!");
11624   LLVM_DEBUG({
11625     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11626       assert(InVals[i].getNode() &&
11627              "LowerFormalArguments emitted a null value!");
11628       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11629              "LowerFormalArguments emitted a value with the wrong type!");
11630     }
11631   });
11632 
11633   // Update the DAG with the new chain value resulting from argument lowering.
11634   DAG.setRoot(NewRoot);
11635 
11636   // Set up the argument values.
11637   unsigned i = 0;
11638   if (!FuncInfo->CanLowerReturn) {
11639     // Create a virtual register for the sret pointer, and put in a copy
11640     // from the sret argument into it.
11641     SmallVector<EVT, 1> ValueVTs;
11642     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11643                     PointerType::get(F.getContext(),
11644                                      DAG.getDataLayout().getAllocaAddrSpace()),
11645                     ValueVTs);
11646     MVT VT = ValueVTs[0].getSimpleVT();
11647     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11648     std::optional<ISD::NodeType> AssertOp;
11649     SDValue ArgValue =
11650         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11651                          F.getCallingConv(), AssertOp);
11652 
11653     MachineFunction& MF = SDB->DAG.getMachineFunction();
11654     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11655     Register SRetReg =
11656         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11657     FuncInfo->DemoteRegister = SRetReg;
11658     NewRoot =
11659         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11660     DAG.setRoot(NewRoot);
11661 
11662     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11663     ++i;
11664   }
11665 
11666   SmallVector<SDValue, 4> Chains;
11667   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11668   for (const Argument &Arg : F.args()) {
11669     SmallVector<SDValue, 4> ArgValues;
11670     SmallVector<EVT, 4> ValueVTs;
11671     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11672     unsigned NumValues = ValueVTs.size();
11673     if (NumValues == 0)
11674       continue;
11675 
11676     bool ArgHasUses = !Arg.use_empty();
11677 
11678     // Elide the copying store if the target loaded this argument from a
11679     // suitable fixed stack object.
11680     if (Ins[i].Flags.isCopyElisionCandidate()) {
11681       unsigned NumParts = 0;
11682       for (EVT VT : ValueVTs)
11683         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11684                                                        F.getCallingConv(), VT);
11685 
11686       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11687                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11688                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11689     }
11690 
11691     // If this argument is unused then remember its value. It is used to generate
11692     // debugging information.
11693     bool isSwiftErrorArg =
11694         TLI->supportSwiftError() &&
11695         Arg.hasAttribute(Attribute::SwiftError);
11696     if (!ArgHasUses && !isSwiftErrorArg) {
11697       SDB->setUnusedArgValue(&Arg, InVals[i]);
11698 
11699       // Also remember any frame index for use in FastISel.
11700       if (FrameIndexSDNode *FI =
11701           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11702         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11703     }
11704 
11705     for (unsigned Val = 0; Val != NumValues; ++Val) {
11706       EVT VT = ValueVTs[Val];
11707       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11708                                                       F.getCallingConv(), VT);
11709       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11710           *CurDAG->getContext(), F.getCallingConv(), VT);
11711 
11712       // Even an apparent 'unused' swifterror argument needs to be returned. So
11713       // we do generate a copy for it that can be used on return from the
11714       // function.
11715       if (ArgHasUses || isSwiftErrorArg) {
11716         std::optional<ISD::NodeType> AssertOp;
11717         if (Arg.hasAttribute(Attribute::SExt))
11718           AssertOp = ISD::AssertSext;
11719         else if (Arg.hasAttribute(Attribute::ZExt))
11720           AssertOp = ISD::AssertZext;
11721 
11722         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11723                                              PartVT, VT, nullptr, NewRoot,
11724                                              F.getCallingConv(), AssertOp));
11725       }
11726 
11727       i += NumParts;
11728     }
11729 
11730     // We don't need to do anything else for unused arguments.
11731     if (ArgValues.empty())
11732       continue;
11733 
11734     // Note down frame index.
11735     if (FrameIndexSDNode *FI =
11736         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11737       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11738 
11739     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11740                                      SDB->getCurSDLoc());
11741 
11742     SDB->setValue(&Arg, Res);
11743     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11744       // We want to associate the argument with the frame index, among
11745       // involved operands, that correspond to the lowest address. The
11746       // getCopyFromParts function, called earlier, is swapping the order of
11747       // the operands to BUILD_PAIR depending on endianness. The result of
11748       // that swapping is that the least significant bits of the argument will
11749       // be in the first operand of the BUILD_PAIR node, and the most
11750       // significant bits will be in the second operand.
11751       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11752       if (LoadSDNode *LNode =
11753           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11754         if (FrameIndexSDNode *FI =
11755             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11756           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11757     }
11758 
11759     // Analyses past this point are naive and don't expect an assertion.
11760     if (Res.getOpcode() == ISD::AssertZext)
11761       Res = Res.getOperand(0);
11762 
11763     // Update the SwiftErrorVRegDefMap.
11764     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11765       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11766       if (Register::isVirtualRegister(Reg))
11767         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11768                                    Reg);
11769     }
11770 
11771     // If this argument is live outside of the entry block, insert a copy from
11772     // wherever we got it to the vreg that other BB's will reference it as.
11773     if (Res.getOpcode() == ISD::CopyFromReg) {
11774       // If we can, though, try to skip creating an unnecessary vreg.
11775       // FIXME: This isn't very clean... it would be nice to make this more
11776       // general.
11777       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11778       if (Register::isVirtualRegister(Reg)) {
11779         FuncInfo->ValueMap[&Arg] = Reg;
11780         continue;
11781       }
11782     }
11783     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11784       FuncInfo->InitializeRegForValue(&Arg);
11785       SDB->CopyToExportRegsIfNeeded(&Arg);
11786     }
11787   }
11788 
11789   if (!Chains.empty()) {
11790     Chains.push_back(NewRoot);
11791     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11792   }
11793 
11794   DAG.setRoot(NewRoot);
11795 
11796   assert(i == InVals.size() && "Argument register count mismatch!");
11797 
11798   // If any argument copy elisions occurred and we have debug info, update the
11799   // stale frame indices used in the dbg.declare variable info table.
11800   if (!ArgCopyElisionFrameIndexMap.empty()) {
11801     for (MachineFunction::VariableDbgInfo &VI :
11802          MF->getInStackSlotVariableDbgInfo()) {
11803       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11804       if (I != ArgCopyElisionFrameIndexMap.end())
11805         VI.updateStackSlot(I->second);
11806     }
11807   }
11808 
11809   // Finally, if the target has anything special to do, allow it to do so.
11810   emitFunctionEntryCode();
11811 }
11812 
11813 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11814 /// ensure constants are generated when needed.  Remember the virtual registers
11815 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11816 /// directly add them, because expansion might result in multiple MBB's for one
11817 /// BB.  As such, the start of the BB might correspond to a different MBB than
11818 /// the end.
11819 void
11820 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11821   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11822 
11823   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11824 
11825   // Check PHI nodes in successors that expect a value to be available from this
11826   // block.
11827   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11828     if (!isa<PHINode>(SuccBB->begin())) continue;
11829     MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
11830 
11831     // If this terminator has multiple identical successors (common for
11832     // switches), only handle each succ once.
11833     if (!SuccsHandled.insert(SuccMBB).second)
11834       continue;
11835 
11836     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11837 
11838     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11839     // nodes and Machine PHI nodes, but the incoming operands have not been
11840     // emitted yet.
11841     for (const PHINode &PN : SuccBB->phis()) {
11842       // Ignore dead phi's.
11843       if (PN.use_empty())
11844         continue;
11845 
11846       // Skip empty types
11847       if (PN.getType()->isEmptyTy())
11848         continue;
11849 
11850       unsigned Reg;
11851       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11852 
11853       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11854         unsigned &RegOut = ConstantsOut[C];
11855         if (RegOut == 0) {
11856           RegOut = FuncInfo.CreateRegs(C);
11857           // We need to zero/sign extend ConstantInt phi operands to match
11858           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11859           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11860           if (auto *CI = dyn_cast<ConstantInt>(C))
11861             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11862                                                     : ISD::ZERO_EXTEND;
11863           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11864         }
11865         Reg = RegOut;
11866       } else {
11867         DenseMap<const Value *, Register>::iterator I =
11868           FuncInfo.ValueMap.find(PHIOp);
11869         if (I != FuncInfo.ValueMap.end())
11870           Reg = I->second;
11871         else {
11872           assert(isa<AllocaInst>(PHIOp) &&
11873                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11874                  "Didn't codegen value into a register!??");
11875           Reg = FuncInfo.CreateRegs(PHIOp);
11876           CopyValueToVirtualRegister(PHIOp, Reg);
11877         }
11878       }
11879 
11880       // Remember that this register needs to added to the machine PHI node as
11881       // the input for this MBB.
11882       SmallVector<EVT, 4> ValueVTs;
11883       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11884       for (EVT VT : ValueVTs) {
11885         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11886         for (unsigned i = 0; i != NumRegisters; ++i)
11887           FuncInfo.PHINodesToUpdate.push_back(
11888               std::make_pair(&*MBBI++, Reg + i));
11889         Reg += NumRegisters;
11890       }
11891     }
11892   }
11893 
11894   ConstantsOut.clear();
11895 }
11896 
11897 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11898   MachineFunction::iterator I(MBB);
11899   if (++I == FuncInfo.MF->end())
11900     return nullptr;
11901   return &*I;
11902 }
11903 
11904 /// During lowering new call nodes can be created (such as memset, etc.).
11905 /// Those will become new roots of the current DAG, but complications arise
11906 /// when they are tail calls. In such cases, the call lowering will update
11907 /// the root, but the builder still needs to know that a tail call has been
11908 /// lowered in order to avoid generating an additional return.
11909 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11910   // If the node is null, we do have a tail call.
11911   if (MaybeTC.getNode() != nullptr)
11912     DAG.setRoot(MaybeTC);
11913   else
11914     HasTailCall = true;
11915 }
11916 
11917 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11918                                         MachineBasicBlock *SwitchMBB,
11919                                         MachineBasicBlock *DefaultMBB) {
11920   MachineFunction *CurMF = FuncInfo.MF;
11921   MachineBasicBlock *NextMBB = nullptr;
11922   MachineFunction::iterator BBI(W.MBB);
11923   if (++BBI != FuncInfo.MF->end())
11924     NextMBB = &*BBI;
11925 
11926   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11927 
11928   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11929 
11930   if (Size == 2 && W.MBB == SwitchMBB) {
11931     // If any two of the cases has the same destination, and if one value
11932     // is the same as the other, but has one bit unset that the other has set,
11933     // use bit manipulation to do two compares at once.  For example:
11934     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11935     // TODO: This could be extended to merge any 2 cases in switches with 3
11936     // cases.
11937     // TODO: Handle cases where W.CaseBB != SwitchBB.
11938     CaseCluster &Small = *W.FirstCluster;
11939     CaseCluster &Big = *W.LastCluster;
11940 
11941     if (Small.Low == Small.High && Big.Low == Big.High &&
11942         Small.MBB == Big.MBB) {
11943       const APInt &SmallValue = Small.Low->getValue();
11944       const APInt &BigValue = Big.Low->getValue();
11945 
11946       // Check that there is only one bit different.
11947       APInt CommonBit = BigValue ^ SmallValue;
11948       if (CommonBit.isPowerOf2()) {
11949         SDValue CondLHS = getValue(Cond);
11950         EVT VT = CondLHS.getValueType();
11951         SDLoc DL = getCurSDLoc();
11952 
11953         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11954                                  DAG.getConstant(CommonBit, DL, VT));
11955         SDValue Cond = DAG.getSetCC(
11956             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11957             ISD::SETEQ);
11958 
11959         // Update successor info.
11960         // Both Small and Big will jump to Small.BB, so we sum up the
11961         // probabilities.
11962         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11963         if (BPI)
11964           addSuccessorWithProb(
11965               SwitchMBB, DefaultMBB,
11966               // The default destination is the first successor in IR.
11967               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
11968         else
11969           addSuccessorWithProb(SwitchMBB, DefaultMBB);
11970 
11971         // Insert the true branch.
11972         SDValue BrCond =
11973             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
11974                         DAG.getBasicBlock(Small.MBB));
11975         // Insert the false branch.
11976         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
11977                              DAG.getBasicBlock(DefaultMBB));
11978 
11979         DAG.setRoot(BrCond);
11980         return;
11981       }
11982     }
11983   }
11984 
11985   if (TM.getOptLevel() != CodeGenOptLevel::None) {
11986     // Here, we order cases by probability so the most likely case will be
11987     // checked first. However, two clusters can have the same probability in
11988     // which case their relative ordering is non-deterministic. So we use Low
11989     // as a tie-breaker as clusters are guaranteed to never overlap.
11990     llvm::sort(W.FirstCluster, W.LastCluster + 1,
11991                [](const CaseCluster &a, const CaseCluster &b) {
11992       return a.Prob != b.Prob ?
11993              a.Prob > b.Prob :
11994              a.Low->getValue().slt(b.Low->getValue());
11995     });
11996 
11997     // Rearrange the case blocks so that the last one falls through if possible
11998     // without changing the order of probabilities.
11999     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12000       --I;
12001       if (I->Prob > W.LastCluster->Prob)
12002         break;
12003       if (I->Kind == CC_Range && I->MBB == NextMBB) {
12004         std::swap(*I, *W.LastCluster);
12005         break;
12006       }
12007     }
12008   }
12009 
12010   // Compute total probability.
12011   BranchProbability DefaultProb = W.DefaultProb;
12012   BranchProbability UnhandledProbs = DefaultProb;
12013   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12014     UnhandledProbs += I->Prob;
12015 
12016   MachineBasicBlock *CurMBB = W.MBB;
12017   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12018     bool FallthroughUnreachable = false;
12019     MachineBasicBlock *Fallthrough;
12020     if (I == W.LastCluster) {
12021       // For the last cluster, fall through to the default destination.
12022       Fallthrough = DefaultMBB;
12023       FallthroughUnreachable = isa<UnreachableInst>(
12024           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12025     } else {
12026       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12027       CurMF->insert(BBI, Fallthrough);
12028       // Put Cond in a virtual register to make it available from the new blocks.
12029       ExportFromCurrentBlock(Cond);
12030     }
12031     UnhandledProbs -= I->Prob;
12032 
12033     switch (I->Kind) {
12034       case CC_JumpTable: {
12035         // FIXME: Optimize away range check based on pivot comparisons.
12036         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12037         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12038 
12039         // The jump block hasn't been inserted yet; insert it here.
12040         MachineBasicBlock *JumpMBB = JT->MBB;
12041         CurMF->insert(BBI, JumpMBB);
12042 
12043         auto JumpProb = I->Prob;
12044         auto FallthroughProb = UnhandledProbs;
12045 
12046         // If the default statement is a target of the jump table, we evenly
12047         // distribute the default probability to successors of CurMBB. Also
12048         // update the probability on the edge from JumpMBB to Fallthrough.
12049         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12050                                               SE = JumpMBB->succ_end();
12051              SI != SE; ++SI) {
12052           if (*SI == DefaultMBB) {
12053             JumpProb += DefaultProb / 2;
12054             FallthroughProb -= DefaultProb / 2;
12055             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12056             JumpMBB->normalizeSuccProbs();
12057             break;
12058           }
12059         }
12060 
12061         // If the default clause is unreachable, propagate that knowledge into
12062         // JTH->FallthroughUnreachable which will use it to suppress the range
12063         // check.
12064         //
12065         // However, don't do this if we're doing branch target enforcement,
12066         // because a table branch _without_ a range check can be a tempting JOP
12067         // gadget - out-of-bounds inputs that are impossible in correct
12068         // execution become possible again if an attacker can influence the
12069         // control flow. So if an attacker doesn't already have a BTI bypass
12070         // available, we don't want them to be able to get one out of this
12071         // table branch.
12072         if (FallthroughUnreachable) {
12073           Function &CurFunc = CurMF->getFunction();
12074           if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12075             JTH->FallthroughUnreachable = true;
12076         }
12077 
12078         if (!JTH->FallthroughUnreachable)
12079           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12080         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12081         CurMBB->normalizeSuccProbs();
12082 
12083         // The jump table header will be inserted in our current block, do the
12084         // range check, and fall through to our fallthrough block.
12085         JTH->HeaderBB = CurMBB;
12086         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12087 
12088         // If we're in the right place, emit the jump table header right now.
12089         if (CurMBB == SwitchMBB) {
12090           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12091           JTH->Emitted = true;
12092         }
12093         break;
12094       }
12095       case CC_BitTests: {
12096         // FIXME: Optimize away range check based on pivot comparisons.
12097         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12098 
12099         // The bit test blocks haven't been inserted yet; insert them here.
12100         for (BitTestCase &BTC : BTB->Cases)
12101           CurMF->insert(BBI, BTC.ThisBB);
12102 
12103         // Fill in fields of the BitTestBlock.
12104         BTB->Parent = CurMBB;
12105         BTB->Default = Fallthrough;
12106 
12107         BTB->DefaultProb = UnhandledProbs;
12108         // If the cases in bit test don't form a contiguous range, we evenly
12109         // distribute the probability on the edge to Fallthrough to two
12110         // successors of CurMBB.
12111         if (!BTB->ContiguousRange) {
12112           BTB->Prob += DefaultProb / 2;
12113           BTB->DefaultProb -= DefaultProb / 2;
12114         }
12115 
12116         if (FallthroughUnreachable)
12117           BTB->FallthroughUnreachable = true;
12118 
12119         // If we're in the right place, emit the bit test header right now.
12120         if (CurMBB == SwitchMBB) {
12121           visitBitTestHeader(*BTB, SwitchMBB);
12122           BTB->Emitted = true;
12123         }
12124         break;
12125       }
12126       case CC_Range: {
12127         const Value *RHS, *LHS, *MHS;
12128         ISD::CondCode CC;
12129         if (I->Low == I->High) {
12130           // Check Cond == I->Low.
12131           CC = ISD::SETEQ;
12132           LHS = Cond;
12133           RHS=I->Low;
12134           MHS = nullptr;
12135         } else {
12136           // Check I->Low <= Cond <= I->High.
12137           CC = ISD::SETLE;
12138           LHS = I->Low;
12139           MHS = Cond;
12140           RHS = I->High;
12141         }
12142 
12143         // If Fallthrough is unreachable, fold away the comparison.
12144         if (FallthroughUnreachable)
12145           CC = ISD::SETTRUE;
12146 
12147         // The false probability is the sum of all unhandled cases.
12148         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12149                      getCurSDLoc(), I->Prob, UnhandledProbs);
12150 
12151         if (CurMBB == SwitchMBB)
12152           visitSwitchCase(CB, SwitchMBB);
12153         else
12154           SL->SwitchCases.push_back(CB);
12155 
12156         break;
12157       }
12158     }
12159     CurMBB = Fallthrough;
12160   }
12161 }
12162 
12163 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12164                                         const SwitchWorkListItem &W,
12165                                         Value *Cond,
12166                                         MachineBasicBlock *SwitchMBB) {
12167   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12168          "Clusters not sorted?");
12169   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12170 
12171   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12172       SL->computeSplitWorkItemInfo(W);
12173 
12174   // Use the first element on the right as pivot since we will make less-than
12175   // comparisons against it.
12176   CaseClusterIt PivotCluster = FirstRight;
12177   assert(PivotCluster > W.FirstCluster);
12178   assert(PivotCluster <= W.LastCluster);
12179 
12180   CaseClusterIt FirstLeft = W.FirstCluster;
12181   CaseClusterIt LastRight = W.LastCluster;
12182 
12183   const ConstantInt *Pivot = PivotCluster->Low;
12184 
12185   // New blocks will be inserted immediately after the current one.
12186   MachineFunction::iterator BBI(W.MBB);
12187   ++BBI;
12188 
12189   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12190   // we can branch to its destination directly if it's squeezed exactly in
12191   // between the known lower bound and Pivot - 1.
12192   MachineBasicBlock *LeftMBB;
12193   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12194       FirstLeft->Low == W.GE &&
12195       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12196     LeftMBB = FirstLeft->MBB;
12197   } else {
12198     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12199     FuncInfo.MF->insert(BBI, LeftMBB);
12200     WorkList.push_back(
12201         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12202     // Put Cond in a virtual register to make it available from the new blocks.
12203     ExportFromCurrentBlock(Cond);
12204   }
12205 
12206   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12207   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12208   // directly if RHS.High equals the current upper bound.
12209   MachineBasicBlock *RightMBB;
12210   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12211       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12212     RightMBB = FirstRight->MBB;
12213   } else {
12214     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12215     FuncInfo.MF->insert(BBI, RightMBB);
12216     WorkList.push_back(
12217         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12218     // Put Cond in a virtual register to make it available from the new blocks.
12219     ExportFromCurrentBlock(Cond);
12220   }
12221 
12222   // Create the CaseBlock record that will be used to lower the branch.
12223   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12224                getCurSDLoc(), LeftProb, RightProb);
12225 
12226   if (W.MBB == SwitchMBB)
12227     visitSwitchCase(CB, SwitchMBB);
12228   else
12229     SL->SwitchCases.push_back(CB);
12230 }
12231 
12232 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12233 // from the swith statement.
12234 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12235                                             BranchProbability PeeledCaseProb) {
12236   if (PeeledCaseProb == BranchProbability::getOne())
12237     return BranchProbability::getZero();
12238   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12239 
12240   uint32_t Numerator = CaseProb.getNumerator();
12241   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12242   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12243 }
12244 
12245 // Try to peel the top probability case if it exceeds the threshold.
12246 // Return current MachineBasicBlock for the switch statement if the peeling
12247 // does not occur.
12248 // If the peeling is performed, return the newly created MachineBasicBlock
12249 // for the peeled switch statement. Also update Clusters to remove the peeled
12250 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12251 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12252     const SwitchInst &SI, CaseClusterVector &Clusters,
12253     BranchProbability &PeeledCaseProb) {
12254   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12255   // Don't perform if there is only one cluster or optimizing for size.
12256   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12257       TM.getOptLevel() == CodeGenOptLevel::None ||
12258       SwitchMBB->getParent()->getFunction().hasMinSize())
12259     return SwitchMBB;
12260 
12261   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12262   unsigned PeeledCaseIndex = 0;
12263   bool SwitchPeeled = false;
12264   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12265     CaseCluster &CC = Clusters[Index];
12266     if (CC.Prob < TopCaseProb)
12267       continue;
12268     TopCaseProb = CC.Prob;
12269     PeeledCaseIndex = Index;
12270     SwitchPeeled = true;
12271   }
12272   if (!SwitchPeeled)
12273     return SwitchMBB;
12274 
12275   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12276                     << TopCaseProb << "\n");
12277 
12278   // Record the MBB for the peeled switch statement.
12279   MachineFunction::iterator BBI(SwitchMBB);
12280   ++BBI;
12281   MachineBasicBlock *PeeledSwitchMBB =
12282       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12283   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12284 
12285   ExportFromCurrentBlock(SI.getCondition());
12286   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12287   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12288                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12289   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12290 
12291   Clusters.erase(PeeledCaseIt);
12292   for (CaseCluster &CC : Clusters) {
12293     LLVM_DEBUG(
12294         dbgs() << "Scale the probablity for one cluster, before scaling: "
12295                << CC.Prob << "\n");
12296     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12297     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12298   }
12299   PeeledCaseProb = TopCaseProb;
12300   return PeeledSwitchMBB;
12301 }
12302 
12303 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12304   // Extract cases from the switch.
12305   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12306   CaseClusterVector Clusters;
12307   Clusters.reserve(SI.getNumCases());
12308   for (auto I : SI.cases()) {
12309     MachineBasicBlock *Succ = FuncInfo.MBBMap[I.getCaseSuccessor()];
12310     const ConstantInt *CaseVal = I.getCaseValue();
12311     BranchProbability Prob =
12312         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12313             : BranchProbability(1, SI.getNumCases() + 1);
12314     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12315   }
12316 
12317   MachineBasicBlock *DefaultMBB = FuncInfo.MBBMap[SI.getDefaultDest()];
12318 
12319   // Cluster adjacent cases with the same destination. We do this at all
12320   // optimization levels because it's cheap to do and will make codegen faster
12321   // if there are many clusters.
12322   sortAndRangeify(Clusters);
12323 
12324   // The branch probablity of the peeled case.
12325   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12326   MachineBasicBlock *PeeledSwitchMBB =
12327       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12328 
12329   // If there is only the default destination, jump there directly.
12330   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12331   if (Clusters.empty()) {
12332     assert(PeeledSwitchMBB == SwitchMBB);
12333     SwitchMBB->addSuccessor(DefaultMBB);
12334     if (DefaultMBB != NextBlock(SwitchMBB)) {
12335       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12336                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12337     }
12338     return;
12339   }
12340 
12341   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12342                      DAG.getBFI());
12343   SL->findBitTestClusters(Clusters, &SI);
12344 
12345   LLVM_DEBUG({
12346     dbgs() << "Case clusters: ";
12347     for (const CaseCluster &C : Clusters) {
12348       if (C.Kind == CC_JumpTable)
12349         dbgs() << "JT:";
12350       if (C.Kind == CC_BitTests)
12351         dbgs() << "BT:";
12352 
12353       C.Low->getValue().print(dbgs(), true);
12354       if (C.Low != C.High) {
12355         dbgs() << '-';
12356         C.High->getValue().print(dbgs(), true);
12357       }
12358       dbgs() << ' ';
12359     }
12360     dbgs() << '\n';
12361   });
12362 
12363   assert(!Clusters.empty());
12364   SwitchWorkList WorkList;
12365   CaseClusterIt First = Clusters.begin();
12366   CaseClusterIt Last = Clusters.end() - 1;
12367   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12368   // Scale the branchprobability for DefaultMBB if the peel occurs and
12369   // DefaultMBB is not replaced.
12370   if (PeeledCaseProb != BranchProbability::getZero() &&
12371       DefaultMBB == FuncInfo.MBBMap[SI.getDefaultDest()])
12372     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12373   WorkList.push_back(
12374       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12375 
12376   while (!WorkList.empty()) {
12377     SwitchWorkListItem W = WorkList.pop_back_val();
12378     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12379 
12380     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12381         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12382       // For optimized builds, lower large range as a balanced binary tree.
12383       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12384       continue;
12385     }
12386 
12387     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12388   }
12389 }
12390 
12391 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12392   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12393   auto DL = getCurSDLoc();
12394   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12395   setValue(&I, DAG.getStepVector(DL, ResultVT));
12396 }
12397 
12398 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12399   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12400   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12401 
12402   SDLoc DL = getCurSDLoc();
12403   SDValue V = getValue(I.getOperand(0));
12404   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12405 
12406   if (VT.isScalableVector()) {
12407     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12408     return;
12409   }
12410 
12411   // Use VECTOR_SHUFFLE for the fixed-length vector
12412   // to maintain existing behavior.
12413   SmallVector<int, 8> Mask;
12414   unsigned NumElts = VT.getVectorMinNumElements();
12415   for (unsigned i = 0; i != NumElts; ++i)
12416     Mask.push_back(NumElts - 1 - i);
12417 
12418   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12419 }
12420 
12421 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12422   auto DL = getCurSDLoc();
12423   SDValue InVec = getValue(I.getOperand(0));
12424   EVT OutVT =
12425       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12426 
12427   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12428 
12429   // ISD Node needs the input vectors split into two equal parts
12430   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12431                            DAG.getVectorIdxConstant(0, DL));
12432   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12433                            DAG.getVectorIdxConstant(OutNumElts, DL));
12434 
12435   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12436   // legalisation and combines.
12437   if (OutVT.isFixedLengthVector()) {
12438     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12439                                         createStrideMask(0, 2, OutNumElts));
12440     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12441                                        createStrideMask(1, 2, OutNumElts));
12442     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12443     setValue(&I, Res);
12444     return;
12445   }
12446 
12447   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12448                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12449   setValue(&I, Res);
12450 }
12451 
12452 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12453   auto DL = getCurSDLoc();
12454   EVT InVT = getValue(I.getOperand(0)).getValueType();
12455   SDValue InVec0 = getValue(I.getOperand(0));
12456   SDValue InVec1 = getValue(I.getOperand(1));
12457   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12458   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12459 
12460   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12461   // legalisation and combines.
12462   if (OutVT.isFixedLengthVector()) {
12463     unsigned NumElts = InVT.getVectorMinNumElements();
12464     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12465     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12466                                       createInterleaveMask(NumElts, 2)));
12467     return;
12468   }
12469 
12470   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12471                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12472   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12473                     Res.getValue(1));
12474   setValue(&I, Res);
12475 }
12476 
12477 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12478   SmallVector<EVT, 4> ValueVTs;
12479   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12480                   ValueVTs);
12481   unsigned NumValues = ValueVTs.size();
12482   if (NumValues == 0) return;
12483 
12484   SmallVector<SDValue, 4> Values(NumValues);
12485   SDValue Op = getValue(I.getOperand(0));
12486 
12487   for (unsigned i = 0; i != NumValues; ++i)
12488     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12489                             SDValue(Op.getNode(), Op.getResNo() + i));
12490 
12491   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12492                            DAG.getVTList(ValueVTs), Values));
12493 }
12494 
12495 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12497   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12498 
12499   SDLoc DL = getCurSDLoc();
12500   SDValue V1 = getValue(I.getOperand(0));
12501   SDValue V2 = getValue(I.getOperand(1));
12502   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12503 
12504   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12505   if (VT.isScalableVector()) {
12506     setValue(&I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12507                              DAG.getVectorIdxConstant(Imm, DL)));
12508     return;
12509   }
12510 
12511   unsigned NumElts = VT.getVectorNumElements();
12512 
12513   uint64_t Idx = (NumElts + Imm) % NumElts;
12514 
12515   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12516   SmallVector<int, 8> Mask;
12517   for (unsigned i = 0; i < NumElts; ++i)
12518     Mask.push_back(Idx + i);
12519   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12520 }
12521 
12522 // Consider the following MIR after SelectionDAG, which produces output in
12523 // phyregs in the first case or virtregs in the second case.
12524 //
12525 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12526 // %5:gr32 = COPY $ebx
12527 // %6:gr32 = COPY $edx
12528 // %1:gr32 = COPY %6:gr32
12529 // %0:gr32 = COPY %5:gr32
12530 //
12531 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12532 // %1:gr32 = COPY %6:gr32
12533 // %0:gr32 = COPY %5:gr32
12534 //
12535 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12536 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12537 //
12538 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12539 // to a single virtreg (such as %0). The remaining outputs monotonically
12540 // increase in virtreg number from there. If a callbr has no outputs, then it
12541 // should not have a corresponding callbr landingpad; in fact, the callbr
12542 // landingpad would not even be able to refer to such a callbr.
12543 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12544   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12545   // There is definitely at least one copy.
12546   assert(MI->getOpcode() == TargetOpcode::COPY &&
12547          "start of copy chain MUST be COPY");
12548   Reg = MI->getOperand(1).getReg();
12549   MI = MRI.def_begin(Reg)->getParent();
12550   // There may be an optional second copy.
12551   if (MI->getOpcode() == TargetOpcode::COPY) {
12552     assert(Reg.isVirtual() && "expected COPY of virtual register");
12553     Reg = MI->getOperand(1).getReg();
12554     assert(Reg.isPhysical() && "expected COPY of physical register");
12555     MI = MRI.def_begin(Reg)->getParent();
12556   }
12557   // The start of the chain must be an INLINEASM_BR.
12558   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12559          "end of copy chain MUST be INLINEASM_BR");
12560   return Reg;
12561 }
12562 
12563 // We must do this walk rather than the simpler
12564 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12565 // otherwise we will end up with copies of virtregs only valid along direct
12566 // edges.
12567 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12568   SmallVector<EVT, 8> ResultVTs;
12569   SmallVector<SDValue, 8> ResultValues;
12570   const auto *CBR =
12571       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12572 
12573   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12574   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12575   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12576 
12577   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12578   SDValue Chain = DAG.getRoot();
12579 
12580   // Re-parse the asm constraints string.
12581   TargetLowering::AsmOperandInfoVector TargetConstraints =
12582       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12583   for (auto &T : TargetConstraints) {
12584     SDISelAsmOperandInfo OpInfo(T);
12585     if (OpInfo.Type != InlineAsm::isOutput)
12586       continue;
12587 
12588     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12589     // individual constraint.
12590     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12591 
12592     switch (OpInfo.ConstraintType) {
12593     case TargetLowering::C_Register:
12594     case TargetLowering::C_RegisterClass: {
12595       // Fill in OpInfo.AssignedRegs.Regs.
12596       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12597 
12598       // getRegistersForValue may produce 1 to many registers based on whether
12599       // the OpInfo.ConstraintVT is legal on the target or not.
12600       for (unsigned &Reg : OpInfo.AssignedRegs.Regs) {
12601         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12602         if (Register::isPhysicalRegister(OriginalDef))
12603           FuncInfo.MBB->addLiveIn(OriginalDef);
12604         // Update the assigned registers to use the original defs.
12605         Reg = OriginalDef;
12606       }
12607 
12608       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12609           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12610       ResultValues.push_back(V);
12611       ResultVTs.push_back(OpInfo.ConstraintVT);
12612       break;
12613     }
12614     case TargetLowering::C_Other: {
12615       SDValue Flag;
12616       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12617                                                   OpInfo, DAG);
12618       ++InitialDef;
12619       ResultValues.push_back(V);
12620       ResultVTs.push_back(OpInfo.ConstraintVT);
12621       break;
12622     }
12623     default:
12624       break;
12625     }
12626   }
12627   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12628                           DAG.getVTList(ResultVTs), ResultValues);
12629   setValue(&I, V);
12630 }
12631