xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 41b55071a13374654a290c01224eb066c38dc87a)
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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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.getMBB(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   bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2822   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2823   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2824       BOp->hasOneUse() && !IsUnpredictable) {
2825     Value *Vec;
2826     const Value *BOp0, *BOp1;
2827     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2828     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2829       Opcode = Instruction::And;
2830     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2831       Opcode = Instruction::Or;
2832 
2833     if (Opcode &&
2834         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2835           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2836         !shouldKeepJumpConditionsTogether(
2837             FuncInfo, I, Opcode, BOp0, BOp1,
2838             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2839                 Opcode, BOp0, BOp1))) {
2840       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2841                            getEdgeProbability(BrMBB, Succ0MBB),
2842                            getEdgeProbability(BrMBB, Succ1MBB),
2843                            /*InvertCond=*/false);
2844       // If the compares in later blocks need to use values not currently
2845       // exported from this block, export them now.  This block should always
2846       // be the first entry.
2847       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2848 
2849       // Allow some cases to be rejected.
2850       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2851         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2852           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2853           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2854         }
2855 
2856         // Emit the branch for this block.
2857         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2858         SL->SwitchCases.erase(SL->SwitchCases.begin());
2859         return;
2860       }
2861 
2862       // Okay, we decided not to do this, remove any inserted MBB's and clear
2863       // SwitchCases.
2864       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2865         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2866 
2867       SL->SwitchCases.clear();
2868     }
2869   }
2870 
2871   // Create a CaseBlock record representing this branch.
2872   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2873                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2874                BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2875                IsUnpredictable);
2876 
2877   // Use visitSwitchCase to actually insert the fast branch sequence for this
2878   // cond branch.
2879   visitSwitchCase(CB, BrMBB);
2880 }
2881 
2882 /// visitSwitchCase - Emits the necessary code to represent a single node in
2883 /// the binary search tree resulting from lowering a switch instruction.
2884 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2885                                           MachineBasicBlock *SwitchBB) {
2886   SDValue Cond;
2887   SDValue CondLHS = getValue(CB.CmpLHS);
2888   SDLoc dl = CB.DL;
2889 
2890   if (CB.CC == ISD::SETTRUE) {
2891     // Branch or fall through to TrueBB.
2892     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2893     SwitchBB->normalizeSuccProbs();
2894     if (CB.TrueBB != NextBlock(SwitchBB)) {
2895       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2896                               DAG.getBasicBlock(CB.TrueBB)));
2897     }
2898     return;
2899   }
2900 
2901   auto &TLI = DAG.getTargetLoweringInfo();
2902   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2903 
2904   // Build the setcc now.
2905   if (!CB.CmpMHS) {
2906     // Fold "(X == true)" to X and "(X == false)" to !X to
2907     // handle common cases produced by branch lowering.
2908     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2909         CB.CC == ISD::SETEQ)
2910       Cond = CondLHS;
2911     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2912              CB.CC == ISD::SETEQ) {
2913       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2914       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2915     } else {
2916       SDValue CondRHS = getValue(CB.CmpRHS);
2917 
2918       // If a pointer's DAG type is larger than its memory type then the DAG
2919       // values are zero-extended. This breaks signed comparisons so truncate
2920       // back to the underlying type before doing the compare.
2921       if (CondLHS.getValueType() != MemVT) {
2922         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2923         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2924       }
2925       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2926     }
2927   } else {
2928     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2929 
2930     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2931     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2932 
2933     SDValue CmpOp = getValue(CB.CmpMHS);
2934     EVT VT = CmpOp.getValueType();
2935 
2936     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2937       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2938                           ISD::SETLE);
2939     } else {
2940       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2941                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2942       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2943                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2944     }
2945   }
2946 
2947   // Update successor info
2948   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2949   // TrueBB and FalseBB are always different unless the incoming IR is
2950   // degenerate. This only happens when running llc on weird IR.
2951   if (CB.TrueBB != CB.FalseBB)
2952     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2953   SwitchBB->normalizeSuccProbs();
2954 
2955   // If the lhs block is the next block, invert the condition so that we can
2956   // fall through to the lhs instead of the rhs block.
2957   if (CB.TrueBB == NextBlock(SwitchBB)) {
2958     std::swap(CB.TrueBB, CB.FalseBB);
2959     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2960     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2961   }
2962 
2963   SDNodeFlags Flags;
2964   Flags.setUnpredictable(CB.IsUnpredictable);
2965   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
2966                                Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
2967 
2968   setValue(CurInst, BrCond);
2969 
2970   // Insert the false branch. Do this even if it's a fall through branch,
2971   // this makes it easier to do DAG optimizations which require inverting
2972   // the branch condition.
2973   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2974                        DAG.getBasicBlock(CB.FalseBB));
2975 
2976   DAG.setRoot(BrCond);
2977 }
2978 
2979 /// visitJumpTable - Emit JumpTable node in the current MBB
2980 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2981   // Emit the code for the jump table
2982   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2983   assert(JT.Reg != -1U && "Should lower JT Header first!");
2984   EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
2985   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2986   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2987   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2988                                     Index.getValue(1), Table, Index);
2989   DAG.setRoot(BrJumpTable);
2990 }
2991 
2992 /// visitJumpTableHeader - This function emits necessary code to produce index
2993 /// in the JumpTable from switch case.
2994 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
2995                                                JumpTableHeader &JTH,
2996                                                MachineBasicBlock *SwitchBB) {
2997   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2998   const SDLoc &dl = *JT.SL;
2999 
3000   // Subtract the lowest switch case value from the value being switched on.
3001   SDValue SwitchOp = getValue(JTH.SValue);
3002   EVT VT = SwitchOp.getValueType();
3003   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3004                             DAG.getConstant(JTH.First, dl, VT));
3005 
3006   // The SDNode we just created, which holds the value being switched on minus
3007   // the smallest case value, needs to be copied to a virtual register so it
3008   // can be used as an index into the jump table in a subsequent basic block.
3009   // This value may be smaller or larger than the target's pointer type, and
3010   // therefore require extension or truncating.
3011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3012   SwitchOp =
3013       DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3014 
3015   unsigned JumpTableReg =
3016       FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3017   SDValue CopyTo =
3018       DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3019   JT.Reg = JumpTableReg;
3020 
3021   if (!JTH.FallthroughUnreachable) {
3022     // Emit the range check for the jump table, and branch to the default block
3023     // for the switch statement if the value being switched on exceeds the
3024     // largest case in the switch.
3025     SDValue CMP = DAG.getSetCC(
3026         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3027                                    Sub.getValueType()),
3028         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3029 
3030     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3031                                  MVT::Other, CopyTo, CMP,
3032                                  DAG.getBasicBlock(JT.Default));
3033 
3034     // Avoid emitting unnecessary branches to the next block.
3035     if (JT.MBB != NextBlock(SwitchBB))
3036       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3037                            DAG.getBasicBlock(JT.MBB));
3038 
3039     DAG.setRoot(BrCond);
3040   } else {
3041     // Avoid emitting unnecessary branches to the next block.
3042     if (JT.MBB != NextBlock(SwitchBB))
3043       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3044                               DAG.getBasicBlock(JT.MBB)));
3045     else
3046       DAG.setRoot(CopyTo);
3047   }
3048 }
3049 
3050 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3051 /// variable if there exists one.
3052 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3053                                  SDValue &Chain) {
3054   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3055   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3056   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3057   MachineFunction &MF = DAG.getMachineFunction();
3058   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3059   MachineSDNode *Node =
3060       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3061   if (Global) {
3062     MachinePointerInfo MPInfo(Global);
3063     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3064                  MachineMemOperand::MODereferenceable;
3065     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3066         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3067         DAG.getEVTAlign(PtrTy));
3068     DAG.setNodeMemRefs(Node, {MemRef});
3069   }
3070   if (PtrTy != PtrMemTy)
3071     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3072   return SDValue(Node, 0);
3073 }
3074 
3075 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3076 /// tail spliced into a stack protector check success bb.
3077 ///
3078 /// For a high level explanation of how this fits into the stack protector
3079 /// generation see the comment on the declaration of class
3080 /// StackProtectorDescriptor.
3081 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3082                                                   MachineBasicBlock *ParentBB) {
3083 
3084   // First create the loads to the guard/stack slot for the comparison.
3085   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3086   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3087   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3088 
3089   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3090   int FI = MFI.getStackProtectorIndex();
3091 
3092   SDValue Guard;
3093   SDLoc dl = getCurSDLoc();
3094   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3095   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3096   Align Align =
3097       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3098 
3099   // Generate code to load the content of the guard slot.
3100   SDValue GuardVal = DAG.getLoad(
3101       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3102       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3103       MachineMemOperand::MOVolatile);
3104 
3105   if (TLI.useStackGuardXorFP())
3106     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3107 
3108   // Retrieve guard check function, nullptr if instrumentation is inlined.
3109   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3110     // The target provides a guard check function to validate the guard value.
3111     // Generate a call to that function with the content of the guard slot as
3112     // argument.
3113     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3114     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3115 
3116     TargetLowering::ArgListTy Args;
3117     TargetLowering::ArgListEntry Entry;
3118     Entry.Node = GuardVal;
3119     Entry.Ty = FnTy->getParamType(0);
3120     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3121       Entry.IsInReg = true;
3122     Args.push_back(Entry);
3123 
3124     TargetLowering::CallLoweringInfo CLI(DAG);
3125     CLI.setDebugLoc(getCurSDLoc())
3126         .setChain(DAG.getEntryNode())
3127         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3128                    getValue(GuardCheckFn), std::move(Args));
3129 
3130     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3131     DAG.setRoot(Result.second);
3132     return;
3133   }
3134 
3135   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3136   // Otherwise, emit a volatile load to retrieve the stack guard value.
3137   SDValue Chain = DAG.getEntryNode();
3138   if (TLI.useLoadStackGuardNode()) {
3139     Guard = getLoadStackGuard(DAG, dl, Chain);
3140   } else {
3141     const Value *IRGuard = TLI.getSDagStackGuard(M);
3142     SDValue GuardPtr = getValue(IRGuard);
3143 
3144     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3145                         MachinePointerInfo(IRGuard, 0), Align,
3146                         MachineMemOperand::MOVolatile);
3147   }
3148 
3149   // Perform the comparison via a getsetcc.
3150   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3151                                                         *DAG.getContext(),
3152                                                         Guard.getValueType()),
3153                              Guard, GuardVal, ISD::SETNE);
3154 
3155   // If the guard/stackslot do not equal, branch to failure MBB.
3156   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3157                                MVT::Other, GuardVal.getOperand(0),
3158                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3159   // Otherwise branch to success MBB.
3160   SDValue Br = DAG.getNode(ISD::BR, dl,
3161                            MVT::Other, BrCond,
3162                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3163 
3164   DAG.setRoot(Br);
3165 }
3166 
3167 /// Codegen the failure basic block for a stack protector check.
3168 ///
3169 /// A failure stack protector machine basic block consists simply of a call to
3170 /// __stack_chk_fail().
3171 ///
3172 /// For a high level explanation of how this fits into the stack protector
3173 /// generation see the comment on the declaration of class
3174 /// StackProtectorDescriptor.
3175 void
3176 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3177   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3178   TargetLowering::MakeLibCallOptions CallOptions;
3179   CallOptions.setDiscardResult(true);
3180   SDValue Chain =
3181       TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL, MVT::isVoid,
3182                       std::nullopt, CallOptions, getCurSDLoc())
3183           .second;
3184   // On PS4/PS5, the "return address" must still be within the calling
3185   // function, even if it's at the very end, so emit an explicit TRAP here.
3186   // Passing 'true' for doesNotReturn above won't generate the trap for us.
3187   if (TM.getTargetTriple().isPS())
3188     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3189   // WebAssembly needs an unreachable instruction after a non-returning call,
3190   // because the function return type can be different from __stack_chk_fail's
3191   // return type (void).
3192   if (TM.getTargetTriple().isWasm())
3193     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3194 
3195   DAG.setRoot(Chain);
3196 }
3197 
3198 /// visitBitTestHeader - This function emits necessary code to produce value
3199 /// suitable for "bit tests"
3200 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3201                                              MachineBasicBlock *SwitchBB) {
3202   SDLoc dl = getCurSDLoc();
3203 
3204   // Subtract the minimum value.
3205   SDValue SwitchOp = getValue(B.SValue);
3206   EVT VT = SwitchOp.getValueType();
3207   SDValue RangeSub =
3208       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3209 
3210   // Determine the type of the test operands.
3211   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3212   bool UsePtrType = false;
3213   if (!TLI.isTypeLegal(VT)) {
3214     UsePtrType = true;
3215   } else {
3216     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3217       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3218         // Switch table case range are encoded into series of masks.
3219         // Just use pointer type, it's guaranteed to fit.
3220         UsePtrType = true;
3221         break;
3222       }
3223   }
3224   SDValue Sub = RangeSub;
3225   if (UsePtrType) {
3226     VT = TLI.getPointerTy(DAG.getDataLayout());
3227     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3228   }
3229 
3230   B.RegVT = VT.getSimpleVT();
3231   B.Reg = FuncInfo.CreateReg(B.RegVT);
3232   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3233 
3234   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3235 
3236   if (!B.FallthroughUnreachable)
3237     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3238   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3239   SwitchBB->normalizeSuccProbs();
3240 
3241   SDValue Root = CopyTo;
3242   if (!B.FallthroughUnreachable) {
3243     // Conditional branch to the default block.
3244     SDValue RangeCmp = DAG.getSetCC(dl,
3245         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3246                                RangeSub.getValueType()),
3247         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3248         ISD::SETUGT);
3249 
3250     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3251                        DAG.getBasicBlock(B.Default));
3252   }
3253 
3254   // Avoid emitting unnecessary branches to the next block.
3255   if (MBB != NextBlock(SwitchBB))
3256     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3257 
3258   DAG.setRoot(Root);
3259 }
3260 
3261 /// visitBitTestCase - this function produces one "bit test"
3262 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3263                                            MachineBasicBlock* NextMBB,
3264                                            BranchProbability BranchProbToNext,
3265                                            unsigned Reg,
3266                                            BitTestCase &B,
3267                                            MachineBasicBlock *SwitchBB) {
3268   SDLoc dl = getCurSDLoc();
3269   MVT VT = BB.RegVT;
3270   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3271   SDValue Cmp;
3272   unsigned PopCount = llvm::popcount(B.Mask);
3273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3274   if (PopCount == 1) {
3275     // Testing for a single bit; just compare the shift count with what it
3276     // would need to be to shift a 1 bit in that position.
3277     Cmp = DAG.getSetCC(
3278         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3279         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3280         ISD::SETEQ);
3281   } else if (PopCount == BB.Range) {
3282     // There is only one zero bit in the range, test for it directly.
3283     Cmp = DAG.getSetCC(
3284         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3285         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3286   } else {
3287     // Make desired shift
3288     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3289                                     DAG.getConstant(1, dl, VT), ShiftOp);
3290 
3291     // Emit bit tests and jumps
3292     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3293                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3294     Cmp = DAG.getSetCC(
3295         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3296         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3297   }
3298 
3299   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3300   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3301   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3302   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3303   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3304   // one as they are relative probabilities (and thus work more like weights),
3305   // and hence we need to normalize them to let the sum of them become one.
3306   SwitchBB->normalizeSuccProbs();
3307 
3308   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3309                               MVT::Other, getControlRoot(),
3310                               Cmp, DAG.getBasicBlock(B.TargetBB));
3311 
3312   // Avoid emitting unnecessary branches to the next block.
3313   if (NextMBB != NextBlock(SwitchBB))
3314     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3315                         DAG.getBasicBlock(NextMBB));
3316 
3317   DAG.setRoot(BrAnd);
3318 }
3319 
3320 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3321   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3322 
3323   // Retrieve successors. Look through artificial IR level blocks like
3324   // catchswitch for successors.
3325   MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3326   const BasicBlock *EHPadBB = I.getSuccessor(1);
3327   MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3328 
3329   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3330   // have to do anything here to lower funclet bundles.
3331   assert(!I.hasOperandBundlesOtherThan(
3332              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3333               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3334               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3335               LLVMContext::OB_clang_arc_attachedcall}) &&
3336          "Cannot lower invokes with arbitrary operand bundles yet!");
3337 
3338   const Value *Callee(I.getCalledOperand());
3339   const Function *Fn = dyn_cast<Function>(Callee);
3340   if (isa<InlineAsm>(Callee))
3341     visitInlineAsm(I, EHPadBB);
3342   else if (Fn && Fn->isIntrinsic()) {
3343     switch (Fn->getIntrinsicID()) {
3344     default:
3345       llvm_unreachable("Cannot invoke this intrinsic");
3346     case Intrinsic::donothing:
3347       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3348     case Intrinsic::seh_try_begin:
3349     case Intrinsic::seh_scope_begin:
3350     case Intrinsic::seh_try_end:
3351     case Intrinsic::seh_scope_end:
3352       if (EHPadMBB)
3353           // a block referenced by EH table
3354           // so dtor-funclet not removed by opts
3355           EHPadMBB->setMachineBlockAddressTaken();
3356       break;
3357     case Intrinsic::experimental_patchpoint_void:
3358     case Intrinsic::experimental_patchpoint:
3359       visitPatchpoint(I, EHPadBB);
3360       break;
3361     case Intrinsic::experimental_gc_statepoint:
3362       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3363       break;
3364     case Intrinsic::wasm_rethrow: {
3365       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3366       // special because it can be invoked, so we manually lower it to a DAG
3367       // node here.
3368       SmallVector<SDValue, 8> Ops;
3369       Ops.push_back(getControlRoot()); // inchain for the terminator node
3370       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3371       Ops.push_back(
3372           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3373                                 TLI.getPointerTy(DAG.getDataLayout())));
3374       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3375       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3376       break;
3377     }
3378     }
3379   } else if (I.hasDeoptState()) {
3380     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3381     // Eventually we will support lowering the @llvm.experimental.deoptimize
3382     // intrinsic, and right now there are no plans to support other intrinsics
3383     // with deopt state.
3384     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3385   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3386     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3387   } else {
3388     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3389   }
3390 
3391   // If the value of the invoke is used outside of its defining block, make it
3392   // available as a virtual register.
3393   // We already took care of the exported value for the statepoint instruction
3394   // during call to the LowerStatepoint.
3395   if (!isa<GCStatepointInst>(I)) {
3396     CopyToExportRegsIfNeeded(&I);
3397   }
3398 
3399   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3400   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3401   BranchProbability EHPadBBProb =
3402       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3403           : BranchProbability::getZero();
3404   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3405 
3406   // Update successor info.
3407   addSuccessorWithProb(InvokeMBB, Return);
3408   for (auto &UnwindDest : UnwindDests) {
3409     UnwindDest.first->setIsEHPad();
3410     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3411   }
3412   InvokeMBB->normalizeSuccProbs();
3413 
3414   // Drop into normal successor.
3415   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3416                           DAG.getBasicBlock(Return)));
3417 }
3418 
3419 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3420   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3421 
3422   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3423   // have to do anything here to lower funclet bundles.
3424   assert(!I.hasOperandBundlesOtherThan(
3425              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3426          "Cannot lower callbrs with arbitrary operand bundles yet!");
3427 
3428   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3429   visitInlineAsm(I);
3430   CopyToExportRegsIfNeeded(&I);
3431 
3432   // Retrieve successors.
3433   SmallPtrSet<BasicBlock *, 8> Dests;
3434   Dests.insert(I.getDefaultDest());
3435   MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3436 
3437   // Update successor info.
3438   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3439   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3440     BasicBlock *Dest = I.getIndirectDest(i);
3441     MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3442     Target->setIsInlineAsmBrIndirectTarget();
3443     Target->setMachineBlockAddressTaken();
3444     Target->setLabelMustBeEmitted();
3445     // Don't add duplicate machine successors.
3446     if (Dests.insert(Dest).second)
3447       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3448   }
3449   CallBrMBB->normalizeSuccProbs();
3450 
3451   // Drop into default successor.
3452   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3453                           MVT::Other, getControlRoot(),
3454                           DAG.getBasicBlock(Return)));
3455 }
3456 
3457 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3458   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3459 }
3460 
3461 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3462   assert(FuncInfo.MBB->isEHPad() &&
3463          "Call to landingpad not in landing pad!");
3464 
3465   // If there aren't registers to copy the values into (e.g., during SjLj
3466   // exceptions), then don't bother to create these DAG nodes.
3467   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3468   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3469   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3470       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3471     return;
3472 
3473   // If landingpad's return type is token type, we don't create DAG nodes
3474   // for its exception pointer and selector value. The extraction of exception
3475   // pointer or selector value from token type landingpads is not currently
3476   // supported.
3477   if (LP.getType()->isTokenTy())
3478     return;
3479 
3480   SmallVector<EVT, 2> ValueVTs;
3481   SDLoc dl = getCurSDLoc();
3482   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3483   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3484 
3485   // Get the two live-in registers as SDValues. The physregs have already been
3486   // copied into virtual registers.
3487   SDValue Ops[2];
3488   if (FuncInfo.ExceptionPointerVirtReg) {
3489     Ops[0] = DAG.getZExtOrTrunc(
3490         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3491                            FuncInfo.ExceptionPointerVirtReg,
3492                            TLI.getPointerTy(DAG.getDataLayout())),
3493         dl, ValueVTs[0]);
3494   } else {
3495     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3496   }
3497   Ops[1] = DAG.getZExtOrTrunc(
3498       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3499                          FuncInfo.ExceptionSelectorVirtReg,
3500                          TLI.getPointerTy(DAG.getDataLayout())),
3501       dl, ValueVTs[1]);
3502 
3503   // Merge into one.
3504   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3505                             DAG.getVTList(ValueVTs), Ops);
3506   setValue(&LP, Res);
3507 }
3508 
3509 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3510                                            MachineBasicBlock *Last) {
3511   // Update JTCases.
3512   for (JumpTableBlock &JTB : SL->JTCases)
3513     if (JTB.first.HeaderBB == First)
3514       JTB.first.HeaderBB = Last;
3515 
3516   // Update BitTestCases.
3517   for (BitTestBlock &BTB : SL->BitTestCases)
3518     if (BTB.Parent == First)
3519       BTB.Parent = Last;
3520 }
3521 
3522 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3523   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3524 
3525   // Update machine-CFG edges with unique successors.
3526   SmallSet<BasicBlock*, 32> Done;
3527   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3528     BasicBlock *BB = I.getSuccessor(i);
3529     bool Inserted = Done.insert(BB).second;
3530     if (!Inserted)
3531         continue;
3532 
3533     MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3534     addSuccessorWithProb(IndirectBrMBB, Succ);
3535   }
3536   IndirectBrMBB->normalizeSuccProbs();
3537 
3538   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3539                           MVT::Other, getControlRoot(),
3540                           getValue(I.getAddress())));
3541 }
3542 
3543 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3544   if (!DAG.getTarget().Options.TrapUnreachable)
3545     return;
3546 
3547   // We may be able to ignore unreachable behind a noreturn call.
3548   if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
3549       Call && Call->doesNotReturn()) {
3550     if (DAG.getTarget().Options.NoTrapAfterNoreturn)
3551       return;
3552     // Do not emit an additional trap instruction.
3553     if (Call->isNonContinuableTrap())
3554       return;
3555   }
3556 
3557   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3558 }
3559 
3560 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3561   SDNodeFlags Flags;
3562   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3563     Flags.copyFMF(*FPOp);
3564 
3565   SDValue Op = getValue(I.getOperand(0));
3566   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3567                                     Op, Flags);
3568   setValue(&I, UnNodeValue);
3569 }
3570 
3571 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3572   SDNodeFlags Flags;
3573   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3574     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3575     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3576   }
3577   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3578     Flags.setExact(ExactOp->isExact());
3579   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3580     Flags.setDisjoint(DisjointOp->isDisjoint());
3581   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3582     Flags.copyFMF(*FPOp);
3583 
3584   SDValue Op1 = getValue(I.getOperand(0));
3585   SDValue Op2 = getValue(I.getOperand(1));
3586   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3587                                      Op1, Op2, Flags);
3588   setValue(&I, BinNodeValue);
3589 }
3590 
3591 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3592   SDValue Op1 = getValue(I.getOperand(0));
3593   SDValue Op2 = getValue(I.getOperand(1));
3594 
3595   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3596       Op1.getValueType(), DAG.getDataLayout());
3597 
3598   // Coerce the shift amount to the right type if we can. This exposes the
3599   // truncate or zext to optimization early.
3600   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3601     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3602            "Unexpected shift type");
3603     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3604   }
3605 
3606   bool nuw = false;
3607   bool nsw = false;
3608   bool exact = false;
3609 
3610   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3611 
3612     if (const OverflowingBinaryOperator *OFBinOp =
3613             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3614       nuw = OFBinOp->hasNoUnsignedWrap();
3615       nsw = OFBinOp->hasNoSignedWrap();
3616     }
3617     if (const PossiblyExactOperator *ExactOp =
3618             dyn_cast<const PossiblyExactOperator>(&I))
3619       exact = ExactOp->isExact();
3620   }
3621   SDNodeFlags Flags;
3622   Flags.setExact(exact);
3623   Flags.setNoSignedWrap(nsw);
3624   Flags.setNoUnsignedWrap(nuw);
3625   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3626                             Flags);
3627   setValue(&I, Res);
3628 }
3629 
3630 void SelectionDAGBuilder::visitSDiv(const User &I) {
3631   SDValue Op1 = getValue(I.getOperand(0));
3632   SDValue Op2 = getValue(I.getOperand(1));
3633 
3634   SDNodeFlags Flags;
3635   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3636                  cast<PossiblyExactOperator>(&I)->isExact());
3637   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3638                            Op2, Flags));
3639 }
3640 
3641 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3642   ICmpInst::Predicate predicate = I.getPredicate();
3643   SDValue Op1 = getValue(I.getOperand(0));
3644   SDValue Op2 = getValue(I.getOperand(1));
3645   ISD::CondCode Opcode = getICmpCondCode(predicate);
3646 
3647   auto &TLI = DAG.getTargetLoweringInfo();
3648   EVT MemVT =
3649       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3650 
3651   // If a pointer's DAG type is larger than its memory type then the DAG values
3652   // are zero-extended. This breaks signed comparisons so truncate back to the
3653   // underlying type before doing the compare.
3654   if (Op1.getValueType() != MemVT) {
3655     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3656     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3657   }
3658 
3659   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3660                                                         I.getType());
3661   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3662 }
3663 
3664 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3665   FCmpInst::Predicate predicate = I.getPredicate();
3666   SDValue Op1 = getValue(I.getOperand(0));
3667   SDValue Op2 = getValue(I.getOperand(1));
3668 
3669   ISD::CondCode Condition = getFCmpCondCode(predicate);
3670   auto *FPMO = cast<FPMathOperator>(&I);
3671   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3672     Condition = getFCmpCodeWithoutNaN(Condition);
3673 
3674   SDNodeFlags Flags;
3675   Flags.copyFMF(*FPMO);
3676   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3677 
3678   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3679                                                         I.getType());
3680   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3681 }
3682 
3683 // Check if the condition of the select has one use or two users that are both
3684 // selects with the same condition.
3685 static bool hasOnlySelectUsers(const Value *Cond) {
3686   return llvm::all_of(Cond->users(), [](const Value *V) {
3687     return isa<SelectInst>(V);
3688   });
3689 }
3690 
3691 void SelectionDAGBuilder::visitSelect(const User &I) {
3692   SmallVector<EVT, 4> ValueVTs;
3693   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3694                   ValueVTs);
3695   unsigned NumValues = ValueVTs.size();
3696   if (NumValues == 0) return;
3697 
3698   SmallVector<SDValue, 4> Values(NumValues);
3699   SDValue Cond     = getValue(I.getOperand(0));
3700   SDValue LHSVal   = getValue(I.getOperand(1));
3701   SDValue RHSVal   = getValue(I.getOperand(2));
3702   SmallVector<SDValue, 1> BaseOps(1, Cond);
3703   ISD::NodeType OpCode =
3704       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3705 
3706   bool IsUnaryAbs = false;
3707   bool Negate = false;
3708 
3709   SDNodeFlags Flags;
3710   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3711     Flags.copyFMF(*FPOp);
3712 
3713   Flags.setUnpredictable(
3714       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3715 
3716   // Min/max matching is only viable if all output VTs are the same.
3717   if (all_equal(ValueVTs)) {
3718     EVT VT = ValueVTs[0];
3719     LLVMContext &Ctx = *DAG.getContext();
3720     auto &TLI = DAG.getTargetLoweringInfo();
3721 
3722     // We care about the legality of the operation after it has been type
3723     // legalized.
3724     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3725       VT = TLI.getTypeToTransformTo(Ctx, VT);
3726 
3727     // If the vselect is legal, assume we want to leave this as a vector setcc +
3728     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3729     // min/max is legal on the scalar type.
3730     bool UseScalarMinMax = VT.isVector() &&
3731       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3732 
3733     // ValueTracking's select pattern matching does not account for -0.0,
3734     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3735     // -0.0 is less than +0.0.
3736     const Value *LHS, *RHS;
3737     auto SPR = matchSelectPattern(&I, LHS, RHS);
3738     ISD::NodeType Opc = ISD::DELETED_NODE;
3739     switch (SPR.Flavor) {
3740     case SPF_UMAX:    Opc = ISD::UMAX; break;
3741     case SPF_UMIN:    Opc = ISD::UMIN; break;
3742     case SPF_SMAX:    Opc = ISD::SMAX; break;
3743     case SPF_SMIN:    Opc = ISD::SMIN; break;
3744     case SPF_FMINNUM:
3745       switch (SPR.NaNBehavior) {
3746       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3747       case SPNB_RETURNS_NAN: break;
3748       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3749       case SPNB_RETURNS_ANY:
3750         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3751             (UseScalarMinMax &&
3752              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3753           Opc = ISD::FMINNUM;
3754         break;
3755       }
3756       break;
3757     case SPF_FMAXNUM:
3758       switch (SPR.NaNBehavior) {
3759       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3760       case SPNB_RETURNS_NAN: break;
3761       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3762       case SPNB_RETURNS_ANY:
3763         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3764             (UseScalarMinMax &&
3765              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3766           Opc = ISD::FMAXNUM;
3767         break;
3768       }
3769       break;
3770     case SPF_NABS:
3771       Negate = true;
3772       [[fallthrough]];
3773     case SPF_ABS:
3774       IsUnaryAbs = true;
3775       Opc = ISD::ABS;
3776       break;
3777     default: break;
3778     }
3779 
3780     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3781         (TLI.isOperationLegalOrCustomOrPromote(Opc, VT) ||
3782          (UseScalarMinMax &&
3783           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3784         // If the underlying comparison instruction is used by any other
3785         // instruction, the consumed instructions won't be destroyed, so it is
3786         // not profitable to convert to a min/max.
3787         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3788       OpCode = Opc;
3789       LHSVal = getValue(LHS);
3790       RHSVal = getValue(RHS);
3791       BaseOps.clear();
3792     }
3793 
3794     if (IsUnaryAbs) {
3795       OpCode = Opc;
3796       LHSVal = getValue(LHS);
3797       BaseOps.clear();
3798     }
3799   }
3800 
3801   if (IsUnaryAbs) {
3802     for (unsigned i = 0; i != NumValues; ++i) {
3803       SDLoc dl = getCurSDLoc();
3804       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3805       Values[i] =
3806           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3807       if (Negate)
3808         Values[i] = DAG.getNegative(Values[i], dl, VT);
3809     }
3810   } else {
3811     for (unsigned i = 0; i != NumValues; ++i) {
3812       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3813       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3814       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3815       Values[i] = DAG.getNode(
3816           OpCode, getCurSDLoc(),
3817           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3818     }
3819   }
3820 
3821   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3822                            DAG.getVTList(ValueVTs), Values));
3823 }
3824 
3825 void SelectionDAGBuilder::visitTrunc(const User &I) {
3826   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3827   SDValue N = getValue(I.getOperand(0));
3828   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3829                                                         I.getType());
3830   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N));
3831 }
3832 
3833 void SelectionDAGBuilder::visitZExt(const User &I) {
3834   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3835   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3836   SDValue N = getValue(I.getOperand(0));
3837   auto &TLI = DAG.getTargetLoweringInfo();
3838   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3839 
3840   SDNodeFlags Flags;
3841   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3842     Flags.setNonNeg(PNI->hasNonNeg());
3843 
3844   // Eagerly use nonneg information to canonicalize towards sign_extend if
3845   // that is the target's preference.
3846   // TODO: Let the target do this later.
3847   if (Flags.hasNonNeg() &&
3848       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3849     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3850     return;
3851   }
3852 
3853   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3854 }
3855 
3856 void SelectionDAGBuilder::visitSExt(const User &I) {
3857   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3858   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3859   SDValue N = getValue(I.getOperand(0));
3860   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3861                                                         I.getType());
3862   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3863 }
3864 
3865 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3866   // FPTrunc is never a no-op cast, no need to check
3867   SDValue N = getValue(I.getOperand(0));
3868   SDLoc dl = getCurSDLoc();
3869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3870   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3871   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3872                            DAG.getTargetConstant(
3873                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3874 }
3875 
3876 void SelectionDAGBuilder::visitFPExt(const User &I) {
3877   // FPExt is never a no-op cast, no need to check
3878   SDValue N = getValue(I.getOperand(0));
3879   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3880                                                         I.getType());
3881   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3882 }
3883 
3884 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3885   // FPToUI is never a no-op cast, no need to check
3886   SDValue N = getValue(I.getOperand(0));
3887   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3888                                                         I.getType());
3889   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3890 }
3891 
3892 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3893   // FPToSI is never a no-op cast, no need to check
3894   SDValue N = getValue(I.getOperand(0));
3895   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3896                                                         I.getType());
3897   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3898 }
3899 
3900 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3901   // UIToFP is never a no-op cast, no need to check
3902   SDValue N = getValue(I.getOperand(0));
3903   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3904                                                         I.getType());
3905   SDNodeFlags Flags;
3906   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3907     Flags.setNonNeg(PNI->hasNonNeg());
3908 
3909   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3910 }
3911 
3912 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3913   // SIToFP is never a no-op cast, no need to check
3914   SDValue N = getValue(I.getOperand(0));
3915   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3916                                                         I.getType());
3917   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3918 }
3919 
3920 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3921   // What to do depends on the size of the integer and the size of the pointer.
3922   // We can either truncate, zero extend, or no-op, accordingly.
3923   SDValue N = getValue(I.getOperand(0));
3924   auto &TLI = DAG.getTargetLoweringInfo();
3925   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3926                                                         I.getType());
3927   EVT PtrMemVT =
3928       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3929   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3930   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3931   setValue(&I, N);
3932 }
3933 
3934 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3935   // What to do depends on the size of the integer and the size of the pointer.
3936   // We can either truncate, zero extend, or no-op, accordingly.
3937   SDValue N = getValue(I.getOperand(0));
3938   auto &TLI = DAG.getTargetLoweringInfo();
3939   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3940   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3941   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3942   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3943   setValue(&I, N);
3944 }
3945 
3946 void SelectionDAGBuilder::visitBitCast(const User &I) {
3947   SDValue N = getValue(I.getOperand(0));
3948   SDLoc dl = getCurSDLoc();
3949   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3950                                                         I.getType());
3951 
3952   // BitCast assures us that source and destination are the same size so this is
3953   // either a BITCAST or a no-op.
3954   if (DestVT != N.getValueType())
3955     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3956                              DestVT, N)); // convert types.
3957   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3958   // might fold any kind of constant expression to an integer constant and that
3959   // is not what we are looking for. Only recognize a bitcast of a genuine
3960   // constant integer as an opaque constant.
3961   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3962     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3963                                  /*isOpaque*/true));
3964   else
3965     setValue(&I, N);            // noop cast.
3966 }
3967 
3968 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3969   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3970   const Value *SV = I.getOperand(0);
3971   SDValue N = getValue(SV);
3972   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3973 
3974   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3975   unsigned DestAS = I.getType()->getPointerAddressSpace();
3976 
3977   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3978     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3979 
3980   setValue(&I, N);
3981 }
3982 
3983 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3984   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3985   SDValue InVec = getValue(I.getOperand(0));
3986   SDValue InVal = getValue(I.getOperand(1));
3987   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3988                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3989   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
3990                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
3991                            InVec, InVal, InIdx));
3992 }
3993 
3994 void SelectionDAGBuilder::visitExtractElement(const User &I) {
3995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3996   SDValue InVec = getValue(I.getOperand(0));
3997   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
3998                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
3999   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
4000                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
4001                            InVec, InIdx));
4002 }
4003 
4004 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4005   SDValue Src1 = getValue(I.getOperand(0));
4006   SDValue Src2 = getValue(I.getOperand(1));
4007   ArrayRef<int> Mask;
4008   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4009     Mask = SVI->getShuffleMask();
4010   else
4011     Mask = cast<ConstantExpr>(I).getShuffleMask();
4012   SDLoc DL = getCurSDLoc();
4013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4014   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4015   EVT SrcVT = Src1.getValueType();
4016 
4017   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4018       VT.isScalableVector()) {
4019     // Canonical splat form of first element of first input vector.
4020     SDValue FirstElt =
4021         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4022                     DAG.getVectorIdxConstant(0, DL));
4023     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4024     return;
4025   }
4026 
4027   // For now, we only handle splats for scalable vectors.
4028   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4029   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4030   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4031 
4032   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4033   unsigned MaskNumElts = Mask.size();
4034 
4035   if (SrcNumElts == MaskNumElts) {
4036     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4037     return;
4038   }
4039 
4040   // Normalize the shuffle vector since mask and vector length don't match.
4041   if (SrcNumElts < MaskNumElts) {
4042     // Mask is longer than the source vectors. We can use concatenate vector to
4043     // make the mask and vectors lengths match.
4044 
4045     if (MaskNumElts % SrcNumElts == 0) {
4046       // Mask length is a multiple of the source vector length.
4047       // Check if the shuffle is some kind of concatenation of the input
4048       // vectors.
4049       unsigned NumConcat = MaskNumElts / SrcNumElts;
4050       bool IsConcat = true;
4051       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4052       for (unsigned i = 0; i != MaskNumElts; ++i) {
4053         int Idx = Mask[i];
4054         if (Idx < 0)
4055           continue;
4056         // Ensure the indices in each SrcVT sized piece are sequential and that
4057         // the same source is used for the whole piece.
4058         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4059             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4060              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4061           IsConcat = false;
4062           break;
4063         }
4064         // Remember which source this index came from.
4065         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4066       }
4067 
4068       // The shuffle is concatenating multiple vectors together. Just emit
4069       // a CONCAT_VECTORS operation.
4070       if (IsConcat) {
4071         SmallVector<SDValue, 8> ConcatOps;
4072         for (auto Src : ConcatSrcs) {
4073           if (Src < 0)
4074             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4075           else if (Src == 0)
4076             ConcatOps.push_back(Src1);
4077           else
4078             ConcatOps.push_back(Src2);
4079         }
4080         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4081         return;
4082       }
4083     }
4084 
4085     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4086     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4087     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4088                                     PaddedMaskNumElts);
4089 
4090     // Pad both vectors with undefs to make them the same length as the mask.
4091     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4092 
4093     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4094     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4095     MOps1[0] = Src1;
4096     MOps2[0] = Src2;
4097 
4098     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4099     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4100 
4101     // Readjust mask for new input vector length.
4102     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4103     for (unsigned i = 0; i != MaskNumElts; ++i) {
4104       int Idx = Mask[i];
4105       if (Idx >= (int)SrcNumElts)
4106         Idx -= SrcNumElts - PaddedMaskNumElts;
4107       MappedOps[i] = Idx;
4108     }
4109 
4110     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4111 
4112     // If the concatenated vector was padded, extract a subvector with the
4113     // correct number of elements.
4114     if (MaskNumElts != PaddedMaskNumElts)
4115       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4116                            DAG.getVectorIdxConstant(0, DL));
4117 
4118     setValue(&I, Result);
4119     return;
4120   }
4121 
4122   if (SrcNumElts > MaskNumElts) {
4123     // Analyze the access pattern of the vector to see if we can extract
4124     // two subvectors and do the shuffle.
4125     int StartIdx[2] = { -1, -1 };  // StartIdx to extract from
4126     bool CanExtract = true;
4127     for (int Idx : Mask) {
4128       unsigned Input = 0;
4129       if (Idx < 0)
4130         continue;
4131 
4132       if (Idx >= (int)SrcNumElts) {
4133         Input = 1;
4134         Idx -= SrcNumElts;
4135       }
4136 
4137       // If all the indices come from the same MaskNumElts sized portion of
4138       // the sources we can use extract. Also make sure the extract wouldn't
4139       // extract past the end of the source.
4140       int NewStartIdx = alignDown(Idx, MaskNumElts);
4141       if (NewStartIdx + MaskNumElts > SrcNumElts ||
4142           (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4143         CanExtract = false;
4144       // Make sure we always update StartIdx as we use it to track if all
4145       // elements are undef.
4146       StartIdx[Input] = NewStartIdx;
4147     }
4148 
4149     if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4150       setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4151       return;
4152     }
4153     if (CanExtract) {
4154       // Extract appropriate subvector and generate a vector shuffle
4155       for (unsigned Input = 0; Input < 2; ++Input) {
4156         SDValue &Src = Input == 0 ? Src1 : Src2;
4157         if (StartIdx[Input] < 0)
4158           Src = DAG.getUNDEF(VT);
4159         else {
4160           Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4161                             DAG.getVectorIdxConstant(StartIdx[Input], DL));
4162         }
4163       }
4164 
4165       // Calculate new mask.
4166       SmallVector<int, 8> MappedOps(Mask);
4167       for (int &Idx : MappedOps) {
4168         if (Idx >= (int)SrcNumElts)
4169           Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4170         else if (Idx >= 0)
4171           Idx -= StartIdx[0];
4172       }
4173 
4174       setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4175       return;
4176     }
4177   }
4178 
4179   // We can't use either concat vectors or extract subvectors so fall back to
4180   // replacing the shuffle with extract and build vector.
4181   // to insert and build vector.
4182   EVT EltVT = VT.getVectorElementType();
4183   SmallVector<SDValue,8> Ops;
4184   for (int Idx : Mask) {
4185     SDValue Res;
4186 
4187     if (Idx < 0) {
4188       Res = DAG.getUNDEF(EltVT);
4189     } else {
4190       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4191       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4192 
4193       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4194                         DAG.getVectorIdxConstant(Idx, DL));
4195     }
4196 
4197     Ops.push_back(Res);
4198   }
4199 
4200   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4201 }
4202 
4203 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4204   ArrayRef<unsigned> Indices = I.getIndices();
4205   const Value *Op0 = I.getOperand(0);
4206   const Value *Op1 = I.getOperand(1);
4207   Type *AggTy = I.getType();
4208   Type *ValTy = Op1->getType();
4209   bool IntoUndef = isa<UndefValue>(Op0);
4210   bool FromUndef = isa<UndefValue>(Op1);
4211 
4212   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4213 
4214   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4215   SmallVector<EVT, 4> AggValueVTs;
4216   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4217   SmallVector<EVT, 4> ValValueVTs;
4218   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4219 
4220   unsigned NumAggValues = AggValueVTs.size();
4221   unsigned NumValValues = ValValueVTs.size();
4222   SmallVector<SDValue, 4> Values(NumAggValues);
4223 
4224   // Ignore an insertvalue that produces an empty object
4225   if (!NumAggValues) {
4226     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4227     return;
4228   }
4229 
4230   SDValue Agg = getValue(Op0);
4231   unsigned i = 0;
4232   // Copy the beginning value(s) from the original aggregate.
4233   for (; i != LinearIndex; ++i)
4234     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4235                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4236   // Copy values from the inserted value(s).
4237   if (NumValValues) {
4238     SDValue Val = getValue(Op1);
4239     for (; i != LinearIndex + NumValValues; ++i)
4240       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4241                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4242   }
4243   // Copy remaining value(s) from the original aggregate.
4244   for (; i != NumAggValues; ++i)
4245     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4246                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4247 
4248   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4249                            DAG.getVTList(AggValueVTs), Values));
4250 }
4251 
4252 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4253   ArrayRef<unsigned> Indices = I.getIndices();
4254   const Value *Op0 = I.getOperand(0);
4255   Type *AggTy = Op0->getType();
4256   Type *ValTy = I.getType();
4257   bool OutOfUndef = isa<UndefValue>(Op0);
4258 
4259   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4260 
4261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4262   SmallVector<EVT, 4> ValValueVTs;
4263   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4264 
4265   unsigned NumValValues = ValValueVTs.size();
4266 
4267   // Ignore a extractvalue that produces an empty object
4268   if (!NumValValues) {
4269     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4270     return;
4271   }
4272 
4273   SmallVector<SDValue, 4> Values(NumValValues);
4274 
4275   SDValue Agg = getValue(Op0);
4276   // Copy out the selected value(s).
4277   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4278     Values[i - LinearIndex] =
4279       OutOfUndef ?
4280         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4281         SDValue(Agg.getNode(), Agg.getResNo() + i);
4282 
4283   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4284                            DAG.getVTList(ValValueVTs), Values));
4285 }
4286 
4287 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4288   Value *Op0 = I.getOperand(0);
4289   // Note that the pointer operand may be a vector of pointers. Take the scalar
4290   // element which holds a pointer.
4291   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4292   SDValue N = getValue(Op0);
4293   SDLoc dl = getCurSDLoc();
4294   auto &TLI = DAG.getTargetLoweringInfo();
4295   GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4296 
4297   // Normalize Vector GEP - all scalar operands should be converted to the
4298   // splat vector.
4299   bool IsVectorGEP = I.getType()->isVectorTy();
4300   ElementCount VectorElementCount =
4301       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4302                   : ElementCount::getFixed(0);
4303 
4304   if (IsVectorGEP && !N.getValueType().isVector()) {
4305     LLVMContext &Context = *DAG.getContext();
4306     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4307     N = DAG.getSplat(VT, dl, N);
4308   }
4309 
4310   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4311        GTI != E; ++GTI) {
4312     const Value *Idx = GTI.getOperand();
4313     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4314       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4315       if (Field) {
4316         // N = N + Offset
4317         uint64_t Offset =
4318             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4319 
4320         // In an inbounds GEP with an offset that is nonnegative even when
4321         // interpreted as signed, assume there is no unsigned overflow.
4322         SDNodeFlags Flags;
4323         if (NW.hasNoUnsignedWrap() ||
4324             (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4325           Flags.setNoUnsignedWrap(true);
4326 
4327         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4328                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4329       }
4330     } else {
4331       // IdxSize is the width of the arithmetic according to IR semantics.
4332       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4333       // (and fix up the result later).
4334       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4335       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4336       TypeSize ElementSize =
4337           GTI.getSequentialElementStride(DAG.getDataLayout());
4338       // We intentionally mask away the high bits here; ElementSize may not
4339       // fit in IdxTy.
4340       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue());
4341       bool ElementScalable = ElementSize.isScalable();
4342 
4343       // If this is a scalar constant or a splat vector of constants,
4344       // handle it quickly.
4345       const auto *C = dyn_cast<Constant>(Idx);
4346       if (C && isa<VectorType>(C->getType()))
4347         C = C->getSplatValue();
4348 
4349       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4350       if (CI && CI->isZero())
4351         continue;
4352       if (CI && !ElementScalable) {
4353         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4354         LLVMContext &Context = *DAG.getContext();
4355         SDValue OffsVal;
4356         if (IsVectorGEP)
4357           OffsVal = DAG.getConstant(
4358               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4359         else
4360           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4361 
4362         // In an inbounds GEP with an offset that is nonnegative even when
4363         // interpreted as signed, assume there is no unsigned overflow.
4364         SDNodeFlags Flags;
4365         if (NW.hasNoUnsignedWrap() ||
4366             (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4367           Flags.setNoUnsignedWrap(true);
4368 
4369         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4370 
4371         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4372         continue;
4373       }
4374 
4375       // N = N + Idx * ElementMul;
4376       SDValue IdxN = getValue(Idx);
4377 
4378       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4379         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4380                                   VectorElementCount);
4381         IdxN = DAG.getSplat(VT, dl, IdxN);
4382       }
4383 
4384       // If the index is smaller or larger than intptr_t, truncate or extend
4385       // it.
4386       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4387 
4388       if (ElementScalable) {
4389         EVT VScaleTy = N.getValueType().getScalarType();
4390         SDValue VScale = DAG.getNode(
4391             ISD::VSCALE, dl, VScaleTy,
4392             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4393         if (IsVectorGEP)
4394           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4395         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale);
4396       } else {
4397         // If this is a multiply by a power of two, turn it into a shl
4398         // immediately.  This is a very common case.
4399         if (ElementMul != 1) {
4400           if (ElementMul.isPowerOf2()) {
4401             unsigned Amt = ElementMul.logBase2();
4402             IdxN = DAG.getNode(ISD::SHL, dl,
4403                                N.getValueType(), IdxN,
4404                                DAG.getConstant(Amt, dl, IdxN.getValueType()));
4405           } else {
4406             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4407                                             IdxN.getValueType());
4408             IdxN = DAG.getNode(ISD::MUL, dl,
4409                                N.getValueType(), IdxN, Scale);
4410           }
4411         }
4412       }
4413 
4414       N = DAG.getNode(ISD::ADD, dl,
4415                       N.getValueType(), N, IdxN);
4416     }
4417   }
4418 
4419   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4420   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4421   if (IsVectorGEP) {
4422     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4423     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4424   }
4425 
4426   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4427     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4428 
4429   setValue(&I, N);
4430 }
4431 
4432 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4433   // If this is a fixed sized alloca in the entry block of the function,
4434   // allocate it statically on the stack.
4435   if (FuncInfo.StaticAllocaMap.count(&I))
4436     return;   // getValue will auto-populate this.
4437 
4438   SDLoc dl = getCurSDLoc();
4439   Type *Ty = I.getAllocatedType();
4440   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4441   auto &DL = DAG.getDataLayout();
4442   TypeSize TySize = DL.getTypeAllocSize(Ty);
4443   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4444 
4445   SDValue AllocSize = getValue(I.getArraySize());
4446 
4447   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4448   if (AllocSize.getValueType() != IntPtr)
4449     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4450 
4451   if (TySize.isScalable())
4452     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4453                             DAG.getVScale(dl, IntPtr,
4454                                           APInt(IntPtr.getScalarSizeInBits(),
4455                                                 TySize.getKnownMinValue())));
4456   else {
4457     SDValue TySizeValue =
4458         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4459     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4460                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4461   }
4462 
4463   // Handle alignment.  If the requested alignment is less than or equal to
4464   // the stack alignment, ignore it.  If the size is greater than or equal to
4465   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4466   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4467   if (*Alignment <= StackAlign)
4468     Alignment = std::nullopt;
4469 
4470   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4471   // Round the size of the allocation up to the stack alignment size
4472   // by add SA-1 to the size. This doesn't overflow because we're computing
4473   // an address inside an alloca.
4474   SDNodeFlags Flags;
4475   Flags.setNoUnsignedWrap(true);
4476   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4477                           DAG.getConstant(StackAlignMask, dl, IntPtr), Flags);
4478 
4479   // Mask out the low bits for alignment purposes.
4480   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4481                           DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4482 
4483   SDValue Ops[] = {
4484       getRoot(), AllocSize,
4485       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4486   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4487   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4488   setValue(&I, DSA);
4489   DAG.setRoot(DSA.getValue(1));
4490 
4491   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4492 }
4493 
4494 static const MDNode *getRangeMetadata(const Instruction &I) {
4495   // If !noundef is not present, then !range violation results in a poison
4496   // value rather than immediate undefined behavior. In theory, transferring
4497   // these annotations to SDAG is fine, but in practice there are key SDAG
4498   // transforms that are known not to be poison-safe, such as folding logical
4499   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4500   // also present.
4501   if (!I.hasMetadata(LLVMContext::MD_noundef))
4502     return nullptr;
4503   return I.getMetadata(LLVMContext::MD_range);
4504 }
4505 
4506 static std::optional<ConstantRange> getRange(const Instruction &I) {
4507   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4508     // see comment in getRangeMetadata about this check
4509     if (CB->hasRetAttr(Attribute::NoUndef))
4510       return CB->getRange();
4511   }
4512   if (const MDNode *Range = getRangeMetadata(I))
4513     return getConstantRangeFromMetadata(*Range);
4514   return std::nullopt;
4515 }
4516 
4517 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4518   if (I.isAtomic())
4519     return visitAtomicLoad(I);
4520 
4521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4522   const Value *SV = I.getOperand(0);
4523   if (TLI.supportSwiftError()) {
4524     // Swifterror values can come from either a function parameter with
4525     // swifterror attribute or an alloca with swifterror attribute.
4526     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4527       if (Arg->hasSwiftErrorAttr())
4528         return visitLoadFromSwiftError(I);
4529     }
4530 
4531     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4532       if (Alloca->isSwiftError())
4533         return visitLoadFromSwiftError(I);
4534     }
4535   }
4536 
4537   SDValue Ptr = getValue(SV);
4538 
4539   Type *Ty = I.getType();
4540   SmallVector<EVT, 4> ValueVTs, MemVTs;
4541   SmallVector<TypeSize, 4> Offsets;
4542   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4543   unsigned NumValues = ValueVTs.size();
4544   if (NumValues == 0)
4545     return;
4546 
4547   Align Alignment = I.getAlign();
4548   AAMDNodes AAInfo = I.getAAMetadata();
4549   const MDNode *Ranges = getRangeMetadata(I);
4550   bool isVolatile = I.isVolatile();
4551   MachineMemOperand::Flags MMOFlags =
4552       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4553 
4554   SDValue Root;
4555   bool ConstantMemory = false;
4556   if (isVolatile)
4557     // Serialize volatile loads with other side effects.
4558     Root = getRoot();
4559   else if (NumValues > MaxParallelChains)
4560     Root = getMemoryRoot();
4561   else if (AA &&
4562            AA->pointsToConstantMemory(MemoryLocation(
4563                SV,
4564                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4565                AAInfo))) {
4566     // Do not serialize (non-volatile) loads of constant memory with anything.
4567     Root = DAG.getEntryNode();
4568     ConstantMemory = true;
4569     MMOFlags |= MachineMemOperand::MOInvariant;
4570   } else {
4571     // Do not serialize non-volatile loads against each other.
4572     Root = DAG.getRoot();
4573   }
4574 
4575   SDLoc dl = getCurSDLoc();
4576 
4577   if (isVolatile)
4578     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4579 
4580   SmallVector<SDValue, 4> Values(NumValues);
4581   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4582 
4583   unsigned ChainI = 0;
4584   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4585     // Serializing loads here may result in excessive register pressure, and
4586     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4587     // could recover a bit by hoisting nodes upward in the chain by recognizing
4588     // they are side-effect free or do not alias. The optimizer should really
4589     // avoid this case by converting large object/array copies to llvm.memcpy
4590     // (MaxParallelChains should always remain as failsafe).
4591     if (ChainI == MaxParallelChains) {
4592       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4593       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4594                                   ArrayRef(Chains.data(), ChainI));
4595       Root = Chain;
4596       ChainI = 0;
4597     }
4598 
4599     // TODO: MachinePointerInfo only supports a fixed length offset.
4600     MachinePointerInfo PtrInfo =
4601         !Offsets[i].isScalable() || Offsets[i].isZero()
4602             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4603             : MachinePointerInfo();
4604 
4605     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4606     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4607                             MMOFlags, AAInfo, Ranges);
4608     Chains[ChainI] = L.getValue(1);
4609 
4610     if (MemVTs[i] != ValueVTs[i])
4611       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4612 
4613     Values[i] = L;
4614   }
4615 
4616   if (!ConstantMemory) {
4617     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4618                                 ArrayRef(Chains.data(), ChainI));
4619     if (isVolatile)
4620       DAG.setRoot(Chain);
4621     else
4622       PendingLoads.push_back(Chain);
4623   }
4624 
4625   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4626                            DAG.getVTList(ValueVTs), Values));
4627 }
4628 
4629 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4630   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4631          "call visitStoreToSwiftError when backend supports swifterror");
4632 
4633   SmallVector<EVT, 4> ValueVTs;
4634   SmallVector<uint64_t, 4> Offsets;
4635   const Value *SrcV = I.getOperand(0);
4636   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4637                   SrcV->getType(), ValueVTs, &Offsets, 0);
4638   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4639          "expect a single EVT for swifterror");
4640 
4641   SDValue Src = getValue(SrcV);
4642   // Create a virtual register, then update the virtual register.
4643   Register VReg =
4644       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4645   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4646   // Chain can be getRoot or getControlRoot.
4647   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4648                                       SDValue(Src.getNode(), Src.getResNo()));
4649   DAG.setRoot(CopyNode);
4650 }
4651 
4652 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4653   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4654          "call visitLoadFromSwiftError when backend supports swifterror");
4655 
4656   assert(!I.isVolatile() &&
4657          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4658          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4659          "Support volatile, non temporal, invariant for load_from_swift_error");
4660 
4661   const Value *SV = I.getOperand(0);
4662   Type *Ty = I.getType();
4663   assert(
4664       (!AA ||
4665        !AA->pointsToConstantMemory(MemoryLocation(
4666            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4667            I.getAAMetadata()))) &&
4668       "load_from_swift_error should not be constant memory");
4669 
4670   SmallVector<EVT, 4> ValueVTs;
4671   SmallVector<uint64_t, 4> Offsets;
4672   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4673                   ValueVTs, &Offsets, 0);
4674   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4675          "expect a single EVT for swifterror");
4676 
4677   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4678   SDValue L = DAG.getCopyFromReg(
4679       getRoot(), getCurSDLoc(),
4680       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4681 
4682   setValue(&I, L);
4683 }
4684 
4685 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4686   if (I.isAtomic())
4687     return visitAtomicStore(I);
4688 
4689   const Value *SrcV = I.getOperand(0);
4690   const Value *PtrV = I.getOperand(1);
4691 
4692   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4693   if (TLI.supportSwiftError()) {
4694     // Swifterror values can come from either a function parameter with
4695     // swifterror attribute or an alloca with swifterror attribute.
4696     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4697       if (Arg->hasSwiftErrorAttr())
4698         return visitStoreToSwiftError(I);
4699     }
4700 
4701     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4702       if (Alloca->isSwiftError())
4703         return visitStoreToSwiftError(I);
4704     }
4705   }
4706 
4707   SmallVector<EVT, 4> ValueVTs, MemVTs;
4708   SmallVector<TypeSize, 4> Offsets;
4709   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4710                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4711   unsigned NumValues = ValueVTs.size();
4712   if (NumValues == 0)
4713     return;
4714 
4715   // Get the lowered operands. Note that we do this after
4716   // checking if NumResults is zero, because with zero results
4717   // the operands won't have values in the map.
4718   SDValue Src = getValue(SrcV);
4719   SDValue Ptr = getValue(PtrV);
4720 
4721   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4722   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4723   SDLoc dl = getCurSDLoc();
4724   Align Alignment = I.getAlign();
4725   AAMDNodes AAInfo = I.getAAMetadata();
4726 
4727   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4728 
4729   unsigned ChainI = 0;
4730   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4731     // See visitLoad comments.
4732     if (ChainI == MaxParallelChains) {
4733       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4734                                   ArrayRef(Chains.data(), ChainI));
4735       Root = Chain;
4736       ChainI = 0;
4737     }
4738 
4739     // TODO: MachinePointerInfo only supports a fixed length offset.
4740     MachinePointerInfo PtrInfo =
4741         !Offsets[i].isScalable() || Offsets[i].isZero()
4742             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4743             : MachinePointerInfo();
4744 
4745     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4746     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4747     if (MemVTs[i] != ValueVTs[i])
4748       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4749     SDValue St =
4750         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4751     Chains[ChainI] = St;
4752   }
4753 
4754   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4755                                   ArrayRef(Chains.data(), ChainI));
4756   setValue(&I, StoreNode);
4757   DAG.setRoot(StoreNode);
4758 }
4759 
4760 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4761                                            bool IsCompressing) {
4762   SDLoc sdl = getCurSDLoc();
4763 
4764   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4765                                Align &Alignment) {
4766     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4767     Src0 = I.getArgOperand(0);
4768     Ptr = I.getArgOperand(1);
4769     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4770     Mask = I.getArgOperand(3);
4771   };
4772   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4773                                     Align &Alignment) {
4774     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4775     Src0 = I.getArgOperand(0);
4776     Ptr = I.getArgOperand(1);
4777     Mask = I.getArgOperand(2);
4778     Alignment = I.getParamAlign(1).valueOrOne();
4779   };
4780 
4781   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4782   Align Alignment;
4783   if (IsCompressing)
4784     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4785   else
4786     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4787 
4788   SDValue Ptr = getValue(PtrOperand);
4789   SDValue Src0 = getValue(Src0Operand);
4790   SDValue Mask = getValue(MaskOperand);
4791   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4792 
4793   EVT VT = Src0.getValueType();
4794 
4795   auto MMOFlags = MachineMemOperand::MOStore;
4796   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4797     MMOFlags |= MachineMemOperand::MONonTemporal;
4798 
4799   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4800       MachinePointerInfo(PtrOperand), MMOFlags,
4801       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4802 
4803   const auto &TLI = DAG.getTargetLoweringInfo();
4804   const auto &TTI =
4805       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4806   SDValue StoreNode =
4807       !IsCompressing &&
4808               TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType())
4809           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4810                                  Mask)
4811           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4812                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4813                                IsCompressing);
4814   DAG.setRoot(StoreNode);
4815   setValue(&I, StoreNode);
4816 }
4817 
4818 // Get a uniform base for the Gather/Scatter intrinsic.
4819 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4820 // We try to represent it as a base pointer + vector of indices.
4821 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4822 // The first operand of the GEP may be a single pointer or a vector of pointers
4823 // Example:
4824 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4825 //  or
4826 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4827 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4828 //
4829 // When the first GEP operand is a single pointer - it is the uniform base we
4830 // are looking for. If first operand of the GEP is a splat vector - we
4831 // extract the splat value and use it as a uniform base.
4832 // In all other cases the function returns 'false'.
4833 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4834                            ISD::MemIndexType &IndexType, SDValue &Scale,
4835                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4836                            uint64_t ElemSize) {
4837   SelectionDAG& DAG = SDB->DAG;
4838   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4839   const DataLayout &DL = DAG.getDataLayout();
4840 
4841   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4842 
4843   // Handle splat constant pointer.
4844   if (auto *C = dyn_cast<Constant>(Ptr)) {
4845     C = C->getSplatValue();
4846     if (!C)
4847       return false;
4848 
4849     Base = SDB->getValue(C);
4850 
4851     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4852     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4853     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4854     IndexType = ISD::SIGNED_SCALED;
4855     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4856     return true;
4857   }
4858 
4859   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4860   if (!GEP || GEP->getParent() != CurBB)
4861     return false;
4862 
4863   if (GEP->getNumOperands() != 2)
4864     return false;
4865 
4866   const Value *BasePtr = GEP->getPointerOperand();
4867   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4868 
4869   // Make sure the base is scalar and the index is a vector.
4870   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4871     return false;
4872 
4873   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4874   if (ScaleVal.isScalable())
4875     return false;
4876 
4877   // Target may not support the required addressing mode.
4878   if (ScaleVal != 1 &&
4879       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4880     return false;
4881 
4882   Base = SDB->getValue(BasePtr);
4883   Index = SDB->getValue(IndexVal);
4884   IndexType = ISD::SIGNED_SCALED;
4885 
4886   Scale =
4887       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4888   return true;
4889 }
4890 
4891 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4892   SDLoc sdl = getCurSDLoc();
4893 
4894   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4895   const Value *Ptr = I.getArgOperand(1);
4896   SDValue Src0 = getValue(I.getArgOperand(0));
4897   SDValue Mask = getValue(I.getArgOperand(3));
4898   EVT VT = Src0.getValueType();
4899   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4900                         ->getMaybeAlignValue()
4901                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4902   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4903 
4904   SDValue Base;
4905   SDValue Index;
4906   ISD::MemIndexType IndexType;
4907   SDValue Scale;
4908   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4909                                     I.getParent(), VT.getScalarStoreSize());
4910 
4911   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4912   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4913       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4914       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4915   if (!UniformBase) {
4916     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4917     Index = getValue(Ptr);
4918     IndexType = ISD::SIGNED_SCALED;
4919     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4920   }
4921 
4922   EVT IdxVT = Index.getValueType();
4923   EVT EltTy = IdxVT.getVectorElementType();
4924   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4925     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4926     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4927   }
4928 
4929   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4930   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4931                                          Ops, MMO, IndexType, false);
4932   DAG.setRoot(Scatter);
4933   setValue(&I, Scatter);
4934 }
4935 
4936 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4937   SDLoc sdl = getCurSDLoc();
4938 
4939   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4940                               Align &Alignment) {
4941     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4942     Ptr = I.getArgOperand(0);
4943     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4944     Mask = I.getArgOperand(2);
4945     Src0 = I.getArgOperand(3);
4946   };
4947   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4948                                  Align &Alignment) {
4949     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4950     Ptr = I.getArgOperand(0);
4951     Alignment = I.getParamAlign(0).valueOrOne();
4952     Mask = I.getArgOperand(1);
4953     Src0 = I.getArgOperand(2);
4954   };
4955 
4956   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4957   Align Alignment;
4958   if (IsExpanding)
4959     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4960   else
4961     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4962 
4963   SDValue Ptr = getValue(PtrOperand);
4964   SDValue Src0 = getValue(Src0Operand);
4965   SDValue Mask = getValue(MaskOperand);
4966   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4967 
4968   EVT VT = Src0.getValueType();
4969   AAMDNodes AAInfo = I.getAAMetadata();
4970   const MDNode *Ranges = getRangeMetadata(I);
4971 
4972   // Do not serialize masked loads of constant memory with anything.
4973   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
4974   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
4975 
4976   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
4977 
4978   auto MMOFlags = MachineMemOperand::MOLoad;
4979   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4980     MMOFlags |= MachineMemOperand::MONonTemporal;
4981 
4982   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4983       MachinePointerInfo(PtrOperand), MMOFlags,
4984       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
4985 
4986   const auto &TLI = DAG.getTargetLoweringInfo();
4987   const auto &TTI =
4988       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4989   // The Load/Res may point to different values and both of them are output
4990   // variables.
4991   SDValue Load;
4992   SDValue Res;
4993   if (!IsExpanding &&
4994       TTI.hasConditionalLoadStoreForType(Src0Operand->getType()))
4995     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
4996   else
4997     Res = Load =
4998         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
4999                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5000   if (AddToChain)
5001     PendingLoads.push_back(Load.getValue(1));
5002   setValue(&I, Res);
5003 }
5004 
5005 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5006   SDLoc sdl = getCurSDLoc();
5007 
5008   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5009   const Value *Ptr = I.getArgOperand(0);
5010   SDValue Src0 = getValue(I.getArgOperand(3));
5011   SDValue Mask = getValue(I.getArgOperand(2));
5012 
5013   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5014   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5015   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5016                         ->getMaybeAlignValue()
5017                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5018 
5019   const MDNode *Ranges = getRangeMetadata(I);
5020 
5021   SDValue Root = DAG.getRoot();
5022   SDValue Base;
5023   SDValue Index;
5024   ISD::MemIndexType IndexType;
5025   SDValue Scale;
5026   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5027                                     I.getParent(), VT.getScalarStoreSize());
5028   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5029   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5030       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5031       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5032       Ranges);
5033 
5034   if (!UniformBase) {
5035     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5036     Index = getValue(Ptr);
5037     IndexType = ISD::SIGNED_SCALED;
5038     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5039   }
5040 
5041   EVT IdxVT = Index.getValueType();
5042   EVT EltTy = IdxVT.getVectorElementType();
5043   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5044     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5045     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5046   }
5047 
5048   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5049   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5050                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5051 
5052   PendingLoads.push_back(Gather.getValue(1));
5053   setValue(&I, Gather);
5054 }
5055 
5056 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5057   SDLoc dl = getCurSDLoc();
5058   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5059   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5060   SyncScope::ID SSID = I.getSyncScopeID();
5061 
5062   SDValue InChain = getRoot();
5063 
5064   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5065   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5066 
5067   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5068   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5069 
5070   MachineFunction &MF = DAG.getMachineFunction();
5071   MachineMemOperand *MMO = MF.getMachineMemOperand(
5072       MachinePointerInfo(I.getPointerOperand()), Flags,
5073       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5074       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5075 
5076   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5077                                    dl, MemVT, VTs, InChain,
5078                                    getValue(I.getPointerOperand()),
5079                                    getValue(I.getCompareOperand()),
5080                                    getValue(I.getNewValOperand()), MMO);
5081 
5082   SDValue OutChain = L.getValue(2);
5083 
5084   setValue(&I, L);
5085   DAG.setRoot(OutChain);
5086 }
5087 
5088 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5089   SDLoc dl = getCurSDLoc();
5090   ISD::NodeType NT;
5091   switch (I.getOperation()) {
5092   default: llvm_unreachable("Unknown atomicrmw operation");
5093   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5094   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5095   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5096   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5097   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5098   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5099   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5100   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5101   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5102   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5103   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5104   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5105   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5106   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5107   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5108   case AtomicRMWInst::UIncWrap:
5109     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5110     break;
5111   case AtomicRMWInst::UDecWrap:
5112     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5113     break;
5114   }
5115   AtomicOrdering Ordering = I.getOrdering();
5116   SyncScope::ID SSID = I.getSyncScopeID();
5117 
5118   SDValue InChain = getRoot();
5119 
5120   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5122   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5123 
5124   MachineFunction &MF = DAG.getMachineFunction();
5125   MachineMemOperand *MMO = MF.getMachineMemOperand(
5126       MachinePointerInfo(I.getPointerOperand()), Flags,
5127       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5128       AAMDNodes(), nullptr, SSID, Ordering);
5129 
5130   SDValue L =
5131     DAG.getAtomic(NT, dl, MemVT, InChain,
5132                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5133                   MMO);
5134 
5135   SDValue OutChain = L.getValue(1);
5136 
5137   setValue(&I, L);
5138   DAG.setRoot(OutChain);
5139 }
5140 
5141 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5142   SDLoc dl = getCurSDLoc();
5143   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5144   SDValue Ops[3];
5145   Ops[0] = getRoot();
5146   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5147                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5148   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5149                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5150   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5151   setValue(&I, N);
5152   DAG.setRoot(N);
5153 }
5154 
5155 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5156   SDLoc dl = getCurSDLoc();
5157   AtomicOrdering Order = I.getOrdering();
5158   SyncScope::ID SSID = I.getSyncScopeID();
5159 
5160   SDValue InChain = getRoot();
5161 
5162   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5163   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5164   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5165 
5166   if (!TLI.supportsUnalignedAtomics() &&
5167       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5168     report_fatal_error("Cannot generate unaligned atomic load");
5169 
5170   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5171 
5172   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5173       MachinePointerInfo(I.getPointerOperand()), Flags,
5174       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5175       nullptr, SSID, Order);
5176 
5177   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5178 
5179   SDValue Ptr = getValue(I.getPointerOperand());
5180   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5181                             Ptr, MMO);
5182 
5183   SDValue OutChain = L.getValue(1);
5184   if (MemVT != VT)
5185     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5186 
5187   setValue(&I, L);
5188   DAG.setRoot(OutChain);
5189 }
5190 
5191 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5192   SDLoc dl = getCurSDLoc();
5193 
5194   AtomicOrdering Ordering = I.getOrdering();
5195   SyncScope::ID SSID = I.getSyncScopeID();
5196 
5197   SDValue InChain = getRoot();
5198 
5199   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5200   EVT MemVT =
5201       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5202 
5203   if (!TLI.supportsUnalignedAtomics() &&
5204       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5205     report_fatal_error("Cannot generate unaligned atomic store");
5206 
5207   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5208 
5209   MachineFunction &MF = DAG.getMachineFunction();
5210   MachineMemOperand *MMO = MF.getMachineMemOperand(
5211       MachinePointerInfo(I.getPointerOperand()), Flags,
5212       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5213       nullptr, SSID, Ordering);
5214 
5215   SDValue Val = getValue(I.getValueOperand());
5216   if (Val.getValueType() != MemVT)
5217     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5218   SDValue Ptr = getValue(I.getPointerOperand());
5219 
5220   SDValue OutChain =
5221       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5222 
5223   setValue(&I, OutChain);
5224   DAG.setRoot(OutChain);
5225 }
5226 
5227 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5228 /// node.
5229 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5230                                                unsigned Intrinsic) {
5231   // Ignore the callsite's attributes. A specific call site may be marked with
5232   // readnone, but the lowering code will expect the chain based on the
5233   // definition.
5234   const Function *F = I.getCalledFunction();
5235   bool HasChain = !F->doesNotAccessMemory();
5236   bool OnlyLoad =
5237       HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5238 
5239   // Build the operand list.
5240   SmallVector<SDValue, 8> Ops;
5241   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5242     if (OnlyLoad) {
5243       // We don't need to serialize loads against other loads.
5244       Ops.push_back(DAG.getRoot());
5245     } else {
5246       Ops.push_back(getRoot());
5247     }
5248   }
5249 
5250   // Info is set by getTgtMemIntrinsic
5251   TargetLowering::IntrinsicInfo Info;
5252   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5253   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5254                                                DAG.getMachineFunction(),
5255                                                Intrinsic);
5256 
5257   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5258   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5259       Info.opc == ISD::INTRINSIC_W_CHAIN)
5260     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5261                                         TLI.getPointerTy(DAG.getDataLayout())));
5262 
5263   // Add all operands of the call to the operand list.
5264   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5265     const Value *Arg = I.getArgOperand(i);
5266     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5267       Ops.push_back(getValue(Arg));
5268       continue;
5269     }
5270 
5271     // Use TargetConstant instead of a regular constant for immarg.
5272     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5273     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5274       assert(CI->getBitWidth() <= 64 &&
5275              "large intrinsic immediates not handled");
5276       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5277     } else {
5278       Ops.push_back(
5279           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5280     }
5281   }
5282 
5283   SmallVector<EVT, 4> ValueVTs;
5284   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5285 
5286   if (HasChain)
5287     ValueVTs.push_back(MVT::Other);
5288 
5289   SDVTList VTs = DAG.getVTList(ValueVTs);
5290 
5291   // Propagate fast-math-flags from IR to node(s).
5292   SDNodeFlags Flags;
5293   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5294     Flags.copyFMF(*FPMO);
5295   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5296 
5297   // Create the node.
5298   SDValue Result;
5299 
5300   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5301     auto *Token = Bundle->Inputs[0].get();
5302     SDValue ConvControlToken = getValue(Token);
5303     assert(Ops.back().getValueType() != MVT::Glue &&
5304            "Did not expected another glue node here.");
5305     ConvControlToken =
5306         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5307     Ops.push_back(ConvControlToken);
5308   }
5309 
5310   // In some cases, custom collection of operands from CallInst I may be needed.
5311   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5312   if (IsTgtIntrinsic) {
5313     // This is target intrinsic that touches memory
5314     //
5315     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5316     //       didn't yield anything useful.
5317     MachinePointerInfo MPI;
5318     if (Info.ptrVal)
5319       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5320     else if (Info.fallbackAddressSpace)
5321       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5322     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5323                                      Info.memVT, MPI, Info.align, Info.flags,
5324                                      Info.size, I.getAAMetadata());
5325   } else if (!HasChain) {
5326     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5327   } else if (!I.getType()->isVoidTy()) {
5328     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5329   } else {
5330     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5331   }
5332 
5333   if (HasChain) {
5334     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5335     if (OnlyLoad)
5336       PendingLoads.push_back(Chain);
5337     else
5338       DAG.setRoot(Chain);
5339   }
5340 
5341   if (!I.getType()->isVoidTy()) {
5342     if (!isa<VectorType>(I.getType()))
5343       Result = lowerRangeToAssertZExt(DAG, I, Result);
5344 
5345     MaybeAlign Alignment = I.getRetAlign();
5346 
5347     // Insert `assertalign` node if there's an alignment.
5348     if (InsertAssertAlign && Alignment) {
5349       Result =
5350           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5351     }
5352   }
5353 
5354   setValue(&I, Result);
5355 }
5356 
5357 /// GetSignificand - Get the significand and build it into a floating-point
5358 /// number with exponent of 1:
5359 ///
5360 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5361 ///
5362 /// where Op is the hexadecimal representation of floating point value.
5363 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5364   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5365                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5366   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5367                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5368   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5369 }
5370 
5371 /// GetExponent - Get the exponent:
5372 ///
5373 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5374 ///
5375 /// where Op is the hexadecimal representation of floating point value.
5376 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5377                            const TargetLowering &TLI, const SDLoc &dl) {
5378   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5379                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5380   SDValue t1 = DAG.getNode(
5381       ISD::SRL, dl, MVT::i32, t0,
5382       DAG.getConstant(23, dl,
5383                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5384   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5385                            DAG.getConstant(127, dl, MVT::i32));
5386   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5387 }
5388 
5389 /// getF32Constant - Get 32-bit floating point constant.
5390 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5391                               const SDLoc &dl) {
5392   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5393                            MVT::f32);
5394 }
5395 
5396 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5397                                        SelectionDAG &DAG) {
5398   // TODO: What fast-math-flags should be set on the floating-point nodes?
5399 
5400   //   IntegerPartOfX = ((int32_t)(t0);
5401   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5402 
5403   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5404   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5405   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5406 
5407   //   IntegerPartOfX <<= 23;
5408   IntegerPartOfX =
5409       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5410                   DAG.getConstant(23, dl,
5411                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5412                                       MVT::i32, DAG.getDataLayout())));
5413 
5414   SDValue TwoToFractionalPartOfX;
5415   if (LimitFloatPrecision <= 6) {
5416     // For floating-point precision of 6:
5417     //
5418     //   TwoToFractionalPartOfX =
5419     //     0.997535578f +
5420     //       (0.735607626f + 0.252464424f * x) * x;
5421     //
5422     // error 0.0144103317, which is 6 bits
5423     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5424                              getF32Constant(DAG, 0x3e814304, dl));
5425     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5426                              getF32Constant(DAG, 0x3f3c50c8, dl));
5427     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5428     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5429                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5430   } else if (LimitFloatPrecision <= 12) {
5431     // For floating-point precision of 12:
5432     //
5433     //   TwoToFractionalPartOfX =
5434     //     0.999892986f +
5435     //       (0.696457318f +
5436     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5437     //
5438     // error 0.000107046256, which is 13 to 14 bits
5439     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5440                              getF32Constant(DAG, 0x3da235e3, dl));
5441     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5442                              getF32Constant(DAG, 0x3e65b8f3, dl));
5443     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5444     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5445                              getF32Constant(DAG, 0x3f324b07, dl));
5446     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5447     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5448                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5449   } else { // LimitFloatPrecision <= 18
5450     // For floating-point precision of 18:
5451     //
5452     //   TwoToFractionalPartOfX =
5453     //     0.999999982f +
5454     //       (0.693148872f +
5455     //         (0.240227044f +
5456     //           (0.554906021e-1f +
5457     //             (0.961591928e-2f +
5458     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5459     // error 2.47208000*10^(-7), which is better than 18 bits
5460     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5461                              getF32Constant(DAG, 0x3924b03e, dl));
5462     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5463                              getF32Constant(DAG, 0x3ab24b87, dl));
5464     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5465     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5466                              getF32Constant(DAG, 0x3c1d8c17, dl));
5467     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5468     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5469                              getF32Constant(DAG, 0x3d634a1d, dl));
5470     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5471     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5472                              getF32Constant(DAG, 0x3e75fe14, dl));
5473     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5474     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5475                               getF32Constant(DAG, 0x3f317234, dl));
5476     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5477     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5478                                          getF32Constant(DAG, 0x3f800000, dl));
5479   }
5480 
5481   // Add the exponent into the result in integer domain.
5482   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5483   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5484                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5485 }
5486 
5487 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5488 /// limited-precision mode.
5489 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5490                          const TargetLowering &TLI, SDNodeFlags Flags) {
5491   if (Op.getValueType() == MVT::f32 &&
5492       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5493 
5494     // Put the exponent in the right bit position for later addition to the
5495     // final result:
5496     //
5497     // t0 = Op * log2(e)
5498 
5499     // TODO: What fast-math-flags should be set here?
5500     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5501                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5502     return getLimitedPrecisionExp2(t0, dl, DAG);
5503   }
5504 
5505   // No special expansion.
5506   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5507 }
5508 
5509 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5510 /// limited-precision mode.
5511 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5512                          const TargetLowering &TLI, SDNodeFlags Flags) {
5513   // TODO: What fast-math-flags should be set on the floating-point nodes?
5514 
5515   if (Op.getValueType() == MVT::f32 &&
5516       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5517     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5518 
5519     // Scale the exponent by log(2).
5520     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5521     SDValue LogOfExponent =
5522         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5523                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5524 
5525     // Get the significand and build it into a floating-point number with
5526     // exponent of 1.
5527     SDValue X = GetSignificand(DAG, Op1, dl);
5528 
5529     SDValue LogOfMantissa;
5530     if (LimitFloatPrecision <= 6) {
5531       // For floating-point precision of 6:
5532       //
5533       //   LogofMantissa =
5534       //     -1.1609546f +
5535       //       (1.4034025f - 0.23903021f * x) * x;
5536       //
5537       // error 0.0034276066, which is better than 8 bits
5538       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5539                                getF32Constant(DAG, 0xbe74c456, dl));
5540       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5541                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5542       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5543       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5544                                   getF32Constant(DAG, 0x3f949a29, dl));
5545     } else if (LimitFloatPrecision <= 12) {
5546       // For floating-point precision of 12:
5547       //
5548       //   LogOfMantissa =
5549       //     -1.7417939f +
5550       //       (2.8212026f +
5551       //         (-1.4699568f +
5552       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5553       //
5554       // error 0.000061011436, which is 14 bits
5555       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5556                                getF32Constant(DAG, 0xbd67b6d6, dl));
5557       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5558                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5559       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5560       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5561                                getF32Constant(DAG, 0x3fbc278b, dl));
5562       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5563       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5564                                getF32Constant(DAG, 0x40348e95, dl));
5565       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5566       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5567                                   getF32Constant(DAG, 0x3fdef31a, dl));
5568     } else { // LimitFloatPrecision <= 18
5569       // For floating-point precision of 18:
5570       //
5571       //   LogOfMantissa =
5572       //     -2.1072184f +
5573       //       (4.2372794f +
5574       //         (-3.7029485f +
5575       //           (2.2781945f +
5576       //             (-0.87823314f +
5577       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5578       //
5579       // error 0.0000023660568, which is better than 18 bits
5580       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5581                                getF32Constant(DAG, 0xbc91e5ac, dl));
5582       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5583                                getF32Constant(DAG, 0x3e4350aa, dl));
5584       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5585       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5586                                getF32Constant(DAG, 0x3f60d3e3, dl));
5587       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5588       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5589                                getF32Constant(DAG, 0x4011cdf0, dl));
5590       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5591       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5592                                getF32Constant(DAG, 0x406cfd1c, dl));
5593       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5594       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5595                                getF32Constant(DAG, 0x408797cb, dl));
5596       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5597       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5598                                   getF32Constant(DAG, 0x4006dcab, dl));
5599     }
5600 
5601     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5602   }
5603 
5604   // No special expansion.
5605   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5606 }
5607 
5608 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5609 /// limited-precision mode.
5610 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5611                           const TargetLowering &TLI, SDNodeFlags Flags) {
5612   // TODO: What fast-math-flags should be set on the floating-point nodes?
5613 
5614   if (Op.getValueType() == MVT::f32 &&
5615       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5616     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5617 
5618     // Get the exponent.
5619     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5620 
5621     // Get the significand and build it into a floating-point number with
5622     // exponent of 1.
5623     SDValue X = GetSignificand(DAG, Op1, dl);
5624 
5625     // Different possible minimax approximations of significand in
5626     // floating-point for various degrees of accuracy over [1,2].
5627     SDValue Log2ofMantissa;
5628     if (LimitFloatPrecision <= 6) {
5629       // For floating-point precision of 6:
5630       //
5631       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5632       //
5633       // error 0.0049451742, which is more than 7 bits
5634       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5635                                getF32Constant(DAG, 0xbeb08fe0, dl));
5636       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5637                                getF32Constant(DAG, 0x40019463, dl));
5638       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5639       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5640                                    getF32Constant(DAG, 0x3fd6633d, dl));
5641     } else if (LimitFloatPrecision <= 12) {
5642       // For floating-point precision of 12:
5643       //
5644       //   Log2ofMantissa =
5645       //     -2.51285454f +
5646       //       (4.07009056f +
5647       //         (-2.12067489f +
5648       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5649       //
5650       // error 0.0000876136000, which is better than 13 bits
5651       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5652                                getF32Constant(DAG, 0xbda7262e, dl));
5653       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5654                                getF32Constant(DAG, 0x3f25280b, dl));
5655       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5656       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5657                                getF32Constant(DAG, 0x4007b923, dl));
5658       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5659       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5660                                getF32Constant(DAG, 0x40823e2f, dl));
5661       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5662       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5663                                    getF32Constant(DAG, 0x4020d29c, dl));
5664     } else { // LimitFloatPrecision <= 18
5665       // For floating-point precision of 18:
5666       //
5667       //   Log2ofMantissa =
5668       //     -3.0400495f +
5669       //       (6.1129976f +
5670       //         (-5.3420409f +
5671       //           (3.2865683f +
5672       //             (-1.2669343f +
5673       //               (0.27515199f -
5674       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5675       //
5676       // error 0.0000018516, which is better than 18 bits
5677       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5678                                getF32Constant(DAG, 0xbcd2769e, dl));
5679       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5680                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5681       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5682       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5683                                getF32Constant(DAG, 0x3fa22ae7, dl));
5684       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5685       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5686                                getF32Constant(DAG, 0x40525723, dl));
5687       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5688       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5689                                getF32Constant(DAG, 0x40aaf200, dl));
5690       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5691       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5692                                getF32Constant(DAG, 0x40c39dad, dl));
5693       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5694       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5695                                    getF32Constant(DAG, 0x4042902c, dl));
5696     }
5697 
5698     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5699   }
5700 
5701   // No special expansion.
5702   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5703 }
5704 
5705 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5706 /// limited-precision mode.
5707 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5708                            const TargetLowering &TLI, SDNodeFlags Flags) {
5709   // TODO: What fast-math-flags should be set on the floating-point nodes?
5710 
5711   if (Op.getValueType() == MVT::f32 &&
5712       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5713     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5714 
5715     // Scale the exponent by log10(2) [0.30102999f].
5716     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5717     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5718                                         getF32Constant(DAG, 0x3e9a209a, dl));
5719 
5720     // Get the significand and build it into a floating-point number with
5721     // exponent of 1.
5722     SDValue X = GetSignificand(DAG, Op1, dl);
5723 
5724     SDValue Log10ofMantissa;
5725     if (LimitFloatPrecision <= 6) {
5726       // For floating-point precision of 6:
5727       //
5728       //   Log10ofMantissa =
5729       //     -0.50419619f +
5730       //       (0.60948995f - 0.10380950f * x) * x;
5731       //
5732       // error 0.0014886165, which is 6 bits
5733       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5734                                getF32Constant(DAG, 0xbdd49a13, dl));
5735       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5736                                getF32Constant(DAG, 0x3f1c0789, dl));
5737       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5738       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5739                                     getF32Constant(DAG, 0x3f011300, dl));
5740     } else if (LimitFloatPrecision <= 12) {
5741       // For floating-point precision of 12:
5742       //
5743       //   Log10ofMantissa =
5744       //     -0.64831180f +
5745       //       (0.91751397f +
5746       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5747       //
5748       // error 0.00019228036, which is better than 12 bits
5749       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5750                                getF32Constant(DAG, 0x3d431f31, dl));
5751       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5752                                getF32Constant(DAG, 0x3ea21fb2, dl));
5753       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5754       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5755                                getF32Constant(DAG, 0x3f6ae232, dl));
5756       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5757       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5758                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5759     } else { // LimitFloatPrecision <= 18
5760       // For floating-point precision of 18:
5761       //
5762       //   Log10ofMantissa =
5763       //     -0.84299375f +
5764       //       (1.5327582f +
5765       //         (-1.0688956f +
5766       //           (0.49102474f +
5767       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5768       //
5769       // error 0.0000037995730, which is better than 18 bits
5770       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5771                                getF32Constant(DAG, 0x3c5d51ce, dl));
5772       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5773                                getF32Constant(DAG, 0x3e00685a, dl));
5774       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5775       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5776                                getF32Constant(DAG, 0x3efb6798, dl));
5777       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5778       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5779                                getF32Constant(DAG, 0x3f88d192, dl));
5780       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5781       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5782                                getF32Constant(DAG, 0x3fc4316c, dl));
5783       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5784       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5785                                     getF32Constant(DAG, 0x3f57ce70, dl));
5786     }
5787 
5788     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5789   }
5790 
5791   // No special expansion.
5792   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5793 }
5794 
5795 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5796 /// limited-precision mode.
5797 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5798                           const TargetLowering &TLI, SDNodeFlags Flags) {
5799   if (Op.getValueType() == MVT::f32 &&
5800       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5801     return getLimitedPrecisionExp2(Op, dl, DAG);
5802 
5803   // No special expansion.
5804   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5805 }
5806 
5807 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5808 /// limited-precision mode with x == 10.0f.
5809 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5810                          SelectionDAG &DAG, const TargetLowering &TLI,
5811                          SDNodeFlags Flags) {
5812   bool IsExp10 = false;
5813   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5814       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5815     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5816       APFloat Ten(10.0f);
5817       IsExp10 = LHSC->isExactlyValue(Ten);
5818     }
5819   }
5820 
5821   // TODO: What fast-math-flags should be set on the FMUL node?
5822   if (IsExp10) {
5823     // Put the exponent in the right bit position for later addition to the
5824     // final result:
5825     //
5826     //   #define LOG2OF10 3.3219281f
5827     //   t0 = Op * LOG2OF10;
5828     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5829                              getF32Constant(DAG, 0x40549a78, dl));
5830     return getLimitedPrecisionExp2(t0, dl, DAG);
5831   }
5832 
5833   // No special expansion.
5834   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5835 }
5836 
5837 /// ExpandPowI - Expand a llvm.powi intrinsic.
5838 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5839                           SelectionDAG &DAG) {
5840   // If RHS is a constant, we can expand this out to a multiplication tree if
5841   // it's beneficial on the target, otherwise we end up lowering to a call to
5842   // __powidf2 (for example).
5843   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5844     unsigned Val = RHSC->getSExtValue();
5845 
5846     // powi(x, 0) -> 1.0
5847     if (Val == 0)
5848       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5849 
5850     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5851             Val, DAG.shouldOptForSize())) {
5852       // Get the exponent as a positive value.
5853       if ((int)Val < 0)
5854         Val = -Val;
5855       // We use the simple binary decomposition method to generate the multiply
5856       // sequence.  There are more optimal ways to do this (for example,
5857       // powi(x,15) generates one more multiply than it should), but this has
5858       // the benefit of being both really simple and much better than a libcall.
5859       SDValue Res; // Logically starts equal to 1.0
5860       SDValue CurSquare = LHS;
5861       // TODO: Intrinsics should have fast-math-flags that propagate to these
5862       // nodes.
5863       while (Val) {
5864         if (Val & 1) {
5865           if (Res.getNode())
5866             Res =
5867                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5868           else
5869             Res = CurSquare; // 1.0*CurSquare.
5870         }
5871 
5872         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5873                                 CurSquare, CurSquare);
5874         Val >>= 1;
5875       }
5876 
5877       // If the original was negative, invert the result, producing 1/(x*x*x).
5878       if (RHSC->getSExtValue() < 0)
5879         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5880                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5881       return Res;
5882     }
5883   }
5884 
5885   // Otherwise, expand to a libcall.
5886   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5887 }
5888 
5889 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5890                             SDValue LHS, SDValue RHS, SDValue Scale,
5891                             SelectionDAG &DAG, const TargetLowering &TLI) {
5892   EVT VT = LHS.getValueType();
5893   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5894   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5895   LLVMContext &Ctx = *DAG.getContext();
5896 
5897   // If the type is legal but the operation isn't, this node might survive all
5898   // the way to operation legalization. If we end up there and we do not have
5899   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5900   // node.
5901 
5902   // Coax the legalizer into expanding the node during type legalization instead
5903   // by bumping the size by one bit. This will force it to Promote, enabling the
5904   // early expansion and avoiding the need to expand later.
5905 
5906   // We don't have to do this if Scale is 0; that can always be expanded, unless
5907   // it's a saturating signed operation. Those can experience true integer
5908   // division overflow, a case which we must avoid.
5909 
5910   // FIXME: We wouldn't have to do this (or any of the early
5911   // expansion/promotion) if it was possible to expand a libcall of an
5912   // illegal type during operation legalization. But it's not, so things
5913   // get a bit hacky.
5914   unsigned ScaleInt = Scale->getAsZExtVal();
5915   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5916       (TLI.isTypeLegal(VT) ||
5917        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5918     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5919         Opcode, VT, ScaleInt);
5920     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5921       EVT PromVT;
5922       if (VT.isScalarInteger())
5923         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5924       else if (VT.isVector()) {
5925         PromVT = VT.getVectorElementType();
5926         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5927         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5928       } else
5929         llvm_unreachable("Wrong VT for DIVFIX?");
5930       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5931       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5932       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5933       // For saturating operations, we need to shift up the LHS to get the
5934       // proper saturation width, and then shift down again afterwards.
5935       if (Saturating)
5936         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5937                           DAG.getConstant(1, DL, ShiftTy));
5938       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5939       if (Saturating)
5940         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5941                           DAG.getConstant(1, DL, ShiftTy));
5942       return DAG.getZExtOrTrunc(Res, DL, VT);
5943     }
5944   }
5945 
5946   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5947 }
5948 
5949 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5950 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5951 static void
5952 getUnderlyingArgRegs(SmallVectorImpl<std::pair<unsigned, TypeSize>> &Regs,
5953                      const SDValue &N) {
5954   switch (N.getOpcode()) {
5955   case ISD::CopyFromReg: {
5956     SDValue Op = N.getOperand(1);
5957     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5958                       Op.getValueType().getSizeInBits());
5959     return;
5960   }
5961   case ISD::BITCAST:
5962   case ISD::AssertZext:
5963   case ISD::AssertSext:
5964   case ISD::TRUNCATE:
5965     getUnderlyingArgRegs(Regs, N.getOperand(0));
5966     return;
5967   case ISD::BUILD_PAIR:
5968   case ISD::BUILD_VECTOR:
5969   case ISD::CONCAT_VECTORS:
5970     for (SDValue Op : N->op_values())
5971       getUnderlyingArgRegs(Regs, Op);
5972     return;
5973   default:
5974     return;
5975   }
5976 }
5977 
5978 /// If the DbgValueInst is a dbg_value of a function argument, create the
5979 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
5980 /// instruction selection, they will be inserted to the entry BB.
5981 /// We don't currently support this for variadic dbg_values, as they shouldn't
5982 /// appear for function arguments or in the prologue.
5983 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
5984     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
5985     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
5986   const Argument *Arg = dyn_cast<Argument>(V);
5987   if (!Arg)
5988     return false;
5989 
5990   MachineFunction &MF = DAG.getMachineFunction();
5991   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
5992 
5993   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
5994   // we've been asked to pursue.
5995   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
5996                               bool Indirect) {
5997     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
5998       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
5999       // pointing at the VReg, which will be patched up later.
6000       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6001       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6002           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6003           /* isKill */ false, /* isDead */ false,
6004           /* isUndef */ false, /* isEarlyClobber */ false,
6005           /* SubReg */ 0, /* isDebug */ true)});
6006 
6007       auto *NewDIExpr = FragExpr;
6008       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6009       // the DIExpression.
6010       if (Indirect)
6011         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6012       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6013       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6014       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6015     } else {
6016       // Create a completely standard DBG_VALUE.
6017       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6018       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6019     }
6020   };
6021 
6022   if (Kind == FuncArgumentDbgValueKind::Value) {
6023     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6024     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6025     // the entry block.
6026     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6027     if (!IsInEntryBlock)
6028       return false;
6029 
6030     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6031     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6032     // variable that also is a param.
6033     //
6034     // Although, if we are at the top of the entry block already, we can still
6035     // emit using ArgDbgValue. This might catch some situations when the
6036     // dbg.value refers to an argument that isn't used in the entry block, so
6037     // any CopyToReg node would be optimized out and the only way to express
6038     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6039     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6040     // we should only emit as ArgDbgValue if the Variable is an argument to the
6041     // current function, and the dbg.value intrinsic is found in the entry
6042     // block.
6043     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6044         !DL->getInlinedAt();
6045     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6046     if (!IsInPrologue && !VariableIsFunctionInputArg)
6047       return false;
6048 
6049     // Here we assume that a function argument on IR level only can be used to
6050     // describe one input parameter on source level. If we for example have
6051     // source code like this
6052     //
6053     //    struct A { long x, y; };
6054     //    void foo(struct A a, long b) {
6055     //      ...
6056     //      b = a.x;
6057     //      ...
6058     //    }
6059     //
6060     // and IR like this
6061     //
6062     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6063     //  entry:
6064     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6065     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6066     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6067     //    ...
6068     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6069     //    ...
6070     //
6071     // then the last dbg.value is describing a parameter "b" using a value that
6072     // is an argument. But since we already has used %a1 to describe a parameter
6073     // we should not handle that last dbg.value here (that would result in an
6074     // incorrect hoisting of the DBG_VALUE to the function entry).
6075     // Notice that we allow one dbg.value per IR level argument, to accommodate
6076     // for the situation with fragments above.
6077     // If there is no node for the value being handled, we return true to skip
6078     // the normal generation of debug info, as it would kill existing debug
6079     // info for the parameter in case of duplicates.
6080     if (VariableIsFunctionInputArg) {
6081       unsigned ArgNo = Arg->getArgNo();
6082       if (ArgNo >= FuncInfo.DescribedArgs.size())
6083         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6084       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6085         return !NodeMap[V].getNode();
6086       FuncInfo.DescribedArgs.set(ArgNo);
6087     }
6088   }
6089 
6090   bool IsIndirect = false;
6091   std::optional<MachineOperand> Op;
6092   // Some arguments' frame index is recorded during argument lowering.
6093   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6094   if (FI != std::numeric_limits<int>::max())
6095     Op = MachineOperand::CreateFI(FI);
6096 
6097   SmallVector<std::pair<unsigned, TypeSize>, 8> ArgRegsAndSizes;
6098   if (!Op && N.getNode()) {
6099     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6100     Register Reg;
6101     if (ArgRegsAndSizes.size() == 1)
6102       Reg = ArgRegsAndSizes.front().first;
6103 
6104     if (Reg && Reg.isVirtual()) {
6105       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6106       Register PR = RegInfo.getLiveInPhysReg(Reg);
6107       if (PR)
6108         Reg = PR;
6109     }
6110     if (Reg) {
6111       Op = MachineOperand::CreateReg(Reg, false);
6112       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6113     }
6114   }
6115 
6116   if (!Op && N.getNode()) {
6117     // Check if frame index is available.
6118     SDValue LCandidate = peekThroughBitcasts(N);
6119     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6120       if (FrameIndexSDNode *FINode =
6121           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6122         Op = MachineOperand::CreateFI(FINode->getIndex());
6123   }
6124 
6125   if (!Op) {
6126     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6127     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<unsigned, TypeSize>>
6128                                          SplitRegs) {
6129       unsigned Offset = 0;
6130       for (const auto &RegAndSize : SplitRegs) {
6131         // If the expression is already a fragment, the current register
6132         // offset+size might extend beyond the fragment. In this case, only
6133         // the register bits that are inside the fragment are relevant.
6134         int RegFragmentSizeInBits = RegAndSize.second;
6135         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6136           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6137           // The register is entirely outside the expression fragment,
6138           // so is irrelevant for debug info.
6139           if (Offset >= ExprFragmentSizeInBits)
6140             break;
6141           // The register is partially outside the expression fragment, only
6142           // the low bits within the fragment are relevant for debug info.
6143           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6144             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6145           }
6146         }
6147 
6148         auto FragmentExpr = DIExpression::createFragmentExpression(
6149             Expr, Offset, RegFragmentSizeInBits);
6150         Offset += RegAndSize.second;
6151         // If a valid fragment expression cannot be created, the variable's
6152         // correct value cannot be determined and so it is set as Undef.
6153         if (!FragmentExpr) {
6154           SDDbgValue *SDV = DAG.getConstantDbgValue(
6155               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6156           DAG.AddDbgValue(SDV, false);
6157           continue;
6158         }
6159         MachineInstr *NewMI =
6160             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6161                              Kind != FuncArgumentDbgValueKind::Value);
6162         FuncInfo.ArgDbgValues.push_back(NewMI);
6163       }
6164     };
6165 
6166     // Check if ValueMap has reg number.
6167     DenseMap<const Value *, Register>::const_iterator
6168       VMI = FuncInfo.ValueMap.find(V);
6169     if (VMI != FuncInfo.ValueMap.end()) {
6170       const auto &TLI = DAG.getTargetLoweringInfo();
6171       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6172                        V->getType(), std::nullopt);
6173       if (RFV.occupiesMultipleRegs()) {
6174         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6175         return true;
6176       }
6177 
6178       Op = MachineOperand::CreateReg(VMI->second, false);
6179       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6180     } else if (ArgRegsAndSizes.size() > 1) {
6181       // This was split due to the calling convention, and no virtual register
6182       // mapping exists for the value.
6183       splitMultiRegDbgValue(ArgRegsAndSizes);
6184       return true;
6185     }
6186   }
6187 
6188   if (!Op)
6189     return false;
6190 
6191   assert(Variable->isValidLocationForIntrinsic(DL) &&
6192          "Expected inlined-at fields to agree");
6193   MachineInstr *NewMI = nullptr;
6194 
6195   if (Op->isReg())
6196     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6197   else
6198     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6199                     Variable, Expr);
6200 
6201   // Otherwise, use ArgDbgValues.
6202   FuncInfo.ArgDbgValues.push_back(NewMI);
6203   return true;
6204 }
6205 
6206 /// Return the appropriate SDDbgValue based on N.
6207 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6208                                              DILocalVariable *Variable,
6209                                              DIExpression *Expr,
6210                                              const DebugLoc &dl,
6211                                              unsigned DbgSDNodeOrder) {
6212   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6213     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6214     // stack slot locations.
6215     //
6216     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6217     // debug values here after optimization:
6218     //
6219     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6220     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6221     //
6222     // Both describe the direct values of their associated variables.
6223     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6224                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6225   }
6226   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6227                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6228 }
6229 
6230 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6231   switch (Intrinsic) {
6232   case Intrinsic::smul_fix:
6233     return ISD::SMULFIX;
6234   case Intrinsic::umul_fix:
6235     return ISD::UMULFIX;
6236   case Intrinsic::smul_fix_sat:
6237     return ISD::SMULFIXSAT;
6238   case Intrinsic::umul_fix_sat:
6239     return ISD::UMULFIXSAT;
6240   case Intrinsic::sdiv_fix:
6241     return ISD::SDIVFIX;
6242   case Intrinsic::udiv_fix:
6243     return ISD::UDIVFIX;
6244   case Intrinsic::sdiv_fix_sat:
6245     return ISD::SDIVFIXSAT;
6246   case Intrinsic::udiv_fix_sat:
6247     return ISD::UDIVFIXSAT;
6248   default:
6249     llvm_unreachable("Unhandled fixed point intrinsic");
6250   }
6251 }
6252 
6253 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6254                                            const char *FunctionName) {
6255   assert(FunctionName && "FunctionName must not be nullptr");
6256   SDValue Callee = DAG.getExternalSymbol(
6257       FunctionName,
6258       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6259   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6260 }
6261 
6262 /// Given a @llvm.call.preallocated.setup, return the corresponding
6263 /// preallocated call.
6264 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6265   assert(cast<CallBase>(PreallocatedSetup)
6266                  ->getCalledFunction()
6267                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6268          "expected call_preallocated_setup Value");
6269   for (const auto *U : PreallocatedSetup->users()) {
6270     auto *UseCall = cast<CallBase>(U);
6271     const Function *Fn = UseCall->getCalledFunction();
6272     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6273       return UseCall;
6274     }
6275   }
6276   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6277 }
6278 
6279 /// If DI is a debug value with an EntryValue expression, lower it using the
6280 /// corresponding physical register of the associated Argument value
6281 /// (guaranteed to exist by the verifier).
6282 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6283     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6284     DIExpression *Expr, DebugLoc DbgLoc) {
6285   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6286     return false;
6287 
6288   // These properties are guaranteed by the verifier.
6289   const Argument *Arg = cast<Argument>(Values[0]);
6290   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6291 
6292   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6293   if (ArgIt == FuncInfo.ValueMap.end()) {
6294     LLVM_DEBUG(
6295         dbgs() << "Dropping dbg.value: expression is entry_value but "
6296                   "couldn't find an associated register for the Argument\n");
6297     return true;
6298   }
6299   Register ArgVReg = ArgIt->getSecond();
6300 
6301   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6302     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6303       SDDbgValue *SDV = DAG.getVRegDbgValue(
6304           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6305       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6306       return true;
6307     }
6308   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6309                        "couldn't find a physical register\n");
6310   return true;
6311 }
6312 
6313 /// Lower the call to the specified intrinsic function.
6314 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6315                                                   unsigned Intrinsic) {
6316   SDLoc sdl = getCurSDLoc();
6317   switch (Intrinsic) {
6318   case Intrinsic::experimental_convergence_anchor:
6319     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6320     break;
6321   case Intrinsic::experimental_convergence_entry:
6322     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6323     break;
6324   case Intrinsic::experimental_convergence_loop: {
6325     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6326     auto *Token = Bundle->Inputs[0].get();
6327     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6328                              getValue(Token)));
6329     break;
6330   }
6331   }
6332 }
6333 
6334 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6335                                                unsigned IntrinsicID) {
6336   // For now, we're only lowering an 'add' histogram.
6337   // We can add others later, e.g. saturating adds, min/max.
6338   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6339          "Tried to lower unsupported histogram type");
6340   SDLoc sdl = getCurSDLoc();
6341   Value *Ptr = I.getOperand(0);
6342   SDValue Inc = getValue(I.getOperand(1));
6343   SDValue Mask = getValue(I.getOperand(2));
6344 
6345   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6346   DataLayout TargetDL = DAG.getDataLayout();
6347   EVT VT = Inc.getValueType();
6348   Align Alignment = DAG.getEVTAlign(VT);
6349 
6350   const MDNode *Ranges = getRangeMetadata(I);
6351 
6352   SDValue Root = DAG.getRoot();
6353   SDValue Base;
6354   SDValue Index;
6355   ISD::MemIndexType IndexType;
6356   SDValue Scale;
6357   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6358                                     I.getParent(), VT.getScalarStoreSize());
6359 
6360   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6361 
6362   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6363       MachinePointerInfo(AS),
6364       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6365       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6366 
6367   if (!UniformBase) {
6368     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6369     Index = getValue(Ptr);
6370     IndexType = ISD::SIGNED_SCALED;
6371     Scale =
6372         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6373   }
6374 
6375   EVT IdxVT = Index.getValueType();
6376   EVT EltTy = IdxVT.getVectorElementType();
6377   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6378     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6379     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6380   }
6381 
6382   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6383 
6384   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6385   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6386                                              Ops, MMO, IndexType);
6387 
6388   setValue(&I, Histogram);
6389   DAG.setRoot(Histogram);
6390 }
6391 
6392 /// Lower the call to the specified intrinsic function.
6393 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6394                                              unsigned Intrinsic) {
6395   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6396   SDLoc sdl = getCurSDLoc();
6397   DebugLoc dl = getCurDebugLoc();
6398   SDValue Res;
6399 
6400   SDNodeFlags Flags;
6401   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6402     Flags.copyFMF(*FPOp);
6403 
6404   switch (Intrinsic) {
6405   default:
6406     // By default, turn this into a target intrinsic node.
6407     visitTargetIntrinsic(I, Intrinsic);
6408     return;
6409   case Intrinsic::vscale: {
6410     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6411     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6412     return;
6413   }
6414   case Intrinsic::vastart:  visitVAStart(I); return;
6415   case Intrinsic::vaend:    visitVAEnd(I); return;
6416   case Intrinsic::vacopy:   visitVACopy(I); return;
6417   case Intrinsic::returnaddress:
6418     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6419                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6420                              getValue(I.getArgOperand(0))));
6421     return;
6422   case Intrinsic::addressofreturnaddress:
6423     setValue(&I,
6424              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6425                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6426     return;
6427   case Intrinsic::sponentry:
6428     setValue(&I,
6429              DAG.getNode(ISD::SPONENTRY, sdl,
6430                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6431     return;
6432   case Intrinsic::frameaddress:
6433     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6434                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6435                              getValue(I.getArgOperand(0))));
6436     return;
6437   case Intrinsic::read_volatile_register:
6438   case Intrinsic::read_register: {
6439     Value *Reg = I.getArgOperand(0);
6440     SDValue Chain = getRoot();
6441     SDValue RegName =
6442         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6443     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6444     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6445       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6446     setValue(&I, Res);
6447     DAG.setRoot(Res.getValue(1));
6448     return;
6449   }
6450   case Intrinsic::write_register: {
6451     Value *Reg = I.getArgOperand(0);
6452     Value *RegValue = I.getArgOperand(1);
6453     SDValue Chain = getRoot();
6454     SDValue RegName =
6455         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6456     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6457                             RegName, getValue(RegValue)));
6458     return;
6459   }
6460   case Intrinsic::memcpy: {
6461     const auto &MCI = cast<MemCpyInst>(I);
6462     SDValue Op1 = getValue(I.getArgOperand(0));
6463     SDValue Op2 = getValue(I.getArgOperand(1));
6464     SDValue Op3 = getValue(I.getArgOperand(2));
6465     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6466     Align DstAlign = MCI.getDestAlign().valueOrOne();
6467     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6468     Align Alignment = std::min(DstAlign, SrcAlign);
6469     bool isVol = MCI.isVolatile();
6470     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6471     // node.
6472     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6473     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6474                                /* AlwaysInline */ false, &I, std::nullopt,
6475                                MachinePointerInfo(I.getArgOperand(0)),
6476                                MachinePointerInfo(I.getArgOperand(1)),
6477                                I.getAAMetadata(), AA);
6478     updateDAGForMaybeTailCall(MC);
6479     return;
6480   }
6481   case Intrinsic::memcpy_inline: {
6482     const auto &MCI = cast<MemCpyInlineInst>(I);
6483     SDValue Dst = getValue(I.getArgOperand(0));
6484     SDValue Src = getValue(I.getArgOperand(1));
6485     SDValue Size = getValue(I.getArgOperand(2));
6486     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6487     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6488     Align DstAlign = MCI.getDestAlign().valueOrOne();
6489     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6490     Align Alignment = std::min(DstAlign, SrcAlign);
6491     bool isVol = MCI.isVolatile();
6492     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6493     // node.
6494     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6495                                /* AlwaysInline */ true, &I, std::nullopt,
6496                                MachinePointerInfo(I.getArgOperand(0)),
6497                                MachinePointerInfo(I.getArgOperand(1)),
6498                                I.getAAMetadata(), AA);
6499     updateDAGForMaybeTailCall(MC);
6500     return;
6501   }
6502   case Intrinsic::memset: {
6503     const auto &MSI = cast<MemSetInst>(I);
6504     SDValue Op1 = getValue(I.getArgOperand(0));
6505     SDValue Op2 = getValue(I.getArgOperand(1));
6506     SDValue Op3 = getValue(I.getArgOperand(2));
6507     // @llvm.memset defines 0 and 1 to both mean no alignment.
6508     Align Alignment = MSI.getDestAlign().valueOrOne();
6509     bool isVol = MSI.isVolatile();
6510     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6511     SDValue MS = DAG.getMemset(
6512         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6513         &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6514     updateDAGForMaybeTailCall(MS);
6515     return;
6516   }
6517   case Intrinsic::memset_inline: {
6518     const auto &MSII = cast<MemSetInlineInst>(I);
6519     SDValue Dst = getValue(I.getArgOperand(0));
6520     SDValue Value = getValue(I.getArgOperand(1));
6521     SDValue Size = getValue(I.getArgOperand(2));
6522     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6523     // @llvm.memset defines 0 and 1 to both mean no alignment.
6524     Align DstAlign = MSII.getDestAlign().valueOrOne();
6525     bool isVol = MSII.isVolatile();
6526     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6527     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6528                                /* AlwaysInline */ true, &I,
6529                                MachinePointerInfo(I.getArgOperand(0)),
6530                                I.getAAMetadata());
6531     updateDAGForMaybeTailCall(MC);
6532     return;
6533   }
6534   case Intrinsic::memmove: {
6535     const auto &MMI = cast<MemMoveInst>(I);
6536     SDValue Op1 = getValue(I.getArgOperand(0));
6537     SDValue Op2 = getValue(I.getArgOperand(1));
6538     SDValue Op3 = getValue(I.getArgOperand(2));
6539     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6540     Align DstAlign = MMI.getDestAlign().valueOrOne();
6541     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6542     Align Alignment = std::min(DstAlign, SrcAlign);
6543     bool isVol = MMI.isVolatile();
6544     // FIXME: Support passing different dest/src alignments to the memmove DAG
6545     // node.
6546     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6547     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I,
6548                                 /* OverrideTailCall */ std::nullopt,
6549                                 MachinePointerInfo(I.getArgOperand(0)),
6550                                 MachinePointerInfo(I.getArgOperand(1)),
6551                                 I.getAAMetadata(), AA);
6552     updateDAGForMaybeTailCall(MM);
6553     return;
6554   }
6555   case Intrinsic::memcpy_element_unordered_atomic: {
6556     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6557     SDValue Dst = getValue(MI.getRawDest());
6558     SDValue Src = getValue(MI.getRawSource());
6559     SDValue Length = getValue(MI.getLength());
6560 
6561     Type *LengthTy = MI.getLength()->getType();
6562     unsigned ElemSz = MI.getElementSizeInBytes();
6563     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6564     SDValue MC =
6565         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6566                             isTC, MachinePointerInfo(MI.getRawDest()),
6567                             MachinePointerInfo(MI.getRawSource()));
6568     updateDAGForMaybeTailCall(MC);
6569     return;
6570   }
6571   case Intrinsic::memmove_element_unordered_atomic: {
6572     auto &MI = cast<AtomicMemMoveInst>(I);
6573     SDValue Dst = getValue(MI.getRawDest());
6574     SDValue Src = getValue(MI.getRawSource());
6575     SDValue Length = getValue(MI.getLength());
6576 
6577     Type *LengthTy = MI.getLength()->getType();
6578     unsigned ElemSz = MI.getElementSizeInBytes();
6579     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6580     SDValue MC =
6581         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6582                              isTC, MachinePointerInfo(MI.getRawDest()),
6583                              MachinePointerInfo(MI.getRawSource()));
6584     updateDAGForMaybeTailCall(MC);
6585     return;
6586   }
6587   case Intrinsic::memset_element_unordered_atomic: {
6588     auto &MI = cast<AtomicMemSetInst>(I);
6589     SDValue Dst = getValue(MI.getRawDest());
6590     SDValue Val = getValue(MI.getValue());
6591     SDValue Length = getValue(MI.getLength());
6592 
6593     Type *LengthTy = MI.getLength()->getType();
6594     unsigned ElemSz = MI.getElementSizeInBytes();
6595     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6596     SDValue MC =
6597         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6598                             isTC, MachinePointerInfo(MI.getRawDest()));
6599     updateDAGForMaybeTailCall(MC);
6600     return;
6601   }
6602   case Intrinsic::call_preallocated_setup: {
6603     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6604     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6605     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6606                               getRoot(), SrcValue);
6607     setValue(&I, Res);
6608     DAG.setRoot(Res);
6609     return;
6610   }
6611   case Intrinsic::call_preallocated_arg: {
6612     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6613     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6614     SDValue Ops[3];
6615     Ops[0] = getRoot();
6616     Ops[1] = SrcValue;
6617     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6618                                    MVT::i32); // arg index
6619     SDValue Res = DAG.getNode(
6620         ISD::PREALLOCATED_ARG, sdl,
6621         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6622     setValue(&I, Res);
6623     DAG.setRoot(Res.getValue(1));
6624     return;
6625   }
6626   case Intrinsic::dbg_declare: {
6627     const auto &DI = cast<DbgDeclareInst>(I);
6628     // Debug intrinsics are handled separately in assignment tracking mode.
6629     // Some intrinsics are handled right after Argument lowering.
6630     if (AssignmentTrackingEnabled ||
6631         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6632       return;
6633     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6634     DILocalVariable *Variable = DI.getVariable();
6635     DIExpression *Expression = DI.getExpression();
6636     dropDanglingDebugInfo(Variable, Expression);
6637     // Assume dbg.declare can not currently use DIArgList, i.e.
6638     // it is non-variadic.
6639     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6640     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6641                        DI.getDebugLoc());
6642     return;
6643   }
6644   case Intrinsic::dbg_label: {
6645     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6646     DILabel *Label = DI.getLabel();
6647     assert(Label && "Missing label");
6648 
6649     SDDbgLabel *SDV;
6650     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6651     DAG.AddDbgLabel(SDV);
6652     return;
6653   }
6654   case Intrinsic::dbg_assign: {
6655     // Debug intrinsics are handled separately in assignment tracking mode.
6656     if (AssignmentTrackingEnabled)
6657       return;
6658     // If assignment tracking hasn't been enabled then fall through and treat
6659     // the dbg.assign as a dbg.value.
6660     [[fallthrough]];
6661   }
6662   case Intrinsic::dbg_value: {
6663     // Debug intrinsics are handled separately in assignment tracking mode.
6664     if (AssignmentTrackingEnabled)
6665       return;
6666     const DbgValueInst &DI = cast<DbgValueInst>(I);
6667     assert(DI.getVariable() && "Missing variable");
6668 
6669     DILocalVariable *Variable = DI.getVariable();
6670     DIExpression *Expression = DI.getExpression();
6671     dropDanglingDebugInfo(Variable, Expression);
6672 
6673     if (DI.isKillLocation()) {
6674       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6675       return;
6676     }
6677 
6678     SmallVector<Value *, 4> Values(DI.getValues());
6679     if (Values.empty())
6680       return;
6681 
6682     bool IsVariadic = DI.hasArgList();
6683     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6684                           SDNodeOrder, IsVariadic))
6685       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6686                            DI.getDebugLoc(), SDNodeOrder);
6687     return;
6688   }
6689 
6690   case Intrinsic::eh_typeid_for: {
6691     // Find the type id for the given typeinfo.
6692     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6693     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6694     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6695     setValue(&I, Res);
6696     return;
6697   }
6698 
6699   case Intrinsic::eh_return_i32:
6700   case Intrinsic::eh_return_i64:
6701     DAG.getMachineFunction().setCallsEHReturn(true);
6702     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6703                             MVT::Other,
6704                             getControlRoot(),
6705                             getValue(I.getArgOperand(0)),
6706                             getValue(I.getArgOperand(1))));
6707     return;
6708   case Intrinsic::eh_unwind_init:
6709     DAG.getMachineFunction().setCallsUnwindInit(true);
6710     return;
6711   case Intrinsic::eh_dwarf_cfa:
6712     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6713                              TLI.getPointerTy(DAG.getDataLayout()),
6714                              getValue(I.getArgOperand(0))));
6715     return;
6716   case Intrinsic::eh_sjlj_callsite: {
6717     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6718     assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6719 
6720     FuncInfo.setCurrentCallSite(CI->getZExtValue());
6721     return;
6722   }
6723   case Intrinsic::eh_sjlj_functioncontext: {
6724     // Get and store the index of the function context.
6725     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6726     AllocaInst *FnCtx =
6727       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6728     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6729     MFI.setFunctionContextIndex(FI);
6730     return;
6731   }
6732   case Intrinsic::eh_sjlj_setjmp: {
6733     SDValue Ops[2];
6734     Ops[0] = getRoot();
6735     Ops[1] = getValue(I.getArgOperand(0));
6736     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6737                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6738     setValue(&I, Op.getValue(0));
6739     DAG.setRoot(Op.getValue(1));
6740     return;
6741   }
6742   case Intrinsic::eh_sjlj_longjmp:
6743     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6744                             getRoot(), getValue(I.getArgOperand(0))));
6745     return;
6746   case Intrinsic::eh_sjlj_setup_dispatch:
6747     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6748                             getRoot()));
6749     return;
6750   case Intrinsic::masked_gather:
6751     visitMaskedGather(I);
6752     return;
6753   case Intrinsic::masked_load:
6754     visitMaskedLoad(I);
6755     return;
6756   case Intrinsic::masked_scatter:
6757     visitMaskedScatter(I);
6758     return;
6759   case Intrinsic::masked_store:
6760     visitMaskedStore(I);
6761     return;
6762   case Intrinsic::masked_expandload:
6763     visitMaskedLoad(I, true /* IsExpanding */);
6764     return;
6765   case Intrinsic::masked_compressstore:
6766     visitMaskedStore(I, true /* IsCompressing */);
6767     return;
6768   case Intrinsic::powi:
6769     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6770                             getValue(I.getArgOperand(1)), DAG));
6771     return;
6772   case Intrinsic::log:
6773     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6774     return;
6775   case Intrinsic::log2:
6776     setValue(&I,
6777              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6778     return;
6779   case Intrinsic::log10:
6780     setValue(&I,
6781              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6782     return;
6783   case Intrinsic::exp:
6784     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6785     return;
6786   case Intrinsic::exp2:
6787     setValue(&I,
6788              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6789     return;
6790   case Intrinsic::pow:
6791     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6792                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6793     return;
6794   case Intrinsic::sqrt:
6795   case Intrinsic::fabs:
6796   case Intrinsic::sin:
6797   case Intrinsic::cos:
6798   case Intrinsic::tan:
6799   case Intrinsic::asin:
6800   case Intrinsic::acos:
6801   case Intrinsic::atan:
6802   case Intrinsic::sinh:
6803   case Intrinsic::cosh:
6804   case Intrinsic::tanh:
6805   case Intrinsic::exp10:
6806   case Intrinsic::floor:
6807   case Intrinsic::ceil:
6808   case Intrinsic::trunc:
6809   case Intrinsic::rint:
6810   case Intrinsic::nearbyint:
6811   case Intrinsic::round:
6812   case Intrinsic::roundeven:
6813   case Intrinsic::canonicalize: {
6814     unsigned Opcode;
6815     // clang-format off
6816     switch (Intrinsic) {
6817     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6818     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6819     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6820     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6821     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6822     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6823     case Intrinsic::asin:         Opcode = ISD::FASIN;         break;
6824     case Intrinsic::acos:         Opcode = ISD::FACOS;         break;
6825     case Intrinsic::atan:         Opcode = ISD::FATAN;         break;
6826     case Intrinsic::sinh:         Opcode = ISD::FSINH;         break;
6827     case Intrinsic::cosh:         Opcode = ISD::FCOSH;         break;
6828     case Intrinsic::tanh:         Opcode = ISD::FTANH;         break;
6829     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6830     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6831     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6832     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6833     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6834     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6835     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6836     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6837     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6838     }
6839     // clang-format on
6840 
6841     setValue(&I, DAG.getNode(Opcode, sdl,
6842                              getValue(I.getArgOperand(0)).getValueType(),
6843                              getValue(I.getArgOperand(0)), Flags));
6844     return;
6845   }
6846   case Intrinsic::lround:
6847   case Intrinsic::llround:
6848   case Intrinsic::lrint:
6849   case Intrinsic::llrint: {
6850     unsigned Opcode;
6851     // clang-format off
6852     switch (Intrinsic) {
6853     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6854     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6855     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6856     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6857     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6858     }
6859     // clang-format on
6860 
6861     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6862     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6863                              getValue(I.getArgOperand(0))));
6864     return;
6865   }
6866   case Intrinsic::minnum:
6867     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6868                              getValue(I.getArgOperand(0)).getValueType(),
6869                              getValue(I.getArgOperand(0)),
6870                              getValue(I.getArgOperand(1)), Flags));
6871     return;
6872   case Intrinsic::maxnum:
6873     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6874                              getValue(I.getArgOperand(0)).getValueType(),
6875                              getValue(I.getArgOperand(0)),
6876                              getValue(I.getArgOperand(1)), Flags));
6877     return;
6878   case Intrinsic::minimum:
6879     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6880                              getValue(I.getArgOperand(0)).getValueType(),
6881                              getValue(I.getArgOperand(0)),
6882                              getValue(I.getArgOperand(1)), Flags));
6883     return;
6884   case Intrinsic::maximum:
6885     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6886                              getValue(I.getArgOperand(0)).getValueType(),
6887                              getValue(I.getArgOperand(0)),
6888                              getValue(I.getArgOperand(1)), Flags));
6889     return;
6890   case Intrinsic::minimumnum:
6891     setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
6892                              getValue(I.getArgOperand(0)).getValueType(),
6893                              getValue(I.getArgOperand(0)),
6894                              getValue(I.getArgOperand(1)), Flags));
6895     return;
6896   case Intrinsic::maximumnum:
6897     setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
6898                              getValue(I.getArgOperand(0)).getValueType(),
6899                              getValue(I.getArgOperand(0)),
6900                              getValue(I.getArgOperand(1)), Flags));
6901     return;
6902   case Intrinsic::copysign:
6903     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6904                              getValue(I.getArgOperand(0)).getValueType(),
6905                              getValue(I.getArgOperand(0)),
6906                              getValue(I.getArgOperand(1)), Flags));
6907     return;
6908   case Intrinsic::ldexp:
6909     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6910                              getValue(I.getArgOperand(0)).getValueType(),
6911                              getValue(I.getArgOperand(0)),
6912                              getValue(I.getArgOperand(1)), Flags));
6913     return;
6914   case Intrinsic::frexp: {
6915     SmallVector<EVT, 2> ValueVTs;
6916     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6917     SDVTList VTs = DAG.getVTList(ValueVTs);
6918     setValue(&I,
6919              DAG.getNode(ISD::FFREXP, sdl, VTs, getValue(I.getArgOperand(0))));
6920     return;
6921   }
6922   case Intrinsic::arithmetic_fence: {
6923     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
6924                              getValue(I.getArgOperand(0)).getValueType(),
6925                              getValue(I.getArgOperand(0)), Flags));
6926     return;
6927   }
6928   case Intrinsic::fma:
6929     setValue(&I, DAG.getNode(
6930                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
6931                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
6932                      getValue(I.getArgOperand(2)), Flags));
6933     return;
6934 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
6935   case Intrinsic::INTRINSIC:
6936 #include "llvm/IR/ConstrainedOps.def"
6937     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
6938     return;
6939 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
6940 #include "llvm/IR/VPIntrinsics.def"
6941     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
6942     return;
6943   case Intrinsic::fptrunc_round: {
6944     // Get the last argument, the metadata and convert it to an integer in the
6945     // call
6946     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
6947     std::optional<RoundingMode> RoundMode =
6948         convertStrToRoundingMode(cast<MDString>(MD)->getString());
6949 
6950     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6951 
6952     // Propagate fast-math-flags from IR to node(s).
6953     SDNodeFlags Flags;
6954     Flags.copyFMF(*cast<FPMathOperator>(&I));
6955     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
6956 
6957     SDValue Result;
6958     Result = DAG.getNode(
6959         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
6960         DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
6961     setValue(&I, Result);
6962 
6963     return;
6964   }
6965   case Intrinsic::fmuladd: {
6966     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6967     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
6968         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
6969       setValue(&I, DAG.getNode(ISD::FMA, sdl,
6970                                getValue(I.getArgOperand(0)).getValueType(),
6971                                getValue(I.getArgOperand(0)),
6972                                getValue(I.getArgOperand(1)),
6973                                getValue(I.getArgOperand(2)), Flags));
6974     } else {
6975       // TODO: Intrinsic calls should have fast-math-flags.
6976       SDValue Mul = DAG.getNode(
6977           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
6978           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
6979       SDValue Add = DAG.getNode(ISD::FADD, sdl,
6980                                 getValue(I.getArgOperand(0)).getValueType(),
6981                                 Mul, getValue(I.getArgOperand(2)), Flags);
6982       setValue(&I, Add);
6983     }
6984     return;
6985   }
6986   case Intrinsic::convert_to_fp16:
6987     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
6988                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
6989                                          getValue(I.getArgOperand(0)),
6990                                          DAG.getTargetConstant(0, sdl,
6991                                                                MVT::i32))));
6992     return;
6993   case Intrinsic::convert_from_fp16:
6994     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
6995                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6996                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
6997                                          getValue(I.getArgOperand(0)))));
6998     return;
6999   case Intrinsic::fptosi_sat: {
7000     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7001     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7002                              getValue(I.getArgOperand(0)),
7003                              DAG.getValueType(VT.getScalarType())));
7004     return;
7005   }
7006   case Intrinsic::fptoui_sat: {
7007     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7008     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7009                              getValue(I.getArgOperand(0)),
7010                              DAG.getValueType(VT.getScalarType())));
7011     return;
7012   }
7013   case Intrinsic::set_rounding:
7014     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7015                       {getRoot(), getValue(I.getArgOperand(0))});
7016     setValue(&I, Res);
7017     DAG.setRoot(Res.getValue(0));
7018     return;
7019   case Intrinsic::is_fpclass: {
7020     const DataLayout DLayout = DAG.getDataLayout();
7021     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7022     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7023     FPClassTest Test = static_cast<FPClassTest>(
7024         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7025     MachineFunction &MF = DAG.getMachineFunction();
7026     const Function &F = MF.getFunction();
7027     SDValue Op = getValue(I.getArgOperand(0));
7028     SDNodeFlags Flags;
7029     Flags.setNoFPExcept(
7030         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7031     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7032     // expansion can use illegal types. Making expansion early allows
7033     // legalizing these types prior to selection.
7034     if (!TLI.isOperationLegalOrCustom(ISD::IS_FPCLASS, ArgVT)) {
7035       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7036       setValue(&I, Result);
7037       return;
7038     }
7039 
7040     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7041     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7042     setValue(&I, V);
7043     return;
7044   }
7045   case Intrinsic::get_fpenv: {
7046     const DataLayout DLayout = DAG.getDataLayout();
7047     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7048     Align TempAlign = DAG.getEVTAlign(EnvVT);
7049     SDValue Chain = getRoot();
7050     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7051     // and temporary storage in stack.
7052     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7053       Res = DAG.getNode(
7054           ISD::GET_FPENV, sdl,
7055           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7056                         MVT::Other),
7057           Chain);
7058     } else {
7059       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7060       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7061       auto MPI =
7062           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7063       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7064           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7065           TempAlign);
7066       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7067       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7068     }
7069     setValue(&I, Res);
7070     DAG.setRoot(Res.getValue(1));
7071     return;
7072   }
7073   case Intrinsic::set_fpenv: {
7074     const DataLayout DLayout = DAG.getDataLayout();
7075     SDValue Env = getValue(I.getArgOperand(0));
7076     EVT EnvVT = Env.getValueType();
7077     Align TempAlign = DAG.getEVTAlign(EnvVT);
7078     SDValue Chain = getRoot();
7079     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7080     // environment from memory.
7081     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7082       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7083     } else {
7084       // Allocate space in stack, copy environment bits into it and use this
7085       // memory in SET_FPENV_MEM.
7086       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7087       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7088       auto MPI =
7089           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7090       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7091                            MachineMemOperand::MOStore);
7092       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7093           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7094           TempAlign);
7095       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7096     }
7097     DAG.setRoot(Chain);
7098     return;
7099   }
7100   case Intrinsic::reset_fpenv:
7101     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7102     return;
7103   case Intrinsic::get_fpmode:
7104     Res = DAG.getNode(
7105         ISD::GET_FPMODE, sdl,
7106         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7107                       MVT::Other),
7108         DAG.getRoot());
7109     setValue(&I, Res);
7110     DAG.setRoot(Res.getValue(1));
7111     return;
7112   case Intrinsic::set_fpmode:
7113     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7114                       getValue(I.getArgOperand(0)));
7115     DAG.setRoot(Res);
7116     return;
7117   case Intrinsic::reset_fpmode: {
7118     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7119     DAG.setRoot(Res);
7120     return;
7121   }
7122   case Intrinsic::pcmarker: {
7123     SDValue Tmp = getValue(I.getArgOperand(0));
7124     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7125     return;
7126   }
7127   case Intrinsic::readcyclecounter: {
7128     SDValue Op = getRoot();
7129     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7130                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7131     setValue(&I, Res);
7132     DAG.setRoot(Res.getValue(1));
7133     return;
7134   }
7135   case Intrinsic::readsteadycounter: {
7136     SDValue Op = getRoot();
7137     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7138                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7139     setValue(&I, Res);
7140     DAG.setRoot(Res.getValue(1));
7141     return;
7142   }
7143   case Intrinsic::bitreverse:
7144     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7145                              getValue(I.getArgOperand(0)).getValueType(),
7146                              getValue(I.getArgOperand(0))));
7147     return;
7148   case Intrinsic::bswap:
7149     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7150                              getValue(I.getArgOperand(0)).getValueType(),
7151                              getValue(I.getArgOperand(0))));
7152     return;
7153   case Intrinsic::cttz: {
7154     SDValue Arg = getValue(I.getArgOperand(0));
7155     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7156     EVT Ty = Arg.getValueType();
7157     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7158                              sdl, Ty, Arg));
7159     return;
7160   }
7161   case Intrinsic::ctlz: {
7162     SDValue Arg = getValue(I.getArgOperand(0));
7163     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7164     EVT Ty = Arg.getValueType();
7165     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7166                              sdl, Ty, Arg));
7167     return;
7168   }
7169   case Intrinsic::ctpop: {
7170     SDValue Arg = getValue(I.getArgOperand(0));
7171     EVT Ty = Arg.getValueType();
7172     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7173     return;
7174   }
7175   case Intrinsic::fshl:
7176   case Intrinsic::fshr: {
7177     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7178     SDValue X = getValue(I.getArgOperand(0));
7179     SDValue Y = getValue(I.getArgOperand(1));
7180     SDValue Z = getValue(I.getArgOperand(2));
7181     EVT VT = X.getValueType();
7182 
7183     if (X == Y) {
7184       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7185       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7186     } else {
7187       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7188       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7189     }
7190     return;
7191   }
7192   case Intrinsic::sadd_sat: {
7193     SDValue Op1 = getValue(I.getArgOperand(0));
7194     SDValue Op2 = getValue(I.getArgOperand(1));
7195     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7196     return;
7197   }
7198   case Intrinsic::uadd_sat: {
7199     SDValue Op1 = getValue(I.getArgOperand(0));
7200     SDValue Op2 = getValue(I.getArgOperand(1));
7201     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7202     return;
7203   }
7204   case Intrinsic::ssub_sat: {
7205     SDValue Op1 = getValue(I.getArgOperand(0));
7206     SDValue Op2 = getValue(I.getArgOperand(1));
7207     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7208     return;
7209   }
7210   case Intrinsic::usub_sat: {
7211     SDValue Op1 = getValue(I.getArgOperand(0));
7212     SDValue Op2 = getValue(I.getArgOperand(1));
7213     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7214     return;
7215   }
7216   case Intrinsic::sshl_sat: {
7217     SDValue Op1 = getValue(I.getArgOperand(0));
7218     SDValue Op2 = getValue(I.getArgOperand(1));
7219     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7220     return;
7221   }
7222   case Intrinsic::ushl_sat: {
7223     SDValue Op1 = getValue(I.getArgOperand(0));
7224     SDValue Op2 = getValue(I.getArgOperand(1));
7225     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7226     return;
7227   }
7228   case Intrinsic::smul_fix:
7229   case Intrinsic::umul_fix:
7230   case Intrinsic::smul_fix_sat:
7231   case Intrinsic::umul_fix_sat: {
7232     SDValue Op1 = getValue(I.getArgOperand(0));
7233     SDValue Op2 = getValue(I.getArgOperand(1));
7234     SDValue Op3 = getValue(I.getArgOperand(2));
7235     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7236                              Op1.getValueType(), Op1, Op2, Op3));
7237     return;
7238   }
7239   case Intrinsic::sdiv_fix:
7240   case Intrinsic::udiv_fix:
7241   case Intrinsic::sdiv_fix_sat:
7242   case Intrinsic::udiv_fix_sat: {
7243     SDValue Op1 = getValue(I.getArgOperand(0));
7244     SDValue Op2 = getValue(I.getArgOperand(1));
7245     SDValue Op3 = getValue(I.getArgOperand(2));
7246     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7247                               Op1, Op2, Op3, DAG, TLI));
7248     return;
7249   }
7250   case Intrinsic::smax: {
7251     SDValue Op1 = getValue(I.getArgOperand(0));
7252     SDValue Op2 = getValue(I.getArgOperand(1));
7253     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7254     return;
7255   }
7256   case Intrinsic::smin: {
7257     SDValue Op1 = getValue(I.getArgOperand(0));
7258     SDValue Op2 = getValue(I.getArgOperand(1));
7259     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7260     return;
7261   }
7262   case Intrinsic::umax: {
7263     SDValue Op1 = getValue(I.getArgOperand(0));
7264     SDValue Op2 = getValue(I.getArgOperand(1));
7265     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7266     return;
7267   }
7268   case Intrinsic::umin: {
7269     SDValue Op1 = getValue(I.getArgOperand(0));
7270     SDValue Op2 = getValue(I.getArgOperand(1));
7271     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7272     return;
7273   }
7274   case Intrinsic::abs: {
7275     // TODO: Preserve "int min is poison" arg in SDAG?
7276     SDValue Op1 = getValue(I.getArgOperand(0));
7277     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7278     return;
7279   }
7280   case Intrinsic::scmp: {
7281     SDValue Op1 = getValue(I.getArgOperand(0));
7282     SDValue Op2 = getValue(I.getArgOperand(1));
7283     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7284     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7285     break;
7286   }
7287   case Intrinsic::ucmp: {
7288     SDValue Op1 = getValue(I.getArgOperand(0));
7289     SDValue Op2 = getValue(I.getArgOperand(1));
7290     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7291     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7292     break;
7293   }
7294   case Intrinsic::stacksave: {
7295     SDValue Op = getRoot();
7296     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7297     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7298     setValue(&I, Res);
7299     DAG.setRoot(Res.getValue(1));
7300     return;
7301   }
7302   case Intrinsic::stackrestore:
7303     Res = getValue(I.getArgOperand(0));
7304     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7305     return;
7306   case Intrinsic::get_dynamic_area_offset: {
7307     SDValue Op = getRoot();
7308     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7309     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7310     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7311     // target.
7312     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7313       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7314                          " intrinsic!");
7315     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7316                       Op);
7317     DAG.setRoot(Op);
7318     setValue(&I, Res);
7319     return;
7320   }
7321   case Intrinsic::stackguard: {
7322     MachineFunction &MF = DAG.getMachineFunction();
7323     const Module &M = *MF.getFunction().getParent();
7324     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7325     SDValue Chain = getRoot();
7326     if (TLI.useLoadStackGuardNode()) {
7327       Res = getLoadStackGuard(DAG, sdl, Chain);
7328       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7329     } else {
7330       const Value *Global = TLI.getSDagStackGuard(M);
7331       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7332       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7333                         MachinePointerInfo(Global, 0), Align,
7334                         MachineMemOperand::MOVolatile);
7335     }
7336     if (TLI.useStackGuardXorFP())
7337       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7338     DAG.setRoot(Chain);
7339     setValue(&I, Res);
7340     return;
7341   }
7342   case Intrinsic::stackprotector: {
7343     // Emit code into the DAG to store the stack guard onto the stack.
7344     MachineFunction &MF = DAG.getMachineFunction();
7345     MachineFrameInfo &MFI = MF.getFrameInfo();
7346     SDValue Src, Chain = getRoot();
7347 
7348     if (TLI.useLoadStackGuardNode())
7349       Src = getLoadStackGuard(DAG, sdl, Chain);
7350     else
7351       Src = getValue(I.getArgOperand(0));   // The guard's value.
7352 
7353     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7354 
7355     int FI = FuncInfo.StaticAllocaMap[Slot];
7356     MFI.setStackProtectorIndex(FI);
7357     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7358 
7359     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7360 
7361     // Store the stack protector onto the stack.
7362     Res = DAG.getStore(
7363         Chain, sdl, Src, FIN,
7364         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7365         MaybeAlign(), MachineMemOperand::MOVolatile);
7366     setValue(&I, Res);
7367     DAG.setRoot(Res);
7368     return;
7369   }
7370   case Intrinsic::objectsize:
7371     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7372 
7373   case Intrinsic::is_constant:
7374     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7375 
7376   case Intrinsic::annotation:
7377   case Intrinsic::ptr_annotation:
7378   case Intrinsic::launder_invariant_group:
7379   case Intrinsic::strip_invariant_group:
7380     // Drop the intrinsic, but forward the value
7381     setValue(&I, getValue(I.getOperand(0)));
7382     return;
7383 
7384   case Intrinsic::assume:
7385   case Intrinsic::experimental_noalias_scope_decl:
7386   case Intrinsic::var_annotation:
7387   case Intrinsic::sideeffect:
7388     // Discard annotate attributes, noalias scope declarations, assumptions, and
7389     // artificial side-effects.
7390     return;
7391 
7392   case Intrinsic::codeview_annotation: {
7393     // Emit a label associated with this metadata.
7394     MachineFunction &MF = DAG.getMachineFunction();
7395     MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7396     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7397     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7398     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7399     DAG.setRoot(Res);
7400     return;
7401   }
7402 
7403   case Intrinsic::init_trampoline: {
7404     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7405 
7406     SDValue Ops[6];
7407     Ops[0] = getRoot();
7408     Ops[1] = getValue(I.getArgOperand(0));
7409     Ops[2] = getValue(I.getArgOperand(1));
7410     Ops[3] = getValue(I.getArgOperand(2));
7411     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7412     Ops[5] = DAG.getSrcValue(F);
7413 
7414     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7415 
7416     DAG.setRoot(Res);
7417     return;
7418   }
7419   case Intrinsic::adjust_trampoline:
7420     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7421                              TLI.getPointerTy(DAG.getDataLayout()),
7422                              getValue(I.getArgOperand(0))));
7423     return;
7424   case Intrinsic::gcroot: {
7425     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7426            "only valid in functions with gc specified, enforced by Verifier");
7427     assert(GFI && "implied by previous");
7428     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7429     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7430 
7431     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7432     GFI->addStackRoot(FI->getIndex(), TypeMap);
7433     return;
7434   }
7435   case Intrinsic::gcread:
7436   case Intrinsic::gcwrite:
7437     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7438   case Intrinsic::get_rounding:
7439     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7440     setValue(&I, Res);
7441     DAG.setRoot(Res.getValue(1));
7442     return;
7443 
7444   case Intrinsic::expect:
7445     // Just replace __builtin_expect(exp, c) with EXP.
7446     setValue(&I, getValue(I.getArgOperand(0)));
7447     return;
7448 
7449   case Intrinsic::ubsantrap:
7450   case Intrinsic::debugtrap:
7451   case Intrinsic::trap: {
7452     StringRef TrapFuncName =
7453         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7454     if (TrapFuncName.empty()) {
7455       switch (Intrinsic) {
7456       case Intrinsic::trap:
7457         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7458         break;
7459       case Intrinsic::debugtrap:
7460         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7461         break;
7462       case Intrinsic::ubsantrap:
7463         DAG.setRoot(DAG.getNode(
7464             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7465             DAG.getTargetConstant(
7466                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7467                 MVT::i32)));
7468         break;
7469       default: llvm_unreachable("unknown trap intrinsic");
7470       }
7471       DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7472                              I.hasFnAttr(Attribute::NoMerge));
7473       return;
7474     }
7475     TargetLowering::ArgListTy Args;
7476     if (Intrinsic == Intrinsic::ubsantrap) {
7477       Args.push_back(TargetLoweringBase::ArgListEntry());
7478       Args[0].Val = I.getArgOperand(0);
7479       Args[0].Node = getValue(Args[0].Val);
7480       Args[0].Ty = Args[0].Val->getType();
7481     }
7482 
7483     TargetLowering::CallLoweringInfo CLI(DAG);
7484     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7485         CallingConv::C, I.getType(),
7486         DAG.getExternalSymbol(TrapFuncName.data(),
7487                               TLI.getPointerTy(DAG.getDataLayout())),
7488         std::move(Args));
7489     CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7490     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7491     DAG.setRoot(Result.second);
7492     return;
7493   }
7494 
7495   case Intrinsic::allow_runtime_check:
7496   case Intrinsic::allow_ubsan_check:
7497     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7498     return;
7499 
7500   case Intrinsic::uadd_with_overflow:
7501   case Intrinsic::sadd_with_overflow:
7502   case Intrinsic::usub_with_overflow:
7503   case Intrinsic::ssub_with_overflow:
7504   case Intrinsic::umul_with_overflow:
7505   case Intrinsic::smul_with_overflow: {
7506     ISD::NodeType Op;
7507     switch (Intrinsic) {
7508     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7509     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7510     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7511     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7512     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7513     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7514     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7515     }
7516     SDValue Op1 = getValue(I.getArgOperand(0));
7517     SDValue Op2 = getValue(I.getArgOperand(1));
7518 
7519     EVT ResultVT = Op1.getValueType();
7520     EVT OverflowVT = MVT::i1;
7521     if (ResultVT.isVector())
7522       OverflowVT = EVT::getVectorVT(
7523           *Context, OverflowVT, ResultVT.getVectorElementCount());
7524 
7525     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7526     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7527     return;
7528   }
7529   case Intrinsic::prefetch: {
7530     SDValue Ops[5];
7531     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7532     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7533     Ops[0] = DAG.getRoot();
7534     Ops[1] = getValue(I.getArgOperand(0));
7535     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7536                                    MVT::i32);
7537     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7538                                    MVT::i32);
7539     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7540                                    MVT::i32);
7541     SDValue Result = DAG.getMemIntrinsicNode(
7542         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7543         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7544         /* align */ std::nullopt, Flags);
7545 
7546     // Chain the prefetch in parallel with any pending loads, to stay out of
7547     // the way of later optimizations.
7548     PendingLoads.push_back(Result);
7549     Result = getRoot();
7550     DAG.setRoot(Result);
7551     return;
7552   }
7553   case Intrinsic::lifetime_start:
7554   case Intrinsic::lifetime_end: {
7555     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7556     // Stack coloring is not enabled in O0, discard region information.
7557     if (TM.getOptLevel() == CodeGenOptLevel::None)
7558       return;
7559 
7560     const int64_t ObjectSize =
7561         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7562     Value *const ObjectPtr = I.getArgOperand(1);
7563     SmallVector<const Value *, 4> Allocas;
7564     getUnderlyingObjects(ObjectPtr, Allocas);
7565 
7566     for (const Value *Alloca : Allocas) {
7567       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7568 
7569       // Could not find an Alloca.
7570       if (!LifetimeObject)
7571         continue;
7572 
7573       // First check that the Alloca is static, otherwise it won't have a
7574       // valid frame index.
7575       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7576       if (SI == FuncInfo.StaticAllocaMap.end())
7577         return;
7578 
7579       const int FrameIndex = SI->second;
7580       int64_t Offset;
7581       if (GetPointerBaseWithConstantOffset(
7582               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7583         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7584       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7585                                 Offset);
7586       DAG.setRoot(Res);
7587     }
7588     return;
7589   }
7590   case Intrinsic::pseudoprobe: {
7591     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7592     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7593     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7594     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7595     DAG.setRoot(Res);
7596     return;
7597   }
7598   case Intrinsic::invariant_start:
7599     // Discard region information.
7600     setValue(&I,
7601              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7602     return;
7603   case Intrinsic::invariant_end:
7604     // Discard region information.
7605     return;
7606   case Intrinsic::clear_cache: {
7607     SDValue InputChain = DAG.getRoot();
7608     SDValue StartVal = getValue(I.getArgOperand(0));
7609     SDValue EndVal = getValue(I.getArgOperand(1));
7610     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7611                       {InputChain, StartVal, EndVal});
7612     setValue(&I, Res);
7613     DAG.setRoot(Res);
7614     return;
7615   }
7616   case Intrinsic::donothing:
7617   case Intrinsic::seh_try_begin:
7618   case Intrinsic::seh_scope_begin:
7619   case Intrinsic::seh_try_end:
7620   case Intrinsic::seh_scope_end:
7621     // ignore
7622     return;
7623   case Intrinsic::experimental_stackmap:
7624     visitStackmap(I);
7625     return;
7626   case Intrinsic::experimental_patchpoint_void:
7627   case Intrinsic::experimental_patchpoint:
7628     visitPatchpoint(I);
7629     return;
7630   case Intrinsic::experimental_gc_statepoint:
7631     LowerStatepoint(cast<GCStatepointInst>(I));
7632     return;
7633   case Intrinsic::experimental_gc_result:
7634     visitGCResult(cast<GCResultInst>(I));
7635     return;
7636   case Intrinsic::experimental_gc_relocate:
7637     visitGCRelocate(cast<GCRelocateInst>(I));
7638     return;
7639   case Intrinsic::instrprof_cover:
7640     llvm_unreachable("instrprof failed to lower a cover");
7641   case Intrinsic::instrprof_increment:
7642     llvm_unreachable("instrprof failed to lower an increment");
7643   case Intrinsic::instrprof_timestamp:
7644     llvm_unreachable("instrprof failed to lower a timestamp");
7645   case Intrinsic::instrprof_value_profile:
7646     llvm_unreachable("instrprof failed to lower a value profiling call");
7647   case Intrinsic::instrprof_mcdc_parameters:
7648     llvm_unreachable("instrprof failed to lower mcdc parameters");
7649   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7650     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7651   case Intrinsic::localescape: {
7652     MachineFunction &MF = DAG.getMachineFunction();
7653     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7654 
7655     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7656     // is the same on all targets.
7657     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7658       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7659       if (isa<ConstantPointerNull>(Arg))
7660         continue; // Skip null pointers. They represent a hole in index space.
7661       AllocaInst *Slot = cast<AllocaInst>(Arg);
7662       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7663              "can only escape static allocas");
7664       int FI = FuncInfo.StaticAllocaMap[Slot];
7665       MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7666           GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7667       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7668               TII->get(TargetOpcode::LOCAL_ESCAPE))
7669           .addSym(FrameAllocSym)
7670           .addFrameIndex(FI);
7671     }
7672 
7673     return;
7674   }
7675 
7676   case Intrinsic::localrecover: {
7677     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7678     MachineFunction &MF = DAG.getMachineFunction();
7679 
7680     // Get the symbol that defines the frame offset.
7681     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7682     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7683     unsigned IdxVal =
7684         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7685     MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7686         GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7687 
7688     Value *FP = I.getArgOperand(1);
7689     SDValue FPVal = getValue(FP);
7690     EVT PtrVT = FPVal.getValueType();
7691 
7692     // Create a MCSymbol for the label to avoid any target lowering
7693     // that would make this PC relative.
7694     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7695     SDValue OffsetVal =
7696         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7697 
7698     // Add the offset to the FP.
7699     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7700     setValue(&I, Add);
7701 
7702     return;
7703   }
7704 
7705   case Intrinsic::eh_exceptionpointer:
7706   case Intrinsic::eh_exceptioncode: {
7707     // Get the exception pointer vreg, copy from it, and resize it to fit.
7708     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7709     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7710     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7711     unsigned VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7712     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7713     if (Intrinsic == Intrinsic::eh_exceptioncode)
7714       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7715     setValue(&I, N);
7716     return;
7717   }
7718   case Intrinsic::xray_customevent: {
7719     // Here we want to make sure that the intrinsic behaves as if it has a
7720     // specific calling convention.
7721     const auto &Triple = DAG.getTarget().getTargetTriple();
7722     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7723       return;
7724 
7725     SmallVector<SDValue, 8> Ops;
7726 
7727     // We want to say that we always want the arguments in registers.
7728     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7729     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7730     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7731     SDValue Chain = getRoot();
7732     Ops.push_back(LogEntryVal);
7733     Ops.push_back(StrSizeVal);
7734     Ops.push_back(Chain);
7735 
7736     // We need to enforce the calling convention for the callsite, so that
7737     // argument ordering is enforced correctly, and that register allocation can
7738     // see that some registers may be assumed clobbered and have to preserve
7739     // them across calls to the intrinsic.
7740     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7741                                            sdl, NodeTys, Ops);
7742     SDValue patchableNode = SDValue(MN, 0);
7743     DAG.setRoot(patchableNode);
7744     setValue(&I, patchableNode);
7745     return;
7746   }
7747   case Intrinsic::xray_typedevent: {
7748     // Here we want to make sure that the intrinsic behaves as if it has a
7749     // specific calling convention.
7750     const auto &Triple = DAG.getTarget().getTargetTriple();
7751     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7752       return;
7753 
7754     SmallVector<SDValue, 8> Ops;
7755 
7756     // We want to say that we always want the arguments in registers.
7757     // It's unclear to me how manipulating the selection DAG here forces callers
7758     // to provide arguments in registers instead of on the stack.
7759     SDValue LogTypeId = getValue(I.getArgOperand(0));
7760     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7761     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7762     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7763     SDValue Chain = getRoot();
7764     Ops.push_back(LogTypeId);
7765     Ops.push_back(LogEntryVal);
7766     Ops.push_back(StrSizeVal);
7767     Ops.push_back(Chain);
7768 
7769     // We need to enforce the calling convention for the callsite, so that
7770     // argument ordering is enforced correctly, and that register allocation can
7771     // see that some registers may be assumed clobbered and have to preserve
7772     // them across calls to the intrinsic.
7773     MachineSDNode *MN = DAG.getMachineNode(
7774         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7775     SDValue patchableNode = SDValue(MN, 0);
7776     DAG.setRoot(patchableNode);
7777     setValue(&I, patchableNode);
7778     return;
7779   }
7780   case Intrinsic::experimental_deoptimize:
7781     LowerDeoptimizeCall(&I);
7782     return;
7783   case Intrinsic::stepvector:
7784     visitStepVector(I);
7785     return;
7786   case Intrinsic::vector_reduce_fadd:
7787   case Intrinsic::vector_reduce_fmul:
7788   case Intrinsic::vector_reduce_add:
7789   case Intrinsic::vector_reduce_mul:
7790   case Intrinsic::vector_reduce_and:
7791   case Intrinsic::vector_reduce_or:
7792   case Intrinsic::vector_reduce_xor:
7793   case Intrinsic::vector_reduce_smax:
7794   case Intrinsic::vector_reduce_smin:
7795   case Intrinsic::vector_reduce_umax:
7796   case Intrinsic::vector_reduce_umin:
7797   case Intrinsic::vector_reduce_fmax:
7798   case Intrinsic::vector_reduce_fmin:
7799   case Intrinsic::vector_reduce_fmaximum:
7800   case Intrinsic::vector_reduce_fminimum:
7801     visitVectorReduce(I, Intrinsic);
7802     return;
7803 
7804   case Intrinsic::icall_branch_funnel: {
7805     SmallVector<SDValue, 16> Ops;
7806     Ops.push_back(getValue(I.getArgOperand(0)));
7807 
7808     int64_t Offset;
7809     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7810         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7811     if (!Base)
7812       report_fatal_error(
7813           "llvm.icall.branch.funnel operand must be a GlobalValue");
7814     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7815 
7816     struct BranchFunnelTarget {
7817       int64_t Offset;
7818       SDValue Target;
7819     };
7820     SmallVector<BranchFunnelTarget, 8> Targets;
7821 
7822     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7823       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7824           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7825       if (ElemBase != Base)
7826         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7827                            "to the same GlobalValue");
7828 
7829       SDValue Val = getValue(I.getArgOperand(Op + 1));
7830       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7831       if (!GA)
7832         report_fatal_error(
7833             "llvm.icall.branch.funnel operand must be a GlobalValue");
7834       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7835                                      GA->getGlobal(), sdl, Val.getValueType(),
7836                                      GA->getOffset())});
7837     }
7838     llvm::sort(Targets,
7839                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7840                  return T1.Offset < T2.Offset;
7841                });
7842 
7843     for (auto &T : Targets) {
7844       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7845       Ops.push_back(T.Target);
7846     }
7847 
7848     Ops.push_back(DAG.getRoot()); // Chain
7849     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7850                                  MVT::Other, Ops),
7851               0);
7852     DAG.setRoot(N);
7853     setValue(&I, N);
7854     HasTailCall = true;
7855     return;
7856   }
7857 
7858   case Intrinsic::wasm_landingpad_index:
7859     // Information this intrinsic contained has been transferred to
7860     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7861     // delete it now.
7862     return;
7863 
7864   case Intrinsic::aarch64_settag:
7865   case Intrinsic::aarch64_settag_zero: {
7866     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7867     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7868     SDValue Val = TSI.EmitTargetCodeForSetTag(
7869         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7870         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7871         ZeroMemory);
7872     DAG.setRoot(Val);
7873     setValue(&I, Val);
7874     return;
7875   }
7876   case Intrinsic::amdgcn_cs_chain: {
7877     assert(I.arg_size() == 5 && "Additional args not supported yet");
7878     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7879            "Non-zero flags not supported yet");
7880 
7881     // At this point we don't care if it's amdgpu_cs_chain or
7882     // amdgpu_cs_chain_preserve.
7883     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7884 
7885     Type *RetTy = I.getType();
7886     assert(RetTy->isVoidTy() && "Should not return");
7887 
7888     SDValue Callee = getValue(I.getOperand(0));
7889 
7890     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
7891     // We'll also tack the value of the EXEC mask at the end.
7892     TargetLowering::ArgListTy Args;
7893     Args.reserve(3);
7894 
7895     for (unsigned Idx : {2, 3, 1}) {
7896       TargetLowering::ArgListEntry Arg;
7897       Arg.Node = getValue(I.getOperand(Idx));
7898       Arg.Ty = I.getOperand(Idx)->getType();
7899       Arg.setAttributes(&I, Idx);
7900       Args.push_back(Arg);
7901     }
7902 
7903     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
7904     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
7905     Args[2].IsInReg = true; // EXEC should be inreg
7906 
7907     TargetLowering::CallLoweringInfo CLI(DAG);
7908     CLI.setDebugLoc(getCurSDLoc())
7909         .setChain(getRoot())
7910         .setCallee(CC, RetTy, Callee, std::move(Args))
7911         .setNoReturn(true)
7912         .setTailCall(true)
7913         .setConvergent(I.isConvergent());
7914     CLI.CB = &I;
7915     std::pair<SDValue, SDValue> Result =
7916         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
7917     (void)Result;
7918     assert(!Result.first.getNode() && !Result.second.getNode() &&
7919            "Should've lowered as tail call");
7920 
7921     HasTailCall = true;
7922     return;
7923   }
7924   case Intrinsic::ptrmask: {
7925     SDValue Ptr = getValue(I.getOperand(0));
7926     SDValue Mask = getValue(I.getOperand(1));
7927 
7928     // On arm64_32, pointers are 32 bits when stored in memory, but
7929     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
7930     // match the index type, but the pointer is 64 bits, so the the mask must be
7931     // zero-extended up to 64 bits to match the pointer.
7932     EVT PtrVT =
7933         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7934     EVT MemVT =
7935         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
7936     assert(PtrVT == Ptr.getValueType());
7937     assert(MemVT == Mask.getValueType());
7938     if (MemVT != PtrVT)
7939       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
7940 
7941     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
7942     return;
7943   }
7944   case Intrinsic::threadlocal_address: {
7945     setValue(&I, getValue(I.getOperand(0)));
7946     return;
7947   }
7948   case Intrinsic::get_active_lane_mask: {
7949     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7950     SDValue Index = getValue(I.getOperand(0));
7951     EVT ElementVT = Index.getValueType();
7952 
7953     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
7954       visitTargetIntrinsic(I, Intrinsic);
7955       return;
7956     }
7957 
7958     SDValue TripCount = getValue(I.getOperand(1));
7959     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
7960                                  CCVT.getVectorElementCount());
7961 
7962     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
7963     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
7964     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
7965     SDValue VectorInduction = DAG.getNode(
7966         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
7967     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
7968                                  VectorTripCount, ISD::CondCode::SETULT);
7969     setValue(&I, SetCC);
7970     return;
7971   }
7972   case Intrinsic::experimental_get_vector_length: {
7973     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
7974            "Expected positive VF");
7975     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
7976     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
7977 
7978     SDValue Count = getValue(I.getOperand(0));
7979     EVT CountVT = Count.getValueType();
7980 
7981     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
7982       visitTargetIntrinsic(I, Intrinsic);
7983       return;
7984     }
7985 
7986     // Expand to a umin between the trip count and the maximum elements the type
7987     // can hold.
7988     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7989 
7990     // Extend the trip count to at least the result VT.
7991     if (CountVT.bitsLT(VT)) {
7992       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
7993       CountVT = VT;
7994     }
7995 
7996     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
7997                                          ElementCount::get(VF, IsScalable));
7998 
7999     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8000     // Clip to the result type if needed.
8001     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8002 
8003     setValue(&I, Trunc);
8004     return;
8005   }
8006   case Intrinsic::experimental_vector_partial_reduce_add: {
8007     SDValue OpNode = getValue(I.getOperand(1));
8008     EVT ReducedTy = EVT::getEVT(I.getType());
8009     EVT FullTy = OpNode.getValueType();
8010 
8011     unsigned Stride = ReducedTy.getVectorMinNumElements();
8012     unsigned ScaleFactor = FullTy.getVectorMinNumElements() / Stride;
8013 
8014     // Collect all of the subvectors
8015     std::deque<SDValue> Subvectors;
8016     Subvectors.push_back(getValue(I.getOperand(0)));
8017     for (unsigned i = 0; i < ScaleFactor; i++) {
8018       auto SourceIndex = DAG.getVectorIdxConstant(i * Stride, sdl);
8019       Subvectors.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ReducedTy,
8020                                        {OpNode, SourceIndex}));
8021     }
8022 
8023     // Flatten the subvector tree
8024     while (Subvectors.size() > 1) {
8025       Subvectors.push_back(DAG.getNode(ISD::ADD, sdl, ReducedTy,
8026                                        {Subvectors[0], Subvectors[1]}));
8027       Subvectors.pop_front();
8028       Subvectors.pop_front();
8029     }
8030 
8031     assert(Subvectors.size() == 1 &&
8032            "There should only be one subvector after tree flattening");
8033 
8034     setValue(&I, Subvectors[0]);
8035     return;
8036   }
8037   case Intrinsic::experimental_cttz_elts: {
8038     auto DL = getCurSDLoc();
8039     SDValue Op = getValue(I.getOperand(0));
8040     EVT OpVT = Op.getValueType();
8041 
8042     if (!TLI.shouldExpandCttzElements(OpVT)) {
8043       visitTargetIntrinsic(I, Intrinsic);
8044       return;
8045     }
8046 
8047     if (OpVT.getScalarType() != MVT::i1) {
8048       // Compare the input vector elements to zero & use to count trailing zeros
8049       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8050       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8051                               OpVT.getVectorElementCount());
8052       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8053     }
8054 
8055     // If the zero-is-poison flag is set, we can assume the upper limit
8056     // of the result is VF-1.
8057     bool ZeroIsPoison =
8058         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8059     ConstantRange VScaleRange(1, true); // Dummy value.
8060     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8061       VScaleRange = getVScaleRange(I.getCaller(), 64);
8062     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8063         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8064 
8065     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8066 
8067     // Create the new vector type & get the vector length
8068     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8069                                  OpVT.getVectorElementCount());
8070 
8071     SDValue VL =
8072         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8073 
8074     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8075     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8076     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8077     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8078     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8079     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8080     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8081 
8082     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8083     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8084 
8085     setValue(&I, Ret);
8086     return;
8087   }
8088   case Intrinsic::vector_insert: {
8089     SDValue Vec = getValue(I.getOperand(0));
8090     SDValue SubVec = getValue(I.getOperand(1));
8091     SDValue Index = getValue(I.getOperand(2));
8092 
8093     // The intrinsic's index type is i64, but the SDNode requires an index type
8094     // suitable for the target. Convert the index as required.
8095     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8096     if (Index.getValueType() != VectorIdxTy)
8097       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8098 
8099     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8100     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8101                              Index));
8102     return;
8103   }
8104   case Intrinsic::vector_extract: {
8105     SDValue Vec = getValue(I.getOperand(0));
8106     SDValue Index = getValue(I.getOperand(1));
8107     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8108 
8109     // The intrinsic's index type is i64, but the SDNode requires an index type
8110     // suitable for the target. Convert the index as required.
8111     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8112     if (Index.getValueType() != VectorIdxTy)
8113       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8114 
8115     setValue(&I,
8116              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8117     return;
8118   }
8119   case Intrinsic::vector_reverse:
8120     visitVectorReverse(I);
8121     return;
8122   case Intrinsic::vector_splice:
8123     visitVectorSplice(I);
8124     return;
8125   case Intrinsic::callbr_landingpad:
8126     visitCallBrLandingPad(I);
8127     return;
8128   case Intrinsic::vector_interleave2:
8129     visitVectorInterleave(I);
8130     return;
8131   case Intrinsic::vector_deinterleave2:
8132     visitVectorDeinterleave(I);
8133     return;
8134   case Intrinsic::experimental_vector_compress:
8135     setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8136                              getValue(I.getArgOperand(0)).getValueType(),
8137                              getValue(I.getArgOperand(0)),
8138                              getValue(I.getArgOperand(1)),
8139                              getValue(I.getArgOperand(2)), Flags));
8140     return;
8141   case Intrinsic::experimental_convergence_anchor:
8142   case Intrinsic::experimental_convergence_entry:
8143   case Intrinsic::experimental_convergence_loop:
8144     visitConvergenceControl(I, Intrinsic);
8145     return;
8146   case Intrinsic::experimental_vector_histogram_add: {
8147     visitVectorHistogram(I, Intrinsic);
8148     return;
8149   }
8150   }
8151 }
8152 
8153 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8154     const ConstrainedFPIntrinsic &FPI) {
8155   SDLoc sdl = getCurSDLoc();
8156 
8157   // We do not need to serialize constrained FP intrinsics against
8158   // each other or against (nonvolatile) loads, so they can be
8159   // chained like loads.
8160   SDValue Chain = DAG.getRoot();
8161   SmallVector<SDValue, 4> Opers;
8162   Opers.push_back(Chain);
8163   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8164     Opers.push_back(getValue(FPI.getArgOperand(I)));
8165 
8166   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8167     assert(Result.getNode()->getNumValues() == 2);
8168 
8169     // Push node to the appropriate list so that future instructions can be
8170     // chained up correctly.
8171     SDValue OutChain = Result.getValue(1);
8172     switch (EB) {
8173     case fp::ExceptionBehavior::ebIgnore:
8174       // The only reason why ebIgnore nodes still need to be chained is that
8175       // they might depend on the current rounding mode, and therefore must
8176       // not be moved across instruction that may change that mode.
8177       [[fallthrough]];
8178     case fp::ExceptionBehavior::ebMayTrap:
8179       // These must not be moved across calls or instructions that may change
8180       // floating-point exception masks.
8181       PendingConstrainedFP.push_back(OutChain);
8182       break;
8183     case fp::ExceptionBehavior::ebStrict:
8184       // These must not be moved across calls or instructions that may change
8185       // floating-point exception masks or read floating-point exception flags.
8186       // In addition, they cannot be optimized out even if unused.
8187       PendingConstrainedFPStrict.push_back(OutChain);
8188       break;
8189     }
8190   };
8191 
8192   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8193   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8194   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8195   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8196 
8197   SDNodeFlags Flags;
8198   if (EB == fp::ExceptionBehavior::ebIgnore)
8199     Flags.setNoFPExcept(true);
8200 
8201   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8202     Flags.copyFMF(*FPOp);
8203 
8204   unsigned Opcode;
8205   switch (FPI.getIntrinsicID()) {
8206   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8207 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8208   case Intrinsic::INTRINSIC:                                                   \
8209     Opcode = ISD::STRICT_##DAGN;                                               \
8210     break;
8211 #include "llvm/IR/ConstrainedOps.def"
8212   case Intrinsic::experimental_constrained_fmuladd: {
8213     Opcode = ISD::STRICT_FMA;
8214     // Break fmuladd into fmul and fadd.
8215     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8216         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8217       Opers.pop_back();
8218       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8219       pushOutChain(Mul, EB);
8220       Opcode = ISD::STRICT_FADD;
8221       Opers.clear();
8222       Opers.push_back(Mul.getValue(1));
8223       Opers.push_back(Mul.getValue(0));
8224       Opers.push_back(getValue(FPI.getArgOperand(2)));
8225     }
8226     break;
8227   }
8228   }
8229 
8230   // A few strict DAG nodes carry additional operands that are not
8231   // set up by the default code above.
8232   switch (Opcode) {
8233   default: break;
8234   case ISD::STRICT_FP_ROUND:
8235     Opers.push_back(
8236         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8237     break;
8238   case ISD::STRICT_FSETCC:
8239   case ISD::STRICT_FSETCCS: {
8240     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8241     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8242     if (TM.Options.NoNaNsFPMath)
8243       Condition = getFCmpCodeWithoutNaN(Condition);
8244     Opers.push_back(DAG.getCondCode(Condition));
8245     break;
8246   }
8247   }
8248 
8249   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8250   pushOutChain(Result, EB);
8251 
8252   SDValue FPResult = Result.getValue(0);
8253   setValue(&FPI, FPResult);
8254 }
8255 
8256 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8257   std::optional<unsigned> ResOPC;
8258   switch (VPIntrin.getIntrinsicID()) {
8259   case Intrinsic::vp_ctlz: {
8260     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8261     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8262     break;
8263   }
8264   case Intrinsic::vp_cttz: {
8265     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8266     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8267     break;
8268   }
8269   case Intrinsic::vp_cttz_elts: {
8270     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8271     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8272     break;
8273   }
8274 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8275   case Intrinsic::VPID:                                                        \
8276     ResOPC = ISD::VPSD;                                                        \
8277     break;
8278 #include "llvm/IR/VPIntrinsics.def"
8279   }
8280 
8281   if (!ResOPC)
8282     llvm_unreachable(
8283         "Inconsistency: no SDNode available for this VPIntrinsic!");
8284 
8285   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8286       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8287     if (VPIntrin.getFastMathFlags().allowReassoc())
8288       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8289                                                 : ISD::VP_REDUCE_FMUL;
8290   }
8291 
8292   return *ResOPC;
8293 }
8294 
8295 void SelectionDAGBuilder::visitVPLoad(
8296     const VPIntrinsic &VPIntrin, EVT VT,
8297     const SmallVectorImpl<SDValue> &OpValues) {
8298   SDLoc DL = getCurSDLoc();
8299   Value *PtrOperand = VPIntrin.getArgOperand(0);
8300   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8301   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8302   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8303   SDValue LD;
8304   // Do not serialize variable-length loads of constant memory with
8305   // anything.
8306   if (!Alignment)
8307     Alignment = DAG.getEVTAlign(VT);
8308   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8309   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8310   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8311   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8312       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8313       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8314   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8315                      MMO, false /*IsExpanding */);
8316   if (AddToChain)
8317     PendingLoads.push_back(LD.getValue(1));
8318   setValue(&VPIntrin, LD);
8319 }
8320 
8321 void SelectionDAGBuilder::visitVPGather(
8322     const VPIntrinsic &VPIntrin, EVT VT,
8323     const SmallVectorImpl<SDValue> &OpValues) {
8324   SDLoc DL = getCurSDLoc();
8325   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8326   Value *PtrOperand = VPIntrin.getArgOperand(0);
8327   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8328   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8329   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8330   SDValue LD;
8331   if (!Alignment)
8332     Alignment = DAG.getEVTAlign(VT.getScalarType());
8333   unsigned AS =
8334     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8335   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8336       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8337       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8338   SDValue Base, Index, Scale;
8339   ISD::MemIndexType IndexType;
8340   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8341                                     this, VPIntrin.getParent(),
8342                                     VT.getScalarStoreSize());
8343   if (!UniformBase) {
8344     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8345     Index = getValue(PtrOperand);
8346     IndexType = ISD::SIGNED_SCALED;
8347     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8348   }
8349   EVT IdxVT = Index.getValueType();
8350   EVT EltTy = IdxVT.getVectorElementType();
8351   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8352     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8353     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8354   }
8355   LD = DAG.getGatherVP(
8356       DAG.getVTList(VT, MVT::Other), VT, DL,
8357       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8358       IndexType);
8359   PendingLoads.push_back(LD.getValue(1));
8360   setValue(&VPIntrin, LD);
8361 }
8362 
8363 void SelectionDAGBuilder::visitVPStore(
8364     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8365   SDLoc DL = getCurSDLoc();
8366   Value *PtrOperand = VPIntrin.getArgOperand(1);
8367   EVT VT = OpValues[0].getValueType();
8368   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8369   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8370   SDValue ST;
8371   if (!Alignment)
8372     Alignment = DAG.getEVTAlign(VT);
8373   SDValue Ptr = OpValues[1];
8374   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8375   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8376       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8377       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8378   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8379                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8380                       /* IsTruncating */ false, /*IsCompressing*/ false);
8381   DAG.setRoot(ST);
8382   setValue(&VPIntrin, ST);
8383 }
8384 
8385 void SelectionDAGBuilder::visitVPScatter(
8386     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8387   SDLoc DL = getCurSDLoc();
8388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8389   Value *PtrOperand = VPIntrin.getArgOperand(1);
8390   EVT VT = OpValues[0].getValueType();
8391   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8392   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8393   SDValue ST;
8394   if (!Alignment)
8395     Alignment = DAG.getEVTAlign(VT.getScalarType());
8396   unsigned AS =
8397       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8398   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8399       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8400       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8401   SDValue Base, Index, Scale;
8402   ISD::MemIndexType IndexType;
8403   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8404                                     this, VPIntrin.getParent(),
8405                                     VT.getScalarStoreSize());
8406   if (!UniformBase) {
8407     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8408     Index = getValue(PtrOperand);
8409     IndexType = ISD::SIGNED_SCALED;
8410     Scale =
8411       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8412   }
8413   EVT IdxVT = Index.getValueType();
8414   EVT EltTy = IdxVT.getVectorElementType();
8415   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8416     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8417     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8418   }
8419   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8420                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8421                          OpValues[2], OpValues[3]},
8422                         MMO, IndexType);
8423   DAG.setRoot(ST);
8424   setValue(&VPIntrin, ST);
8425 }
8426 
8427 void SelectionDAGBuilder::visitVPStridedLoad(
8428     const VPIntrinsic &VPIntrin, EVT VT,
8429     const SmallVectorImpl<SDValue> &OpValues) {
8430   SDLoc DL = getCurSDLoc();
8431   Value *PtrOperand = VPIntrin.getArgOperand(0);
8432   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8433   if (!Alignment)
8434     Alignment = DAG.getEVTAlign(VT.getScalarType());
8435   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8436   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8437   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8438   bool AddToChain = !AA || !AA->pointsToConstantMemory(ML);
8439   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8440   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8441   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8442       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8443       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8444 
8445   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8446                                     OpValues[2], OpValues[3], MMO,
8447                                     false /*IsExpanding*/);
8448 
8449   if (AddToChain)
8450     PendingLoads.push_back(LD.getValue(1));
8451   setValue(&VPIntrin, LD);
8452 }
8453 
8454 void SelectionDAGBuilder::visitVPStridedStore(
8455     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8456   SDLoc DL = getCurSDLoc();
8457   Value *PtrOperand = VPIntrin.getArgOperand(1);
8458   EVT VT = OpValues[0].getValueType();
8459   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8460   if (!Alignment)
8461     Alignment = DAG.getEVTAlign(VT.getScalarType());
8462   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8463   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8464   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8465       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8466       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8467 
8468   SDValue ST = DAG.getStridedStoreVP(
8469       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8470       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8471       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8472       /*IsCompressing*/ false);
8473 
8474   DAG.setRoot(ST);
8475   setValue(&VPIntrin, ST);
8476 }
8477 
8478 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8480   SDLoc DL = getCurSDLoc();
8481 
8482   ISD::CondCode Condition;
8483   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8484   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8485   if (IsFP) {
8486     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8487     // flags, but calls that don't return floating-point types can't be
8488     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8489     Condition = getFCmpCondCode(CondCode);
8490     if (TM.Options.NoNaNsFPMath)
8491       Condition = getFCmpCodeWithoutNaN(Condition);
8492   } else {
8493     Condition = getICmpCondCode(CondCode);
8494   }
8495 
8496   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8497   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8498   // #2 is the condition code
8499   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8500   SDValue EVL = getValue(VPIntrin.getOperand(4));
8501   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8502   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8503          "Unexpected target EVL type");
8504   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8505 
8506   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8507                                                         VPIntrin.getType());
8508   setValue(&VPIntrin,
8509            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8510 }
8511 
8512 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8513     const VPIntrinsic &VPIntrin) {
8514   SDLoc DL = getCurSDLoc();
8515   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8516 
8517   auto IID = VPIntrin.getIntrinsicID();
8518 
8519   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8520     return visitVPCmp(*CmpI);
8521 
8522   SmallVector<EVT, 4> ValueVTs;
8523   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8524   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8525   SDVTList VTs = DAG.getVTList(ValueVTs);
8526 
8527   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8528 
8529   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8530   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8531          "Unexpected target EVL type");
8532 
8533   // Request operands.
8534   SmallVector<SDValue, 7> OpValues;
8535   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8536     auto Op = getValue(VPIntrin.getArgOperand(I));
8537     if (I == EVLParamPos)
8538       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8539     OpValues.push_back(Op);
8540   }
8541 
8542   switch (Opcode) {
8543   default: {
8544     SDNodeFlags SDFlags;
8545     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8546       SDFlags.copyFMF(*FPMO);
8547     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8548     setValue(&VPIntrin, Result);
8549     break;
8550   }
8551   case ISD::VP_LOAD:
8552     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8553     break;
8554   case ISD::VP_GATHER:
8555     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8556     break;
8557   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8558     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8559     break;
8560   case ISD::VP_STORE:
8561     visitVPStore(VPIntrin, OpValues);
8562     break;
8563   case ISD::VP_SCATTER:
8564     visitVPScatter(VPIntrin, OpValues);
8565     break;
8566   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8567     visitVPStridedStore(VPIntrin, OpValues);
8568     break;
8569   case ISD::VP_FMULADD: {
8570     assert(OpValues.size() == 5 && "Unexpected number of operands");
8571     SDNodeFlags SDFlags;
8572     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8573       SDFlags.copyFMF(*FPMO);
8574     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8575         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8576       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8577     } else {
8578       SDValue Mul = DAG.getNode(
8579           ISD::VP_FMUL, DL, VTs,
8580           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8581       SDValue Add =
8582           DAG.getNode(ISD::VP_FADD, DL, VTs,
8583                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8584       setValue(&VPIntrin, Add);
8585     }
8586     break;
8587   }
8588   case ISD::VP_IS_FPCLASS: {
8589     const DataLayout DLayout = DAG.getDataLayout();
8590     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8591     auto Constant = OpValues[1]->getAsZExtVal();
8592     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8593     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8594                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8595     setValue(&VPIntrin, V);
8596     return;
8597   }
8598   case ISD::VP_INTTOPTR: {
8599     SDValue N = OpValues[0];
8600     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8601     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8602     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8603                                OpValues[2]);
8604     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8605                              OpValues[2]);
8606     setValue(&VPIntrin, N);
8607     break;
8608   }
8609   case ISD::VP_PTRTOINT: {
8610     SDValue N = OpValues[0];
8611     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8612                                                           VPIntrin.getType());
8613     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8614                                        VPIntrin.getOperand(0)->getType());
8615     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8616                                OpValues[2]);
8617     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8618                              OpValues[2]);
8619     setValue(&VPIntrin, N);
8620     break;
8621   }
8622   case ISD::VP_ABS:
8623   case ISD::VP_CTLZ:
8624   case ISD::VP_CTLZ_ZERO_UNDEF:
8625   case ISD::VP_CTTZ:
8626   case ISD::VP_CTTZ_ZERO_UNDEF:
8627   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8628   case ISD::VP_CTTZ_ELTS: {
8629     SDValue Result =
8630         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8631     setValue(&VPIntrin, Result);
8632     break;
8633   }
8634   }
8635 }
8636 
8637 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8638                                           const BasicBlock *EHPadBB,
8639                                           MCSymbol *&BeginLabel) {
8640   MachineFunction &MF = DAG.getMachineFunction();
8641 
8642   // Insert a label before the invoke call to mark the try range.  This can be
8643   // used to detect deletion of the invoke via the MachineModuleInfo.
8644   BeginLabel = MF.getContext().createTempSymbol();
8645 
8646   // For SjLj, keep track of which landing pads go with which invokes
8647   // so as to maintain the ordering of pads in the LSDA.
8648   unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
8649   if (CallSiteIndex) {
8650     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8651     LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
8652 
8653     // Now that the call site is handled, stop tracking it.
8654     FuncInfo.setCurrentCallSite(0);
8655   }
8656 
8657   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8658 }
8659 
8660 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8661                                         const BasicBlock *EHPadBB,
8662                                         MCSymbol *BeginLabel) {
8663   assert(BeginLabel && "BeginLabel should've been set");
8664 
8665   MachineFunction &MF = DAG.getMachineFunction();
8666 
8667   // Insert a label at the end of the invoke call to mark the try range.  This
8668   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8669   MCSymbol *EndLabel = MF.getContext().createTempSymbol();
8670   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8671 
8672   // Inform MachineModuleInfo of range.
8673   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8674   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8675   // actually use outlined funclets and their LSDA info style.
8676   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8677     assert(II && "II should've been set");
8678     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8679     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8680   } else if (!isScopedEHPersonality(Pers)) {
8681     assert(EHPadBB);
8682     MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
8683   }
8684 
8685   return Chain;
8686 }
8687 
8688 std::pair<SDValue, SDValue>
8689 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8690                                     const BasicBlock *EHPadBB) {
8691   MCSymbol *BeginLabel = nullptr;
8692 
8693   if (EHPadBB) {
8694     // Both PendingLoads and PendingExports must be flushed here;
8695     // this call might not return.
8696     (void)getRoot();
8697     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8698     CLI.setChain(getRoot());
8699   }
8700 
8701   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8702   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8703 
8704   assert((CLI.IsTailCall || Result.second.getNode()) &&
8705          "Non-null chain expected with non-tail call!");
8706   assert((Result.second.getNode() || !Result.first.getNode()) &&
8707          "Null value expected with tail call!");
8708 
8709   if (!Result.second.getNode()) {
8710     // As a special case, a null chain means that a tail call has been emitted
8711     // and the DAG root is already updated.
8712     HasTailCall = true;
8713 
8714     // Since there's no actual continuation from this block, nothing can be
8715     // relying on us setting vregs for them.
8716     PendingExports.clear();
8717   } else {
8718     DAG.setRoot(Result.second);
8719   }
8720 
8721   if (EHPadBB) {
8722     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8723                            BeginLabel));
8724     Result.second = getRoot();
8725   }
8726 
8727   return Result;
8728 }
8729 
8730 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8731                                       bool isTailCall, bool isMustTailCall,
8732                                       const BasicBlock *EHPadBB,
8733                                       const TargetLowering::PtrAuthInfo *PAI) {
8734   auto &DL = DAG.getDataLayout();
8735   FunctionType *FTy = CB.getFunctionType();
8736   Type *RetTy = CB.getType();
8737 
8738   TargetLowering::ArgListTy Args;
8739   Args.reserve(CB.arg_size());
8740 
8741   const Value *SwiftErrorVal = nullptr;
8742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8743 
8744   if (isTailCall) {
8745     // Avoid emitting tail calls in functions with the disable-tail-calls
8746     // attribute.
8747     auto *Caller = CB.getParent()->getParent();
8748     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8749         "true" && !isMustTailCall)
8750       isTailCall = false;
8751 
8752     // We can't tail call inside a function with a swifterror argument. Lowering
8753     // does not support this yet. It would have to move into the swifterror
8754     // register before the call.
8755     if (TLI.supportSwiftError() &&
8756         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8757       isTailCall = false;
8758   }
8759 
8760   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8761     TargetLowering::ArgListEntry Entry;
8762     const Value *V = *I;
8763 
8764     // Skip empty types
8765     if (V->getType()->isEmptyTy())
8766       continue;
8767 
8768     SDValue ArgNode = getValue(V);
8769     Entry.Node = ArgNode; Entry.Ty = V->getType();
8770 
8771     Entry.setAttributes(&CB, I - CB.arg_begin());
8772 
8773     // Use swifterror virtual register as input to the call.
8774     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8775       SwiftErrorVal = V;
8776       // We find the virtual register for the actual swifterror argument.
8777       // Instead of using the Value, we use the virtual register instead.
8778       Entry.Node =
8779           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8780                           EVT(TLI.getPointerTy(DL)));
8781     }
8782 
8783     Args.push_back(Entry);
8784 
8785     // If we have an explicit sret argument that is an Instruction, (i.e., it
8786     // might point to function-local memory), we can't meaningfully tail-call.
8787     if (Entry.IsSRet && isa<Instruction>(V))
8788       isTailCall = false;
8789   }
8790 
8791   // If call site has a cfguardtarget operand bundle, create and add an
8792   // additional ArgListEntry.
8793   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8794     TargetLowering::ArgListEntry Entry;
8795     Value *V = Bundle->Inputs[0];
8796     SDValue ArgNode = getValue(V);
8797     Entry.Node = ArgNode;
8798     Entry.Ty = V->getType();
8799     Entry.IsCFGuardTarget = true;
8800     Args.push_back(Entry);
8801   }
8802 
8803   // Check if target-independent constraints permit a tail call here.
8804   // Target-dependent constraints are checked within TLI->LowerCallTo.
8805   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8806     isTailCall = false;
8807 
8808   // Disable tail calls if there is an swifterror argument. Targets have not
8809   // been updated to support tail calls.
8810   if (TLI.supportSwiftError() && SwiftErrorVal)
8811     isTailCall = false;
8812 
8813   ConstantInt *CFIType = nullptr;
8814   if (CB.isIndirectCall()) {
8815     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8816       if (!TLI.supportKCFIBundles())
8817         report_fatal_error(
8818             "Target doesn't support calls with kcfi operand bundles.");
8819       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8820       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8821     }
8822   }
8823 
8824   SDValue ConvControlToken;
8825   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8826     auto *Token = Bundle->Inputs[0].get();
8827     ConvControlToken = getValue(Token);
8828   }
8829 
8830   TargetLowering::CallLoweringInfo CLI(DAG);
8831   CLI.setDebugLoc(getCurSDLoc())
8832       .setChain(getRoot())
8833       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8834       .setTailCall(isTailCall)
8835       .setConvergent(CB.isConvergent())
8836       .setIsPreallocated(
8837           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8838       .setCFIType(CFIType)
8839       .setConvergenceControlToken(ConvControlToken);
8840 
8841   // Set the pointer authentication info if we have it.
8842   if (PAI) {
8843     if (!TLI.supportPtrAuthBundles())
8844       report_fatal_error(
8845           "This target doesn't support calls with ptrauth operand bundles.");
8846     CLI.setPtrAuth(*PAI);
8847   }
8848 
8849   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8850 
8851   if (Result.first.getNode()) {
8852     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8853     setValue(&CB, Result.first);
8854   }
8855 
8856   // The last element of CLI.InVals has the SDValue for swifterror return.
8857   // Here we copy it to a virtual register and update SwiftErrorMap for
8858   // book-keeping.
8859   if (SwiftErrorVal && TLI.supportSwiftError()) {
8860     // Get the last element of InVals.
8861     SDValue Src = CLI.InVals.back();
8862     Register VReg =
8863         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8864     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8865     DAG.setRoot(CopyNode);
8866   }
8867 }
8868 
8869 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8870                              SelectionDAGBuilder &Builder) {
8871   // Check to see if this load can be trivially constant folded, e.g. if the
8872   // input is from a string literal.
8873   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
8874     // Cast pointer to the type we really want to load.
8875     Type *LoadTy =
8876         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
8877     if (LoadVT.isVector())
8878       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
8879 
8880     LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
8881                                          PointerType::getUnqual(LoadTy));
8882 
8883     if (const Constant *LoadCst =
8884             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
8885                                          LoadTy, Builder.DAG.getDataLayout()))
8886       return Builder.getValue(LoadCst);
8887   }
8888 
8889   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
8890   // still constant memory, the input chain can be the entry node.
8891   SDValue Root;
8892   bool ConstantMemory = false;
8893 
8894   // Do not serialize (non-volatile) loads of constant memory with anything.
8895   if (Builder.AA && Builder.AA->pointsToConstantMemory(PtrVal)) {
8896     Root = Builder.DAG.getEntryNode();
8897     ConstantMemory = true;
8898   } else {
8899     // Do not serialize non-volatile loads against each other.
8900     Root = Builder.DAG.getRoot();
8901   }
8902 
8903   SDValue Ptr = Builder.getValue(PtrVal);
8904   SDValue LoadVal =
8905       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
8906                           MachinePointerInfo(PtrVal), Align(1));
8907 
8908   if (!ConstantMemory)
8909     Builder.PendingLoads.push_back(LoadVal.getValue(1));
8910   return LoadVal;
8911 }
8912 
8913 /// Record the value for an instruction that produces an integer result,
8914 /// converting the type where necessary.
8915 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
8916                                                   SDValue Value,
8917                                                   bool IsSigned) {
8918   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8919                                                     I.getType(), true);
8920   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
8921   setValue(&I, Value);
8922 }
8923 
8924 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
8925 /// true and lower it. Otherwise return false, and it will be lowered like a
8926 /// normal call.
8927 /// The caller already checked that \p I calls the appropriate LibFunc with a
8928 /// correct prototype.
8929 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
8930   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
8931   const Value *Size = I.getArgOperand(2);
8932   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
8933   if (CSize && CSize->getZExtValue() == 0) {
8934     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8935                                                           I.getType(), true);
8936     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
8937     return true;
8938   }
8939 
8940   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
8941   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
8942       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
8943       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
8944   if (Res.first.getNode()) {
8945     processIntegerCallValue(I, Res.first, true);
8946     PendingLoads.push_back(Res.second);
8947     return true;
8948   }
8949 
8950   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
8951   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
8952   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
8953     return false;
8954 
8955   // If the target has a fast compare for the given size, it will return a
8956   // preferred load type for that size. Require that the load VT is legal and
8957   // that the target supports unaligned loads of that type. Otherwise, return
8958   // INVALID.
8959   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
8960     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8961     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
8962     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
8963       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
8964       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
8965       // TODO: Check alignment of src and dest ptrs.
8966       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
8967       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
8968       if (!TLI.isTypeLegal(LVT) ||
8969           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
8970           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
8971         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
8972     }
8973 
8974     return LVT;
8975   };
8976 
8977   // This turns into unaligned loads. We only do this if the target natively
8978   // supports the MVT we'll be loading or if it is small enough (<= 4) that
8979   // we'll only produce a small number of byte loads.
8980   MVT LoadVT;
8981   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
8982   switch (NumBitsToCompare) {
8983   default:
8984     return false;
8985   case 16:
8986     LoadVT = MVT::i16;
8987     break;
8988   case 32:
8989     LoadVT = MVT::i32;
8990     break;
8991   case 64:
8992   case 128:
8993   case 256:
8994     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
8995     break;
8996   }
8997 
8998   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
8999     return false;
9000 
9001   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9002   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9003 
9004   // Bitcast to a wide integer type if the loads are vectors.
9005   if (LoadVT.isVector()) {
9006     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9007     LoadL = DAG.getBitcast(CmpVT, LoadL);
9008     LoadR = DAG.getBitcast(CmpVT, LoadR);
9009   }
9010 
9011   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9012   processIntegerCallValue(I, Cmp, false);
9013   return true;
9014 }
9015 
9016 /// See if we can lower a memchr call into an optimized form. If so, return
9017 /// true and lower it. Otherwise return false, and it will be lowered like a
9018 /// normal call.
9019 /// The caller already checked that \p I calls the appropriate LibFunc with a
9020 /// correct prototype.
9021 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9022   const Value *Src = I.getArgOperand(0);
9023   const Value *Char = I.getArgOperand(1);
9024   const Value *Length = I.getArgOperand(2);
9025 
9026   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9027   std::pair<SDValue, SDValue> Res =
9028     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9029                                 getValue(Src), getValue(Char), getValue(Length),
9030                                 MachinePointerInfo(Src));
9031   if (Res.first.getNode()) {
9032     setValue(&I, Res.first);
9033     PendingLoads.push_back(Res.second);
9034     return true;
9035   }
9036 
9037   return false;
9038 }
9039 
9040 /// See if we can lower a mempcpy call into an optimized form. If so, return
9041 /// true and lower it. Otherwise return false, and it will be lowered like a
9042 /// normal call.
9043 /// The caller already checked that \p I calls the appropriate LibFunc with a
9044 /// correct prototype.
9045 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9046   SDValue Dst = getValue(I.getArgOperand(0));
9047   SDValue Src = getValue(I.getArgOperand(1));
9048   SDValue Size = getValue(I.getArgOperand(2));
9049 
9050   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9051   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9052   // DAG::getMemcpy needs Alignment to be defined.
9053   Align Alignment = std::min(DstAlign, SrcAlign);
9054 
9055   SDLoc sdl = getCurSDLoc();
9056 
9057   // In the mempcpy context we need to pass in a false value for isTailCall
9058   // because the return pointer needs to be adjusted by the size of
9059   // the copied memory.
9060   SDValue Root = getMemoryRoot();
9061   SDValue MC = DAG.getMemcpy(
9062       Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr,
9063       std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9064       MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9065   assert(MC.getNode() != nullptr &&
9066          "** memcpy should not be lowered as TailCall in mempcpy context **");
9067   DAG.setRoot(MC);
9068 
9069   // Check if Size needs to be truncated or extended.
9070   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9071 
9072   // Adjust return pointer to point just past the last dst byte.
9073   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9074                                     Dst, Size);
9075   setValue(&I, DstPlusSize);
9076   return true;
9077 }
9078 
9079 /// See if we can lower a strcpy call into an optimized form.  If so, return
9080 /// true and lower it, otherwise return false and it will be lowered like a
9081 /// normal call.
9082 /// The caller already checked that \p I calls the appropriate LibFunc with a
9083 /// correct prototype.
9084 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9085   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9086 
9087   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9088   std::pair<SDValue, SDValue> Res =
9089     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9090                                 getValue(Arg0), getValue(Arg1),
9091                                 MachinePointerInfo(Arg0),
9092                                 MachinePointerInfo(Arg1), isStpcpy);
9093   if (Res.first.getNode()) {
9094     setValue(&I, Res.first);
9095     DAG.setRoot(Res.second);
9096     return true;
9097   }
9098 
9099   return false;
9100 }
9101 
9102 /// See if we can lower a strcmp call into an optimized form.  If so, return
9103 /// true and lower it, otherwise return false and it will be lowered like a
9104 /// normal call.
9105 /// The caller already checked that \p I calls the appropriate LibFunc with a
9106 /// correct prototype.
9107 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9108   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9109 
9110   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9111   std::pair<SDValue, SDValue> Res =
9112     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9113                                 getValue(Arg0), getValue(Arg1),
9114                                 MachinePointerInfo(Arg0),
9115                                 MachinePointerInfo(Arg1));
9116   if (Res.first.getNode()) {
9117     processIntegerCallValue(I, Res.first, true);
9118     PendingLoads.push_back(Res.second);
9119     return true;
9120   }
9121 
9122   return false;
9123 }
9124 
9125 /// See if we can lower a strlen call into an optimized form.  If so, return
9126 /// true and lower it, otherwise return false and it will be lowered like a
9127 /// normal call.
9128 /// The caller already checked that \p I calls the appropriate LibFunc with a
9129 /// correct prototype.
9130 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9131   const Value *Arg0 = I.getArgOperand(0);
9132 
9133   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9134   std::pair<SDValue, SDValue> Res =
9135     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9136                                 getValue(Arg0), MachinePointerInfo(Arg0));
9137   if (Res.first.getNode()) {
9138     processIntegerCallValue(I, Res.first, false);
9139     PendingLoads.push_back(Res.second);
9140     return true;
9141   }
9142 
9143   return false;
9144 }
9145 
9146 /// See if we can lower a strnlen call into an optimized form.  If so, return
9147 /// true and lower it, otherwise return false and it will be lowered like a
9148 /// normal call.
9149 /// The caller already checked that \p I calls the appropriate LibFunc with a
9150 /// correct prototype.
9151 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9152   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9153 
9154   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9155   std::pair<SDValue, SDValue> Res =
9156     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9157                                  getValue(Arg0), getValue(Arg1),
9158                                  MachinePointerInfo(Arg0));
9159   if (Res.first.getNode()) {
9160     processIntegerCallValue(I, Res.first, false);
9161     PendingLoads.push_back(Res.second);
9162     return true;
9163   }
9164 
9165   return false;
9166 }
9167 
9168 /// See if we can lower a unary 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::visitUnaryFloatCall(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 Tmp = getValue(I.getArgOperand(0));
9183   setValue(&I,
9184            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9185   return true;
9186 }
9187 
9188 /// See if we can lower a binary floating-point operation into an SDNode with
9189 /// the specified Opcode. If so, return true and lower it. Otherwise return
9190 /// false, and it will be lowered like a normal call.
9191 /// The caller already checked that \p I calls the appropriate LibFunc with a
9192 /// correct prototype.
9193 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9194                                                unsigned Opcode) {
9195   // We already checked this call's prototype; verify it doesn't modify errno.
9196   if (!I.onlyReadsMemory())
9197     return false;
9198 
9199   SDNodeFlags Flags;
9200   Flags.copyFMF(cast<FPMathOperator>(I));
9201 
9202   SDValue Tmp0 = getValue(I.getArgOperand(0));
9203   SDValue Tmp1 = getValue(I.getArgOperand(1));
9204   EVT VT = Tmp0.getValueType();
9205   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9206   return true;
9207 }
9208 
9209 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9210   // Handle inline assembly differently.
9211   if (I.isInlineAsm()) {
9212     visitInlineAsm(I);
9213     return;
9214   }
9215 
9216   diagnoseDontCall(I);
9217 
9218   if (Function *F = I.getCalledFunction()) {
9219     if (F->isDeclaration()) {
9220       // Is this an LLVM intrinsic or a target-specific intrinsic?
9221       unsigned IID = F->getIntrinsicID();
9222       if (!IID)
9223         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9224           IID = II->getIntrinsicID(F);
9225 
9226       if (IID) {
9227         visitIntrinsicCall(I, IID);
9228         return;
9229       }
9230     }
9231 
9232     // Check for well-known libc/libm calls.  If the function is internal, it
9233     // can't be a library call.  Don't do the check if marked as nobuiltin for
9234     // some reason or the call site requires strict floating point semantics.
9235     LibFunc Func;
9236     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9237         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9238         LibInfo->hasOptimizedCodeGen(Func)) {
9239       switch (Func) {
9240       default: break;
9241       case LibFunc_bcmp:
9242         if (visitMemCmpBCmpCall(I))
9243           return;
9244         break;
9245       case LibFunc_copysign:
9246       case LibFunc_copysignf:
9247       case LibFunc_copysignl:
9248         // We already checked this call's prototype; verify it doesn't modify
9249         // errno.
9250         if (I.onlyReadsMemory()) {
9251           SDValue LHS = getValue(I.getArgOperand(0));
9252           SDValue RHS = getValue(I.getArgOperand(1));
9253           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9254                                    LHS.getValueType(), LHS, RHS));
9255           return;
9256         }
9257         break;
9258       case LibFunc_fabs:
9259       case LibFunc_fabsf:
9260       case LibFunc_fabsl:
9261         if (visitUnaryFloatCall(I, ISD::FABS))
9262           return;
9263         break;
9264       case LibFunc_fmin:
9265       case LibFunc_fminf:
9266       case LibFunc_fminl:
9267         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9268           return;
9269         break;
9270       case LibFunc_fmax:
9271       case LibFunc_fmaxf:
9272       case LibFunc_fmaxl:
9273         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9274           return;
9275         break;
9276       case LibFunc_fminimum_num:
9277       case LibFunc_fminimum_numf:
9278       case LibFunc_fminimum_numl:
9279         if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM))
9280           return;
9281         break;
9282       case LibFunc_fmaximum_num:
9283       case LibFunc_fmaximum_numf:
9284       case LibFunc_fmaximum_numl:
9285         if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM))
9286           return;
9287         break;
9288       case LibFunc_sin:
9289       case LibFunc_sinf:
9290       case LibFunc_sinl:
9291         if (visitUnaryFloatCall(I, ISD::FSIN))
9292           return;
9293         break;
9294       case LibFunc_cos:
9295       case LibFunc_cosf:
9296       case LibFunc_cosl:
9297         if (visitUnaryFloatCall(I, ISD::FCOS))
9298           return;
9299         break;
9300       case LibFunc_tan:
9301       case LibFunc_tanf:
9302       case LibFunc_tanl:
9303         if (visitUnaryFloatCall(I, ISD::FTAN))
9304           return;
9305         break;
9306       case LibFunc_asin:
9307       case LibFunc_asinf:
9308       case LibFunc_asinl:
9309         if (visitUnaryFloatCall(I, ISD::FASIN))
9310           return;
9311         break;
9312       case LibFunc_acos:
9313       case LibFunc_acosf:
9314       case LibFunc_acosl:
9315         if (visitUnaryFloatCall(I, ISD::FACOS))
9316           return;
9317         break;
9318       case LibFunc_atan:
9319       case LibFunc_atanf:
9320       case LibFunc_atanl:
9321         if (visitUnaryFloatCall(I, ISD::FATAN))
9322           return;
9323         break;
9324       case LibFunc_sinh:
9325       case LibFunc_sinhf:
9326       case LibFunc_sinhl:
9327         if (visitUnaryFloatCall(I, ISD::FSINH))
9328           return;
9329         break;
9330       case LibFunc_cosh:
9331       case LibFunc_coshf:
9332       case LibFunc_coshl:
9333         if (visitUnaryFloatCall(I, ISD::FCOSH))
9334           return;
9335         break;
9336       case LibFunc_tanh:
9337       case LibFunc_tanhf:
9338       case LibFunc_tanhl:
9339         if (visitUnaryFloatCall(I, ISD::FTANH))
9340           return;
9341         break;
9342       case LibFunc_sqrt:
9343       case LibFunc_sqrtf:
9344       case LibFunc_sqrtl:
9345       case LibFunc_sqrt_finite:
9346       case LibFunc_sqrtf_finite:
9347       case LibFunc_sqrtl_finite:
9348         if (visitUnaryFloatCall(I, ISD::FSQRT))
9349           return;
9350         break;
9351       case LibFunc_floor:
9352       case LibFunc_floorf:
9353       case LibFunc_floorl:
9354         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9355           return;
9356         break;
9357       case LibFunc_nearbyint:
9358       case LibFunc_nearbyintf:
9359       case LibFunc_nearbyintl:
9360         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9361           return;
9362         break;
9363       case LibFunc_ceil:
9364       case LibFunc_ceilf:
9365       case LibFunc_ceill:
9366         if (visitUnaryFloatCall(I, ISD::FCEIL))
9367           return;
9368         break;
9369       case LibFunc_rint:
9370       case LibFunc_rintf:
9371       case LibFunc_rintl:
9372         if (visitUnaryFloatCall(I, ISD::FRINT))
9373           return;
9374         break;
9375       case LibFunc_round:
9376       case LibFunc_roundf:
9377       case LibFunc_roundl:
9378         if (visitUnaryFloatCall(I, ISD::FROUND))
9379           return;
9380         break;
9381       case LibFunc_trunc:
9382       case LibFunc_truncf:
9383       case LibFunc_truncl:
9384         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9385           return;
9386         break;
9387       case LibFunc_log2:
9388       case LibFunc_log2f:
9389       case LibFunc_log2l:
9390         if (visitUnaryFloatCall(I, ISD::FLOG2))
9391           return;
9392         break;
9393       case LibFunc_exp2:
9394       case LibFunc_exp2f:
9395       case LibFunc_exp2l:
9396         if (visitUnaryFloatCall(I, ISD::FEXP2))
9397           return;
9398         break;
9399       case LibFunc_exp10:
9400       case LibFunc_exp10f:
9401       case LibFunc_exp10l:
9402         if (visitUnaryFloatCall(I, ISD::FEXP10))
9403           return;
9404         break;
9405       case LibFunc_ldexp:
9406       case LibFunc_ldexpf:
9407       case LibFunc_ldexpl:
9408         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9409           return;
9410         break;
9411       case LibFunc_memcmp:
9412         if (visitMemCmpBCmpCall(I))
9413           return;
9414         break;
9415       case LibFunc_mempcpy:
9416         if (visitMemPCpyCall(I))
9417           return;
9418         break;
9419       case LibFunc_memchr:
9420         if (visitMemChrCall(I))
9421           return;
9422         break;
9423       case LibFunc_strcpy:
9424         if (visitStrCpyCall(I, false))
9425           return;
9426         break;
9427       case LibFunc_stpcpy:
9428         if (visitStrCpyCall(I, true))
9429           return;
9430         break;
9431       case LibFunc_strcmp:
9432         if (visitStrCmpCall(I))
9433           return;
9434         break;
9435       case LibFunc_strlen:
9436         if (visitStrLenCall(I))
9437           return;
9438         break;
9439       case LibFunc_strnlen:
9440         if (visitStrNLenCall(I))
9441           return;
9442         break;
9443       }
9444     }
9445   }
9446 
9447   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9448     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9449     return;
9450   }
9451 
9452   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9453   // have to do anything here to lower funclet bundles.
9454   // CFGuardTarget bundles are lowered in LowerCallTo.
9455   assert(!I.hasOperandBundlesOtherThan(
9456              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9457               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9458               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9459               LLVMContext::OB_convergencectrl}) &&
9460          "Cannot lower calls with arbitrary operand bundles!");
9461 
9462   SDValue Callee = getValue(I.getCalledOperand());
9463 
9464   if (I.hasDeoptState())
9465     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9466   else
9467     // Check if we can potentially perform a tail call. More detailed checking
9468     // is be done within LowerCallTo, after more information about the call is
9469     // known.
9470     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9471 }
9472 
9473 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9474     const CallBase &CB, const BasicBlock *EHPadBB) {
9475   auto PAB = CB.getOperandBundle("ptrauth");
9476   const Value *CalleeV = CB.getCalledOperand();
9477 
9478   // Gather the call ptrauth data from the operand bundle:
9479   //   [ i32 <key>, i64 <discriminator> ]
9480   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9481   const Value *Discriminator = PAB->Inputs[1];
9482 
9483   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9484   assert(Discriminator->getType()->isIntegerTy(64) &&
9485          "Invalid ptrauth discriminator");
9486 
9487   // Look through ptrauth constants to find the raw callee.
9488   // Do a direct unauthenticated call if we found it and everything matches.
9489   if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9490     if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9491                                          DAG.getDataLayout()))
9492       return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9493                          CB.isMustTailCall(), EHPadBB);
9494 
9495   // Functions should never be ptrauth-called directly.
9496   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9497 
9498   // Otherwise, do an authenticated indirect call.
9499   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9500                                      getValue(Discriminator)};
9501 
9502   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9503               EHPadBB, &PAI);
9504 }
9505 
9506 namespace {
9507 
9508 /// AsmOperandInfo - This contains information for each constraint that we are
9509 /// lowering.
9510 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9511 public:
9512   /// CallOperand - If this is the result output operand or a clobber
9513   /// this is null, otherwise it is the incoming operand to the CallInst.
9514   /// This gets modified as the asm is processed.
9515   SDValue CallOperand;
9516 
9517   /// AssignedRegs - If this is a register or register class operand, this
9518   /// contains the set of register corresponding to the operand.
9519   RegsForValue AssignedRegs;
9520 
9521   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9522     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9523   }
9524 
9525   /// Whether or not this operand accesses memory
9526   bool hasMemory(const TargetLowering &TLI) const {
9527     // Indirect operand accesses access memory.
9528     if (isIndirect)
9529       return true;
9530 
9531     for (const auto &Code : Codes)
9532       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9533         return true;
9534 
9535     return false;
9536   }
9537 };
9538 
9539 
9540 } // end anonymous namespace
9541 
9542 /// Make sure that the output operand \p OpInfo and its corresponding input
9543 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9544 /// out).
9545 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9546                                SDISelAsmOperandInfo &MatchingOpInfo,
9547                                SelectionDAG &DAG) {
9548   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9549     return;
9550 
9551   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9552   const auto &TLI = DAG.getTargetLoweringInfo();
9553 
9554   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9555       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9556                                        OpInfo.ConstraintVT);
9557   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9558       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9559                                        MatchingOpInfo.ConstraintVT);
9560   if ((OpInfo.ConstraintVT.isInteger() !=
9561        MatchingOpInfo.ConstraintVT.isInteger()) ||
9562       (MatchRC.second != InputRC.second)) {
9563     // FIXME: error out in a more elegant fashion
9564     report_fatal_error("Unsupported asm: input constraint"
9565                        " with a matching output constraint of"
9566                        " incompatible type!");
9567   }
9568   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9569 }
9570 
9571 /// Get a direct memory input to behave well as an indirect operand.
9572 /// This may introduce stores, hence the need for a \p Chain.
9573 /// \return The (possibly updated) chain.
9574 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9575                                         SDISelAsmOperandInfo &OpInfo,
9576                                         SelectionDAG &DAG) {
9577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9578 
9579   // If we don't have an indirect input, put it in the constpool if we can,
9580   // otherwise spill it to a stack slot.
9581   // TODO: This isn't quite right. We need to handle these according to
9582   // the addressing mode that the constraint wants. Also, this may take
9583   // an additional register for the computation and we don't want that
9584   // either.
9585 
9586   // If the operand is a float, integer, or vector constant, spill to a
9587   // constant pool entry to get its address.
9588   const Value *OpVal = OpInfo.CallOperandVal;
9589   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9590       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9591     OpInfo.CallOperand = DAG.getConstantPool(
9592         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9593     return Chain;
9594   }
9595 
9596   // Otherwise, create a stack slot and emit a store to it before the asm.
9597   Type *Ty = OpVal->getType();
9598   auto &DL = DAG.getDataLayout();
9599   TypeSize TySize = DL.getTypeAllocSize(Ty);
9600   MachineFunction &MF = DAG.getMachineFunction();
9601   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9602   int StackID = 0;
9603   if (TySize.isScalable())
9604     StackID = TFI->getStackIDForScalableVectors();
9605   int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
9606                                                  DL.getPrefTypeAlign(Ty), false,
9607                                                  nullptr, StackID);
9608   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9609   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9610                             MachinePointerInfo::getFixedStack(MF, SSFI),
9611                             TLI.getMemValueType(DL, Ty));
9612   OpInfo.CallOperand = StackSlot;
9613 
9614   return Chain;
9615 }
9616 
9617 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9618 /// specified operand.  We prefer to assign virtual registers, to allow the
9619 /// register allocator to handle the assignment process.  However, if the asm
9620 /// uses features that we can't model on machineinstrs, we have SDISel do the
9621 /// allocation.  This produces generally horrible, but correct, code.
9622 ///
9623 ///   OpInfo describes the operand
9624 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9625 static std::optional<unsigned>
9626 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9627                      SDISelAsmOperandInfo &OpInfo,
9628                      SDISelAsmOperandInfo &RefOpInfo) {
9629   LLVMContext &Context = *DAG.getContext();
9630   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9631 
9632   MachineFunction &MF = DAG.getMachineFunction();
9633   SmallVector<unsigned, 4> Regs;
9634   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9635 
9636   // No work to do for memory/address operands.
9637   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9638       OpInfo.ConstraintType == TargetLowering::C_Address)
9639     return std::nullopt;
9640 
9641   // If this is a constraint for a single physreg, or a constraint for a
9642   // register class, find it.
9643   unsigned AssignedReg;
9644   const TargetRegisterClass *RC;
9645   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9646       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9647   // RC is unset only on failure. Return immediately.
9648   if (!RC)
9649     return std::nullopt;
9650 
9651   // Get the actual register value type.  This is important, because the user
9652   // may have asked for (e.g.) the AX register in i32 type.  We need to
9653   // remember that AX is actually i16 to get the right extension.
9654   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9655 
9656   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9657     // If this is an FP operand in an integer register (or visa versa), or more
9658     // generally if the operand value disagrees with the register class we plan
9659     // to stick it in, fix the operand type.
9660     //
9661     // If this is an input value, the bitcast to the new type is done now.
9662     // Bitcast for output value is done at the end of visitInlineAsm().
9663     if ((OpInfo.Type == InlineAsm::isOutput ||
9664          OpInfo.Type == InlineAsm::isInput) &&
9665         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9666       // Try to convert to the first EVT that the reg class contains.  If the
9667       // types are identical size, use a bitcast to convert (e.g. two differing
9668       // vector types).  Note: output bitcast is done at the end of
9669       // visitInlineAsm().
9670       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9671         // Exclude indirect inputs while they are unsupported because the code
9672         // to perform the load is missing and thus OpInfo.CallOperand still
9673         // refers to the input address rather than the pointed-to value.
9674         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9675           OpInfo.CallOperand =
9676               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9677         OpInfo.ConstraintVT = RegVT;
9678         // If the operand is an FP value and we want it in integer registers,
9679         // use the corresponding integer type. This turns an f64 value into
9680         // i64, which can be passed with two i32 values on a 32-bit machine.
9681       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9682         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9683         if (OpInfo.Type == InlineAsm::isInput)
9684           OpInfo.CallOperand =
9685               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9686         OpInfo.ConstraintVT = VT;
9687       }
9688     }
9689   }
9690 
9691   // No need to allocate a matching input constraint since the constraint it's
9692   // matching to has already been allocated.
9693   if (OpInfo.isMatchingInputConstraint())
9694     return std::nullopt;
9695 
9696   EVT ValueVT = OpInfo.ConstraintVT;
9697   if (OpInfo.ConstraintVT == MVT::Other)
9698     ValueVT = RegVT;
9699 
9700   // Initialize NumRegs.
9701   unsigned NumRegs = 1;
9702   if (OpInfo.ConstraintVT != MVT::Other)
9703     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9704 
9705   // If this is a constraint for a specific physical register, like {r17},
9706   // assign it now.
9707 
9708   // If this associated to a specific register, initialize iterator to correct
9709   // place. If virtual, make sure we have enough registers
9710 
9711   // Initialize iterator if necessary
9712   TargetRegisterClass::iterator I = RC->begin();
9713   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9714 
9715   // Do not check for single registers.
9716   if (AssignedReg) {
9717     I = std::find(I, RC->end(), AssignedReg);
9718     if (I == RC->end()) {
9719       // RC does not contain the selected register, which indicates a
9720       // mismatch between the register and the required type/bitwidth.
9721       return {AssignedReg};
9722     }
9723   }
9724 
9725   for (; NumRegs; --NumRegs, ++I) {
9726     assert(I != RC->end() && "Ran out of registers to allocate!");
9727     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9728     Regs.push_back(R);
9729   }
9730 
9731   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9732   return std::nullopt;
9733 }
9734 
9735 static unsigned
9736 findMatchingInlineAsmOperand(unsigned OperandNo,
9737                              const std::vector<SDValue> &AsmNodeOperands) {
9738   // Scan until we find the definition we already emitted of this operand.
9739   unsigned CurOp = InlineAsm::Op_FirstOperand;
9740   for (; OperandNo; --OperandNo) {
9741     // Advance to the next operand.
9742     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9743     const InlineAsm::Flag F(OpFlag);
9744     assert(
9745         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9746         "Skipped past definitions?");
9747     CurOp += F.getNumOperandRegisters() + 1;
9748   }
9749   return CurOp;
9750 }
9751 
9752 namespace {
9753 
9754 class ExtraFlags {
9755   unsigned Flags = 0;
9756 
9757 public:
9758   explicit ExtraFlags(const CallBase &Call) {
9759     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9760     if (IA->hasSideEffects())
9761       Flags |= InlineAsm::Extra_HasSideEffects;
9762     if (IA->isAlignStack())
9763       Flags |= InlineAsm::Extra_IsAlignStack;
9764     if (Call.isConvergent())
9765       Flags |= InlineAsm::Extra_IsConvergent;
9766     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9767   }
9768 
9769   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9770     // Ideally, we would only check against memory constraints.  However, the
9771     // meaning of an Other constraint can be target-specific and we can't easily
9772     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9773     // for Other constraints as well.
9774     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9775         OpInfo.ConstraintType == TargetLowering::C_Other) {
9776       if (OpInfo.Type == InlineAsm::isInput)
9777         Flags |= InlineAsm::Extra_MayLoad;
9778       else if (OpInfo.Type == InlineAsm::isOutput)
9779         Flags |= InlineAsm::Extra_MayStore;
9780       else if (OpInfo.Type == InlineAsm::isClobber)
9781         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9782     }
9783   }
9784 
9785   unsigned get() const { return Flags; }
9786 };
9787 
9788 } // end anonymous namespace
9789 
9790 static bool isFunction(SDValue Op) {
9791   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9792     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9793       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9794 
9795       // In normal "call dllimport func" instruction (non-inlineasm) it force
9796       // indirect access by specifing call opcode. And usually specially print
9797       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9798       // not do in this way now. (In fact, this is similar with "Data Access"
9799       // action). So here we ignore dllimport function.
9800       if (Fn && !Fn->hasDLLImportStorageClass())
9801         return true;
9802     }
9803   }
9804   return false;
9805 }
9806 
9807 /// visitInlineAsm - Handle a call to an InlineAsm object.
9808 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9809                                          const BasicBlock *EHPadBB) {
9810   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9811 
9812   /// ConstraintOperands - Information about all of the constraints.
9813   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9814 
9815   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9816   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9817       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9818 
9819   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9820   // AsmDialect, MayLoad, MayStore).
9821   bool HasSideEffect = IA->hasSideEffects();
9822   ExtraFlags ExtraInfo(Call);
9823 
9824   for (auto &T : TargetConstraints) {
9825     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9826     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9827 
9828     if (OpInfo.CallOperandVal)
9829       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9830 
9831     if (!HasSideEffect)
9832       HasSideEffect = OpInfo.hasMemory(TLI);
9833 
9834     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9835     // FIXME: Could we compute this on OpInfo rather than T?
9836 
9837     // Compute the constraint code and ConstraintType to use.
9838     TLI.ComputeConstraintToUse(T, SDValue());
9839 
9840     if (T.ConstraintType == TargetLowering::C_Immediate &&
9841         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9842       // We've delayed emitting a diagnostic like the "n" constraint because
9843       // inlining could cause an integer showing up.
9844       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9845                                           "' expects an integer constant "
9846                                           "expression");
9847 
9848     ExtraInfo.update(T);
9849   }
9850 
9851   // We won't need to flush pending loads if this asm doesn't touch
9852   // memory and is nonvolatile.
9853   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9854 
9855   bool EmitEHLabels = isa<InvokeInst>(Call);
9856   if (EmitEHLabels) {
9857     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9858   }
9859   bool IsCallBr = isa<CallBrInst>(Call);
9860 
9861   if (IsCallBr || EmitEHLabels) {
9862     // If this is a callbr or invoke we need to flush pending exports since
9863     // inlineasm_br and invoke are terminators.
9864     // We need to do this before nodes are glued to the inlineasm_br node.
9865     Chain = getControlRoot();
9866   }
9867 
9868   MCSymbol *BeginLabel = nullptr;
9869   if (EmitEHLabels) {
9870     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
9871   }
9872 
9873   int OpNo = -1;
9874   SmallVector<StringRef> AsmStrs;
9875   IA->collectAsmStrs(AsmStrs);
9876 
9877   // Second pass over the constraints: compute which constraint option to use.
9878   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9879     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
9880       OpNo++;
9881 
9882     // If this is an output operand with a matching input operand, look up the
9883     // matching input. If their types mismatch, e.g. one is an integer, the
9884     // other is floating point, or their sizes are different, flag it as an
9885     // error.
9886     if (OpInfo.hasMatchingInput()) {
9887       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
9888       patchMatchingInput(OpInfo, Input, DAG);
9889     }
9890 
9891     // Compute the constraint code and ConstraintType to use.
9892     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
9893 
9894     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
9895          OpInfo.Type == InlineAsm::isClobber) ||
9896         OpInfo.ConstraintType == TargetLowering::C_Address)
9897       continue;
9898 
9899     // In Linux PIC model, there are 4 cases about value/label addressing:
9900     //
9901     // 1: Function call or Label jmp inside the module.
9902     // 2: Data access (such as global variable, static variable) inside module.
9903     // 3: Function call or Label jmp outside the module.
9904     // 4: Data access (such as global variable) outside the module.
9905     //
9906     // Due to current llvm inline asm architecture designed to not "recognize"
9907     // the asm code, there are quite troubles for us to treat mem addressing
9908     // differently for same value/adress used in different instuctions.
9909     // For example, in pic model, call a func may in plt way or direclty
9910     // pc-related, but lea/mov a function adress may use got.
9911     //
9912     // Here we try to "recognize" function call for the case 1 and case 3 in
9913     // inline asm. And try to adjust the constraint for them.
9914     //
9915     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
9916     // label, so here we don't handle jmp function label now, but we need to
9917     // enhance it (especilly in PIC model) if we meet meaningful requirements.
9918     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
9919         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
9920         TM.getCodeModel() != CodeModel::Large) {
9921       OpInfo.isIndirect = false;
9922       OpInfo.ConstraintType = TargetLowering::C_Address;
9923     }
9924 
9925     // If this is a memory input, and if the operand is not indirect, do what we
9926     // need to provide an address for the memory input.
9927     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
9928         !OpInfo.isIndirect) {
9929       assert((OpInfo.isMultipleAlternative ||
9930               (OpInfo.Type == InlineAsm::isInput)) &&
9931              "Can only indirectify direct input operands!");
9932 
9933       // Memory operands really want the address of the value.
9934       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
9935 
9936       // There is no longer a Value* corresponding to this operand.
9937       OpInfo.CallOperandVal = nullptr;
9938 
9939       // It is now an indirect operand.
9940       OpInfo.isIndirect = true;
9941     }
9942 
9943   }
9944 
9945   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
9946   std::vector<SDValue> AsmNodeOperands;
9947   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
9948   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
9949       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
9950 
9951   // If we have a !srcloc metadata node associated with it, we want to attach
9952   // this to the ultimately generated inline asm machineinstr.  To do this, we
9953   // pass in the third operand as this (potentially null) inline asm MDNode.
9954   const MDNode *SrcLoc = Call.getMetadata("srcloc");
9955   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
9956 
9957   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
9958   // bits as operand 3.
9959   AsmNodeOperands.push_back(DAG.getTargetConstant(
9960       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
9961 
9962   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
9963   // this, assign virtual and physical registers for inputs and otput.
9964   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
9965     // Assign Registers.
9966     SDISelAsmOperandInfo &RefOpInfo =
9967         OpInfo.isMatchingInputConstraint()
9968             ? ConstraintOperands[OpInfo.getMatchedOperand()]
9969             : OpInfo;
9970     const auto RegError =
9971         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
9972     if (RegError) {
9973       const MachineFunction &MF = DAG.getMachineFunction();
9974       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9975       const char *RegName = TRI.getName(*RegError);
9976       emitInlineAsmError(Call, "register '" + Twine(RegName) +
9977                                    "' allocated for constraint '" +
9978                                    Twine(OpInfo.ConstraintCode) +
9979                                    "' does not match required type");
9980       return;
9981     }
9982 
9983     auto DetectWriteToReservedRegister = [&]() {
9984       const MachineFunction &MF = DAG.getMachineFunction();
9985       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9986       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
9987         if (Register::isPhysicalRegister(Reg) &&
9988             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
9989           const char *RegName = TRI.getName(Reg);
9990           emitInlineAsmError(Call, "write to reserved register '" +
9991                                        Twine(RegName) + "'");
9992           return true;
9993         }
9994       }
9995       return false;
9996     };
9997     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
9998             (OpInfo.Type == InlineAsm::isInput &&
9999              !OpInfo.isMatchingInputConstraint())) &&
10000            "Only address as input operand is allowed.");
10001 
10002     switch (OpInfo.Type) {
10003     case InlineAsm::isOutput:
10004       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10005         const InlineAsm::ConstraintCode ConstraintID =
10006             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10007         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10008                "Failed to convert memory constraint code to constraint id.");
10009 
10010         // Add information to the INLINEASM node to know about this output.
10011         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10012         OpFlags.setMemConstraint(ConstraintID);
10013         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
10014                                                         MVT::i32));
10015         AsmNodeOperands.push_back(OpInfo.CallOperand);
10016       } else {
10017         // Otherwise, this outputs to a register (directly for C_Register /
10018         // C_RegisterClass, and a target-defined fashion for
10019         // C_Immediate/C_Other). Find a register that we can use.
10020         if (OpInfo.AssignedRegs.Regs.empty()) {
10021           emitInlineAsmError(
10022               Call, "couldn't allocate output register for constraint '" +
10023                         Twine(OpInfo.ConstraintCode) + "'");
10024           return;
10025         }
10026 
10027         if (DetectWriteToReservedRegister())
10028           return;
10029 
10030         // Add information to the INLINEASM node to know that this register is
10031         // set.
10032         OpInfo.AssignedRegs.AddInlineAsmOperands(
10033             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10034                                   : InlineAsm::Kind::RegDef,
10035             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
10036       }
10037       break;
10038 
10039     case InlineAsm::isInput:
10040     case InlineAsm::isLabel: {
10041       SDValue InOperandVal = OpInfo.CallOperand;
10042 
10043       if (OpInfo.isMatchingInputConstraint()) {
10044         // If this is required to match an output register we have already set,
10045         // just use its register.
10046         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10047                                                   AsmNodeOperands);
10048         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10049         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10050           if (OpInfo.isIndirect) {
10051             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10052             emitInlineAsmError(Call, "inline asm not supported yet: "
10053                                      "don't know how to handle tied "
10054                                      "indirect register inputs");
10055             return;
10056           }
10057 
10058           SmallVector<unsigned, 4> Regs;
10059           MachineFunction &MF = DAG.getMachineFunction();
10060           MachineRegisterInfo &MRI = MF.getRegInfo();
10061           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10062           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
10063           Register TiedReg = R->getReg();
10064           MVT RegVT = R->getSimpleValueType(0);
10065           const TargetRegisterClass *RC =
10066               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
10067               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10068                                       : TRI.getMinimalPhysRegClass(TiedReg);
10069           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10070             Regs.push_back(MRI.createVirtualRegister(RC));
10071 
10072           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10073 
10074           SDLoc dl = getCurSDLoc();
10075           // Use the produced MatchedRegs object to
10076           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
10077           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
10078                                            OpInfo.getMatchedOperand(), dl, DAG,
10079                                            AsmNodeOperands);
10080           break;
10081         }
10082 
10083         assert(Flag.isMemKind() && "Unknown matching constraint!");
10084         assert(Flag.getNumOperandRegisters() == 1 &&
10085                "Unexpected number of operands");
10086         // Add information to the INLINEASM node to know about this input.
10087         // See InlineAsm.h isUseOperandTiedToDef.
10088         Flag.clearMemConstraint();
10089         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10090         AsmNodeOperands.push_back(DAG.getTargetConstant(
10091             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10092         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10093         break;
10094       }
10095 
10096       // Treat indirect 'X' constraint as memory.
10097       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10098           OpInfo.isIndirect)
10099         OpInfo.ConstraintType = TargetLowering::C_Memory;
10100 
10101       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10102           OpInfo.ConstraintType == TargetLowering::C_Other) {
10103         std::vector<SDValue> Ops;
10104         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10105                                           Ops, DAG);
10106         if (Ops.empty()) {
10107           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10108             if (isa<ConstantSDNode>(InOperandVal)) {
10109               emitInlineAsmError(Call, "value out of range for constraint '" +
10110                                            Twine(OpInfo.ConstraintCode) + "'");
10111               return;
10112             }
10113 
10114           emitInlineAsmError(Call,
10115                              "invalid operand for inline asm constraint '" +
10116                                  Twine(OpInfo.ConstraintCode) + "'");
10117           return;
10118         }
10119 
10120         // Add information to the INLINEASM node to know about this input.
10121         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10122         AsmNodeOperands.push_back(DAG.getTargetConstant(
10123             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10124         llvm::append_range(AsmNodeOperands, Ops);
10125         break;
10126       }
10127 
10128       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10129         assert((OpInfo.isIndirect ||
10130                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10131                "Operand must be indirect to be a mem!");
10132         assert(InOperandVal.getValueType() ==
10133                    TLI.getPointerTy(DAG.getDataLayout()) &&
10134                "Memory operands expect pointer values");
10135 
10136         const InlineAsm::ConstraintCode ConstraintID =
10137             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10138         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10139                "Failed to convert memory constraint code to constraint id.");
10140 
10141         // Add information to the INLINEASM node to know about this input.
10142         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10143         ResOpType.setMemConstraint(ConstraintID);
10144         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10145                                                         getCurSDLoc(),
10146                                                         MVT::i32));
10147         AsmNodeOperands.push_back(InOperandVal);
10148         break;
10149       }
10150 
10151       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10152         const InlineAsm::ConstraintCode ConstraintID =
10153             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10154         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10155                "Failed to convert memory constraint code to constraint id.");
10156 
10157         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10158 
10159         SDValue AsmOp = InOperandVal;
10160         if (isFunction(InOperandVal)) {
10161           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10162           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10163           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10164                                              InOperandVal.getValueType(),
10165                                              GA->getOffset());
10166         }
10167 
10168         // Add information to the INLINEASM node to know about this input.
10169         ResOpType.setMemConstraint(ConstraintID);
10170 
10171         AsmNodeOperands.push_back(
10172             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10173 
10174         AsmNodeOperands.push_back(AsmOp);
10175         break;
10176       }
10177 
10178       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10179           OpInfo.ConstraintType != TargetLowering::C_Register) {
10180         emitInlineAsmError(Call, "unknown asm constraint '" +
10181                                      Twine(OpInfo.ConstraintCode) + "'");
10182         return;
10183       }
10184 
10185       // TODO: Support this.
10186       if (OpInfo.isIndirect) {
10187         emitInlineAsmError(
10188             Call, "Don't know how to handle indirect register inputs yet "
10189                   "for constraint '" +
10190                       Twine(OpInfo.ConstraintCode) + "'");
10191         return;
10192       }
10193 
10194       // Copy the input into the appropriate registers.
10195       if (OpInfo.AssignedRegs.Regs.empty()) {
10196         emitInlineAsmError(Call,
10197                            "couldn't allocate input reg for constraint '" +
10198                                Twine(OpInfo.ConstraintCode) + "'");
10199         return;
10200       }
10201 
10202       if (DetectWriteToReservedRegister())
10203         return;
10204 
10205       SDLoc dl = getCurSDLoc();
10206 
10207       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10208                                         &Call);
10209 
10210       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10211                                                0, dl, DAG, AsmNodeOperands);
10212       break;
10213     }
10214     case InlineAsm::isClobber:
10215       // Add the clobbered value to the operand list, so that the register
10216       // allocator is aware that the physreg got clobbered.
10217       if (!OpInfo.AssignedRegs.Regs.empty())
10218         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10219                                                  false, 0, getCurSDLoc(), DAG,
10220                                                  AsmNodeOperands);
10221       break;
10222     }
10223   }
10224 
10225   // Finish up input operands.  Set the input chain and add the flag last.
10226   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10227   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10228 
10229   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10230   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10231                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10232   Glue = Chain.getValue(1);
10233 
10234   // Do additional work to generate outputs.
10235 
10236   SmallVector<EVT, 1> ResultVTs;
10237   SmallVector<SDValue, 1> ResultValues;
10238   SmallVector<SDValue, 8> OutChains;
10239 
10240   llvm::Type *CallResultType = Call.getType();
10241   ArrayRef<Type *> ResultTypes;
10242   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10243     ResultTypes = StructResult->elements();
10244   else if (!CallResultType->isVoidTy())
10245     ResultTypes = ArrayRef(CallResultType);
10246 
10247   auto CurResultType = ResultTypes.begin();
10248   auto handleRegAssign = [&](SDValue V) {
10249     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10250     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10251     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10252     ++CurResultType;
10253     // If the type of the inline asm call site return value is different but has
10254     // same size as the type of the asm output bitcast it.  One example of this
10255     // is for vectors with different width / number of elements.  This can
10256     // happen for register classes that can contain multiple different value
10257     // types.  The preg or vreg allocated may not have the same VT as was
10258     // expected.
10259     //
10260     // This can also happen for a return value that disagrees with the register
10261     // class it is put in, eg. a double in a general-purpose register on a
10262     // 32-bit machine.
10263     if (ResultVT != V.getValueType() &&
10264         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10265       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10266     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10267              V.getValueType().isInteger()) {
10268       // If a result value was tied to an input value, the computed result
10269       // may have a wider width than the expected result.  Extract the
10270       // relevant portion.
10271       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10272     }
10273     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10274     ResultVTs.push_back(ResultVT);
10275     ResultValues.push_back(V);
10276   };
10277 
10278   // Deal with output operands.
10279   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10280     if (OpInfo.Type == InlineAsm::isOutput) {
10281       SDValue Val;
10282       // Skip trivial output operands.
10283       if (OpInfo.AssignedRegs.Regs.empty())
10284         continue;
10285 
10286       switch (OpInfo.ConstraintType) {
10287       case TargetLowering::C_Register:
10288       case TargetLowering::C_RegisterClass:
10289         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10290                                                   Chain, &Glue, &Call);
10291         break;
10292       case TargetLowering::C_Immediate:
10293       case TargetLowering::C_Other:
10294         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10295                                               OpInfo, DAG);
10296         break;
10297       case TargetLowering::C_Memory:
10298         break; // Already handled.
10299       case TargetLowering::C_Address:
10300         break; // Silence warning.
10301       case TargetLowering::C_Unknown:
10302         assert(false && "Unexpected unknown constraint");
10303       }
10304 
10305       // Indirect output manifest as stores. Record output chains.
10306       if (OpInfo.isIndirect) {
10307         const Value *Ptr = OpInfo.CallOperandVal;
10308         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10309         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10310                                      MachinePointerInfo(Ptr));
10311         OutChains.push_back(Store);
10312       } else {
10313         // generate CopyFromRegs to associated registers.
10314         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10315         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10316           for (const SDValue &V : Val->op_values())
10317             handleRegAssign(V);
10318         } else
10319           handleRegAssign(Val);
10320       }
10321     }
10322   }
10323 
10324   // Set results.
10325   if (!ResultValues.empty()) {
10326     assert(CurResultType == ResultTypes.end() &&
10327            "Mismatch in number of ResultTypes");
10328     assert(ResultValues.size() == ResultTypes.size() &&
10329            "Mismatch in number of output operands in asm result");
10330 
10331     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10332                             DAG.getVTList(ResultVTs), ResultValues);
10333     setValue(&Call, V);
10334   }
10335 
10336   // Collect store chains.
10337   if (!OutChains.empty())
10338     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10339 
10340   if (EmitEHLabels) {
10341     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10342   }
10343 
10344   // Only Update Root if inline assembly has a memory effect.
10345   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10346       EmitEHLabels)
10347     DAG.setRoot(Chain);
10348 }
10349 
10350 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10351                                              const Twine &Message) {
10352   LLVMContext &Ctx = *DAG.getContext();
10353   Ctx.emitError(&Call, Message);
10354 
10355   // Make sure we leave the DAG in a valid state
10356   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10357   SmallVector<EVT, 1> ValueVTs;
10358   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10359 
10360   if (ValueVTs.empty())
10361     return;
10362 
10363   SmallVector<SDValue, 1> Ops;
10364   for (const EVT &VT : ValueVTs)
10365     Ops.push_back(DAG.getUNDEF(VT));
10366 
10367   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10368 }
10369 
10370 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10371   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10372                           MVT::Other, getRoot(),
10373                           getValue(I.getArgOperand(0)),
10374                           DAG.getSrcValue(I.getArgOperand(0))));
10375 }
10376 
10377 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10379   const DataLayout &DL = DAG.getDataLayout();
10380   SDValue V = DAG.getVAArg(
10381       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10382       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10383       DL.getABITypeAlign(I.getType()).value());
10384   DAG.setRoot(V.getValue(1));
10385 
10386   if (I.getType()->isPointerTy())
10387     V = DAG.getPtrExtOrTrunc(
10388         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10389   setValue(&I, V);
10390 }
10391 
10392 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10393   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10394                           MVT::Other, getRoot(),
10395                           getValue(I.getArgOperand(0)),
10396                           DAG.getSrcValue(I.getArgOperand(0))));
10397 }
10398 
10399 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10400   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10401                           MVT::Other, getRoot(),
10402                           getValue(I.getArgOperand(0)),
10403                           getValue(I.getArgOperand(1)),
10404                           DAG.getSrcValue(I.getArgOperand(0)),
10405                           DAG.getSrcValue(I.getArgOperand(1))));
10406 }
10407 
10408 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10409                                                     const Instruction &I,
10410                                                     SDValue Op) {
10411   std::optional<ConstantRange> CR = getRange(I);
10412 
10413   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10414     return Op;
10415 
10416   APInt Lo = CR->getUnsignedMin();
10417   if (!Lo.isMinValue())
10418     return Op;
10419 
10420   APInt Hi = CR->getUnsignedMax();
10421   unsigned Bits = std::max(Hi.getActiveBits(),
10422                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10423 
10424   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10425 
10426   SDLoc SL = getCurSDLoc();
10427 
10428   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10429                              DAG.getValueType(SmallVT));
10430   unsigned NumVals = Op.getNode()->getNumValues();
10431   if (NumVals == 1)
10432     return ZExt;
10433 
10434   SmallVector<SDValue, 4> Ops;
10435 
10436   Ops.push_back(ZExt);
10437   for (unsigned I = 1; I != NumVals; ++I)
10438     Ops.push_back(Op.getValue(I));
10439 
10440   return DAG.getMergeValues(Ops, SL);
10441 }
10442 
10443 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10444 /// the call being lowered.
10445 ///
10446 /// This is a helper for lowering intrinsics that follow a target calling
10447 /// convention or require stack pointer adjustment. Only a subset of the
10448 /// intrinsic's operands need to participate in the calling convention.
10449 void SelectionDAGBuilder::populateCallLoweringInfo(
10450     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10451     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10452     AttributeSet RetAttrs, bool IsPatchPoint) {
10453   TargetLowering::ArgListTy Args;
10454   Args.reserve(NumArgs);
10455 
10456   // Populate the argument list.
10457   // Attributes for args start at offset 1, after the return attribute.
10458   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10459        ArgI != ArgE; ++ArgI) {
10460     const Value *V = Call->getOperand(ArgI);
10461 
10462     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10463 
10464     TargetLowering::ArgListEntry Entry;
10465     Entry.Node = getValue(V);
10466     Entry.Ty = V->getType();
10467     Entry.setAttributes(Call, ArgI);
10468     Args.push_back(Entry);
10469   }
10470 
10471   CLI.setDebugLoc(getCurSDLoc())
10472       .setChain(getRoot())
10473       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10474                  RetAttrs)
10475       .setDiscardResult(Call->use_empty())
10476       .setIsPatchPoint(IsPatchPoint)
10477       .setIsPreallocated(
10478           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10479 }
10480 
10481 /// Add a stack map intrinsic call's live variable operands to a stackmap
10482 /// or patchpoint target node's operand list.
10483 ///
10484 /// Constants are converted to TargetConstants purely as an optimization to
10485 /// avoid constant materialization and register allocation.
10486 ///
10487 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10488 /// generate addess computation nodes, and so FinalizeISel can convert the
10489 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10490 /// address materialization and register allocation, but may also be required
10491 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10492 /// alloca in the entry block, then the runtime may assume that the alloca's
10493 /// StackMap location can be read immediately after compilation and that the
10494 /// location is valid at any point during execution (this is similar to the
10495 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10496 /// only available in a register, then the runtime would need to trap when
10497 /// execution reaches the StackMap in order to read the alloca's location.
10498 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10499                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10500                                 SelectionDAGBuilder &Builder) {
10501   SelectionDAG &DAG = Builder.DAG;
10502   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10503     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10504 
10505     // Things on the stack are pointer-typed, meaning that they are already
10506     // legal and can be emitted directly to target nodes.
10507     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10508       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10509     } else {
10510       // Otherwise emit a target independent node to be legalised.
10511       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10512     }
10513   }
10514 }
10515 
10516 /// Lower llvm.experimental.stackmap.
10517 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10518   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10519   //                                  [live variables...])
10520 
10521   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10522 
10523   SDValue Chain, InGlue, Callee;
10524   SmallVector<SDValue, 32> Ops;
10525 
10526   SDLoc DL = getCurSDLoc();
10527   Callee = getValue(CI.getCalledOperand());
10528 
10529   // The stackmap intrinsic only records the live variables (the arguments
10530   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10531   // intrinsic, this won't be lowered to a function call. This means we don't
10532   // have to worry about calling conventions and target specific lowering code.
10533   // Instead we perform the call lowering right here.
10534   //
10535   // chain, flag = CALLSEQ_START(chain, 0, 0)
10536   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10537   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10538   //
10539   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10540   InGlue = Chain.getValue(1);
10541 
10542   // Add the STACKMAP operands, starting with DAG house-keeping.
10543   Ops.push_back(Chain);
10544   Ops.push_back(InGlue);
10545 
10546   // Add the <id>, <numShadowBytes> operands.
10547   //
10548   // These do not require legalisation, and can be emitted directly to target
10549   // constant nodes.
10550   SDValue ID = getValue(CI.getArgOperand(0));
10551   assert(ID.getValueType() == MVT::i64);
10552   SDValue IDConst =
10553       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10554   Ops.push_back(IDConst);
10555 
10556   SDValue Shad = getValue(CI.getArgOperand(1));
10557   assert(Shad.getValueType() == MVT::i32);
10558   SDValue ShadConst =
10559       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10560   Ops.push_back(ShadConst);
10561 
10562   // Add the live variables.
10563   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10564 
10565   // Create the STACKMAP node.
10566   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10567   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10568   InGlue = Chain.getValue(1);
10569 
10570   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10571 
10572   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10573 
10574   // Set the root to the target-lowered call chain.
10575   DAG.setRoot(Chain);
10576 
10577   // Inform the Frame Information that we have a stackmap in this function.
10578   FuncInfo.MF->getFrameInfo().setHasStackMap();
10579 }
10580 
10581 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10582 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10583                                           const BasicBlock *EHPadBB) {
10584   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10585   //                                         i32 <numBytes>,
10586   //                                         i8* <target>,
10587   //                                         i32 <numArgs>,
10588   //                                         [Args...],
10589   //                                         [live variables...])
10590 
10591   CallingConv::ID CC = CB.getCallingConv();
10592   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10593   bool HasDef = !CB.getType()->isVoidTy();
10594   SDLoc dl = getCurSDLoc();
10595   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10596 
10597   // Handle immediate and symbolic callees.
10598   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10599     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10600                                    /*isTarget=*/true);
10601   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10602     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10603                                          SDLoc(SymbolicCallee),
10604                                          SymbolicCallee->getValueType(0));
10605 
10606   // Get the real number of arguments participating in the call <numArgs>
10607   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10608   unsigned NumArgs = NArgVal->getAsZExtVal();
10609 
10610   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10611   // Intrinsics include all meta-operands up to but not including CC.
10612   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10613   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10614          "Not enough arguments provided to the patchpoint intrinsic");
10615 
10616   // For AnyRegCC the arguments are lowered later on manually.
10617   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10618   Type *ReturnTy =
10619       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10620 
10621   TargetLowering::CallLoweringInfo CLI(DAG);
10622   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10623                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10624   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10625 
10626   SDNode *CallEnd = Result.second.getNode();
10627   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10628     CallEnd = CallEnd->getOperand(0).getNode();
10629   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10630     CallEnd = CallEnd->getOperand(0).getNode();
10631 
10632   /// Get a call instruction from the call sequence chain.
10633   /// Tail calls are not allowed.
10634   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10635          "Expected a callseq node.");
10636   SDNode *Call = CallEnd->getOperand(0).getNode();
10637   bool HasGlue = Call->getGluedNode();
10638 
10639   // Replace the target specific call node with the patchable intrinsic.
10640   SmallVector<SDValue, 8> Ops;
10641 
10642   // Push the chain.
10643   Ops.push_back(*(Call->op_begin()));
10644 
10645   // Optionally, push the glue (if any).
10646   if (HasGlue)
10647     Ops.push_back(*(Call->op_end() - 1));
10648 
10649   // Push the register mask info.
10650   if (HasGlue)
10651     Ops.push_back(*(Call->op_end() - 2));
10652   else
10653     Ops.push_back(*(Call->op_end() - 1));
10654 
10655   // Add the <id> and <numBytes> constants.
10656   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10657   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10658   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10659   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10660 
10661   // Add the callee.
10662   Ops.push_back(Callee);
10663 
10664   // Adjust <numArgs> to account for any arguments that have been passed on the
10665   // stack instead.
10666   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10667   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10668   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10669   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10670 
10671   // Add the calling convention
10672   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10673 
10674   // Add the arguments we omitted previously. The register allocator should
10675   // place these in any free register.
10676   if (IsAnyRegCC)
10677     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10678       Ops.push_back(getValue(CB.getArgOperand(i)));
10679 
10680   // Push the arguments from the call instruction.
10681   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10682   Ops.append(Call->op_begin() + 2, e);
10683 
10684   // Push live variables for the stack map.
10685   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10686 
10687   SDVTList NodeTys;
10688   if (IsAnyRegCC && HasDef) {
10689     // Create the return types based on the intrinsic definition
10690     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10691     SmallVector<EVT, 3> ValueVTs;
10692     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10693     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10694 
10695     // There is always a chain and a glue type at the end
10696     ValueVTs.push_back(MVT::Other);
10697     ValueVTs.push_back(MVT::Glue);
10698     NodeTys = DAG.getVTList(ValueVTs);
10699   } else
10700     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10701 
10702   // Replace the target specific call node with a PATCHPOINT node.
10703   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10704 
10705   // Update the NodeMap.
10706   if (HasDef) {
10707     if (IsAnyRegCC)
10708       setValue(&CB, SDValue(PPV.getNode(), 0));
10709     else
10710       setValue(&CB, Result.first);
10711   }
10712 
10713   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10714   // call sequence. Furthermore the location of the chain and glue can change
10715   // when the AnyReg calling convention is used and the intrinsic returns a
10716   // value.
10717   if (IsAnyRegCC && HasDef) {
10718     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10719     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10720     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10721   } else
10722     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10723   DAG.DeleteNode(Call);
10724 
10725   // Inform the Frame Information that we have a patchpoint in this function.
10726   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10727 }
10728 
10729 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10730                                             unsigned Intrinsic) {
10731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10732   SDValue Op1 = getValue(I.getArgOperand(0));
10733   SDValue Op2;
10734   if (I.arg_size() > 1)
10735     Op2 = getValue(I.getArgOperand(1));
10736   SDLoc dl = getCurSDLoc();
10737   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10738   SDValue Res;
10739   SDNodeFlags SDFlags;
10740   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10741     SDFlags.copyFMF(*FPMO);
10742 
10743   switch (Intrinsic) {
10744   case Intrinsic::vector_reduce_fadd:
10745     if (SDFlags.hasAllowReassociation())
10746       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10747                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10748                         SDFlags);
10749     else
10750       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10751     break;
10752   case Intrinsic::vector_reduce_fmul:
10753     if (SDFlags.hasAllowReassociation())
10754       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10755                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10756                         SDFlags);
10757     else
10758       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10759     break;
10760   case Intrinsic::vector_reduce_add:
10761     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10762     break;
10763   case Intrinsic::vector_reduce_mul:
10764     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10765     break;
10766   case Intrinsic::vector_reduce_and:
10767     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10768     break;
10769   case Intrinsic::vector_reduce_or:
10770     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10771     break;
10772   case Intrinsic::vector_reduce_xor:
10773     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10774     break;
10775   case Intrinsic::vector_reduce_smax:
10776     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10777     break;
10778   case Intrinsic::vector_reduce_smin:
10779     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10780     break;
10781   case Intrinsic::vector_reduce_umax:
10782     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10783     break;
10784   case Intrinsic::vector_reduce_umin:
10785     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10786     break;
10787   case Intrinsic::vector_reduce_fmax:
10788     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10789     break;
10790   case Intrinsic::vector_reduce_fmin:
10791     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10792     break;
10793   case Intrinsic::vector_reduce_fmaximum:
10794     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10795     break;
10796   case Intrinsic::vector_reduce_fminimum:
10797     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10798     break;
10799   default:
10800     llvm_unreachable("Unhandled vector reduce intrinsic");
10801   }
10802   setValue(&I, Res);
10803 }
10804 
10805 /// Returns an AttributeList representing the attributes applied to the return
10806 /// value of the given call.
10807 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10808   SmallVector<Attribute::AttrKind, 2> Attrs;
10809   if (CLI.RetSExt)
10810     Attrs.push_back(Attribute::SExt);
10811   if (CLI.RetZExt)
10812     Attrs.push_back(Attribute::ZExt);
10813   if (CLI.IsInReg)
10814     Attrs.push_back(Attribute::InReg);
10815 
10816   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10817                             Attrs);
10818 }
10819 
10820 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10821 /// implementation, which just calls LowerCall.
10822 /// FIXME: When all targets are
10823 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10824 std::pair<SDValue, SDValue>
10825 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10826   // Handle the incoming return values from the call.
10827   CLI.Ins.clear();
10828   Type *OrigRetTy = CLI.RetTy;
10829   SmallVector<EVT, 4> RetTys;
10830   SmallVector<TypeSize, 4> Offsets;
10831   auto &DL = CLI.DAG.getDataLayout();
10832   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10833 
10834   if (CLI.IsPostTypeLegalization) {
10835     // If we are lowering a libcall after legalization, split the return type.
10836     SmallVector<EVT, 4> OldRetTys;
10837     SmallVector<TypeSize, 4> OldOffsets;
10838     RetTys.swap(OldRetTys);
10839     Offsets.swap(OldOffsets);
10840 
10841     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10842       EVT RetVT = OldRetTys[i];
10843       uint64_t Offset = OldOffsets[i];
10844       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10845       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10846       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10847       RetTys.append(NumRegs, RegisterVT);
10848       for (unsigned j = 0; j != NumRegs; ++j)
10849         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10850     }
10851   }
10852 
10853   SmallVector<ISD::OutputArg, 4> Outs;
10854   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10855 
10856   bool CanLowerReturn =
10857       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10858                            CLI.IsVarArg, Outs, CLI.RetTy->getContext());
10859 
10860   SDValue DemoteStackSlot;
10861   int DemoteStackIdx = -100;
10862   if (!CanLowerReturn) {
10863     // FIXME: equivalent assert?
10864     // assert(!CS.hasInAllocaArgument() &&
10865     //        "sret demotion is incompatible with inalloca");
10866     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10867     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
10868     MachineFunction &MF = CLI.DAG.getMachineFunction();
10869     DemoteStackIdx =
10870         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
10871     Type *StackSlotPtrType = PointerType::get(CLI.RetTy,
10872                                               DL.getAllocaAddrSpace());
10873 
10874     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
10875     ArgListEntry Entry;
10876     Entry.Node = DemoteStackSlot;
10877     Entry.Ty = StackSlotPtrType;
10878     Entry.IsSExt = false;
10879     Entry.IsZExt = false;
10880     Entry.IsInReg = false;
10881     Entry.IsSRet = true;
10882     Entry.IsNest = false;
10883     Entry.IsByVal = false;
10884     Entry.IsByRef = false;
10885     Entry.IsReturned = false;
10886     Entry.IsSwiftSelf = false;
10887     Entry.IsSwiftAsync = false;
10888     Entry.IsSwiftError = false;
10889     Entry.IsCFGuardTarget = false;
10890     Entry.Alignment = Alignment;
10891     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
10892     CLI.NumFixedArgs += 1;
10893     CLI.getArgs()[0].IndirectType = CLI.RetTy;
10894     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
10895 
10896     // sret demotion isn't compatible with tail-calls, since the sret argument
10897     // points into the callers stack frame.
10898     CLI.IsTailCall = false;
10899   } else {
10900     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10901         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
10902     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
10903       ISD::ArgFlagsTy Flags;
10904       if (NeedsRegBlock) {
10905         Flags.setInConsecutiveRegs();
10906         if (I == RetTys.size() - 1)
10907           Flags.setInConsecutiveRegsLast();
10908       }
10909       EVT VT = RetTys[I];
10910       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
10911                                                      CLI.CallConv, VT);
10912       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
10913                                                        CLI.CallConv, VT);
10914       for (unsigned i = 0; i != NumRegs; ++i) {
10915         ISD::InputArg MyFlags;
10916         MyFlags.Flags = Flags;
10917         MyFlags.VT = RegisterVT;
10918         MyFlags.ArgVT = VT;
10919         MyFlags.Used = CLI.IsReturnValueUsed;
10920         if (CLI.RetTy->isPointerTy()) {
10921           MyFlags.Flags.setPointer();
10922           MyFlags.Flags.setPointerAddrSpace(
10923               cast<PointerType>(CLI.RetTy)->getAddressSpace());
10924         }
10925         if (CLI.RetSExt)
10926           MyFlags.Flags.setSExt();
10927         if (CLI.RetZExt)
10928           MyFlags.Flags.setZExt();
10929         if (CLI.IsInReg)
10930           MyFlags.Flags.setInReg();
10931         CLI.Ins.push_back(MyFlags);
10932       }
10933     }
10934   }
10935 
10936   // We push in swifterror return as the last element of CLI.Ins.
10937   ArgListTy &Args = CLI.getArgs();
10938   if (supportSwiftError()) {
10939     for (const ArgListEntry &Arg : Args) {
10940       if (Arg.IsSwiftError) {
10941         ISD::InputArg MyFlags;
10942         MyFlags.VT = getPointerTy(DL);
10943         MyFlags.ArgVT = EVT(getPointerTy(DL));
10944         MyFlags.Flags.setSwiftError();
10945         CLI.Ins.push_back(MyFlags);
10946       }
10947     }
10948   }
10949 
10950   // Handle all of the outgoing arguments.
10951   CLI.Outs.clear();
10952   CLI.OutVals.clear();
10953   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
10954     SmallVector<EVT, 4> ValueVTs;
10955     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
10956     // FIXME: Split arguments if CLI.IsPostTypeLegalization
10957     Type *FinalType = Args[i].Ty;
10958     if (Args[i].IsByVal)
10959       FinalType = Args[i].IndirectType;
10960     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
10961         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
10962     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
10963          ++Value) {
10964       EVT VT = ValueVTs[Value];
10965       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
10966       SDValue Op = SDValue(Args[i].Node.getNode(),
10967                            Args[i].Node.getResNo() + Value);
10968       ISD::ArgFlagsTy Flags;
10969 
10970       // Certain targets (such as MIPS), may have a different ABI alignment
10971       // for a type depending on the context. Give the target a chance to
10972       // specify the alignment it wants.
10973       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
10974       Flags.setOrigAlign(OriginalAlignment);
10975 
10976       if (Args[i].Ty->isPointerTy()) {
10977         Flags.setPointer();
10978         Flags.setPointerAddrSpace(
10979             cast<PointerType>(Args[i].Ty)->getAddressSpace());
10980       }
10981       if (Args[i].IsZExt)
10982         Flags.setZExt();
10983       if (Args[i].IsSExt)
10984         Flags.setSExt();
10985       if (Args[i].IsInReg) {
10986         // If we are using vectorcall calling convention, a structure that is
10987         // passed InReg - is surely an HVA
10988         if (CLI.CallConv == CallingConv::X86_VectorCall &&
10989             isa<StructType>(FinalType)) {
10990           // The first value of a structure is marked
10991           if (0 == Value)
10992             Flags.setHvaStart();
10993           Flags.setHva();
10994         }
10995         // Set InReg Flag
10996         Flags.setInReg();
10997       }
10998       if (Args[i].IsSRet)
10999         Flags.setSRet();
11000       if (Args[i].IsSwiftSelf)
11001         Flags.setSwiftSelf();
11002       if (Args[i].IsSwiftAsync)
11003         Flags.setSwiftAsync();
11004       if (Args[i].IsSwiftError)
11005         Flags.setSwiftError();
11006       if (Args[i].IsCFGuardTarget)
11007         Flags.setCFGuardTarget();
11008       if (Args[i].IsByVal)
11009         Flags.setByVal();
11010       if (Args[i].IsByRef)
11011         Flags.setByRef();
11012       if (Args[i].IsPreallocated) {
11013         Flags.setPreallocated();
11014         // Set the byval flag for CCAssignFn callbacks that don't know about
11015         // preallocated.  This way we can know how many bytes we should've
11016         // allocated and how many bytes a callee cleanup function will pop.  If
11017         // we port preallocated to more targets, we'll have to add custom
11018         // preallocated handling in the various CC lowering callbacks.
11019         Flags.setByVal();
11020       }
11021       if (Args[i].IsInAlloca) {
11022         Flags.setInAlloca();
11023         // Set the byval flag for CCAssignFn callbacks that don't know about
11024         // inalloca.  This way we can know how many bytes we should've allocated
11025         // and how many bytes a callee cleanup function will pop.  If we port
11026         // inalloca to more targets, we'll have to add custom inalloca handling
11027         // in the various CC lowering callbacks.
11028         Flags.setByVal();
11029       }
11030       Align MemAlign;
11031       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11032         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11033         Flags.setByValSize(FrameSize);
11034 
11035         // info is not there but there are cases it cannot get right.
11036         if (auto MA = Args[i].Alignment)
11037           MemAlign = *MA;
11038         else
11039           MemAlign = Align(getByValTypeAlignment(Args[i].IndirectType, DL));
11040       } else if (auto MA = Args[i].Alignment) {
11041         MemAlign = *MA;
11042       } else {
11043         MemAlign = OriginalAlignment;
11044       }
11045       Flags.setMemAlign(MemAlign);
11046       if (Args[i].IsNest)
11047         Flags.setNest();
11048       if (NeedsRegBlock)
11049         Flags.setInConsecutiveRegs();
11050 
11051       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11052                                                  CLI.CallConv, VT);
11053       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11054                                                         CLI.CallConv, VT);
11055       SmallVector<SDValue, 4> Parts(NumParts);
11056       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11057 
11058       if (Args[i].IsSExt)
11059         ExtendKind = ISD::SIGN_EXTEND;
11060       else if (Args[i].IsZExt)
11061         ExtendKind = ISD::ZERO_EXTEND;
11062 
11063       // Conservatively only handle 'returned' on non-vectors that can be lowered,
11064       // for now.
11065       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11066           CanLowerReturn) {
11067         assert((CLI.RetTy == Args[i].Ty ||
11068                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11069                  CLI.RetTy->getPointerAddressSpace() ==
11070                      Args[i].Ty->getPointerAddressSpace())) &&
11071                RetTys.size() == NumValues && "unexpected use of 'returned'");
11072         // Before passing 'returned' to the target lowering code, ensure that
11073         // either the register MVT and the actual EVT are the same size or that
11074         // the return value and argument are extended in the same way; in these
11075         // cases it's safe to pass the argument register value unchanged as the
11076         // return register value (although it's at the target's option whether
11077         // to do so)
11078         // TODO: allow code generation to take advantage of partially preserved
11079         // registers rather than clobbering the entire register when the
11080         // parameter extension method is not compatible with the return
11081         // extension method
11082         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11083             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11084              CLI.RetZExt == Args[i].IsZExt))
11085           Flags.setReturned();
11086       }
11087 
11088       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11089                      CLI.CallConv, ExtendKind);
11090 
11091       for (unsigned j = 0; j != NumParts; ++j) {
11092         // if it isn't first piece, alignment must be 1
11093         // For scalable vectors the scalable part is currently handled
11094         // by individual targets, so we just use the known minimum size here.
11095         ISD::OutputArg MyFlags(
11096             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11097             i < CLI.NumFixedArgs, i,
11098             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11099         if (NumParts > 1 && j == 0)
11100           MyFlags.Flags.setSplit();
11101         else if (j != 0) {
11102           MyFlags.Flags.setOrigAlign(Align(1));
11103           if (j == NumParts - 1)
11104             MyFlags.Flags.setSplitEnd();
11105         }
11106 
11107         CLI.Outs.push_back(MyFlags);
11108         CLI.OutVals.push_back(Parts[j]);
11109       }
11110 
11111       if (NeedsRegBlock && Value == NumValues - 1)
11112         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11113     }
11114   }
11115 
11116   SmallVector<SDValue, 4> InVals;
11117   CLI.Chain = LowerCall(CLI, InVals);
11118 
11119   // Update CLI.InVals to use outside of this function.
11120   CLI.InVals = InVals;
11121 
11122   // Verify that the target's LowerCall behaved as expected.
11123   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11124          "LowerCall didn't return a valid chain!");
11125   assert((!CLI.IsTailCall || InVals.empty()) &&
11126          "LowerCall emitted a return value for a tail call!");
11127   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11128          "LowerCall didn't emit the correct number of values!");
11129 
11130   // For a tail call, the return value is merely live-out and there aren't
11131   // any nodes in the DAG representing it. Return a special value to
11132   // indicate that a tail call has been emitted and no more Instructions
11133   // should be processed in the current block.
11134   if (CLI.IsTailCall) {
11135     CLI.DAG.setRoot(CLI.Chain);
11136     return std::make_pair(SDValue(), SDValue());
11137   }
11138 
11139 #ifndef NDEBUG
11140   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11141     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11142     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11143            "LowerCall emitted a value with the wrong type!");
11144   }
11145 #endif
11146 
11147   SmallVector<SDValue, 4> ReturnValues;
11148   if (!CanLowerReturn) {
11149     // The instruction result is the result of loading from the
11150     // hidden sret parameter.
11151     SmallVector<EVT, 1> PVTs;
11152     Type *PtrRetTy =
11153         PointerType::get(OrigRetTy->getContext(), DL.getAllocaAddrSpace());
11154 
11155     ComputeValueVTs(*this, DL, PtrRetTy, PVTs);
11156     assert(PVTs.size() == 1 && "Pointers should fit in one register");
11157     EVT PtrVT = PVTs[0];
11158 
11159     unsigned NumValues = RetTys.size();
11160     ReturnValues.resize(NumValues);
11161     SmallVector<SDValue, 4> Chains(NumValues);
11162 
11163     // An aggregate return value cannot wrap around the address space, so
11164     // offsets to its parts don't wrap either.
11165     SDNodeFlags Flags;
11166     Flags.setNoUnsignedWrap(true);
11167 
11168     MachineFunction &MF = CLI.DAG.getMachineFunction();
11169     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11170     for (unsigned i = 0; i < NumValues; ++i) {
11171       SDValue Add = CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11172                                     CLI.DAG.getConstant(Offsets[i], CLI.DL,
11173                                                         PtrVT), Flags);
11174       SDValue L = CLI.DAG.getLoad(
11175           RetTys[i], CLI.DL, CLI.Chain, Add,
11176           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11177                                             DemoteStackIdx, Offsets[i]),
11178           HiddenSRetAlign);
11179       ReturnValues[i] = L;
11180       Chains[i] = L.getValue(1);
11181     }
11182 
11183     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11184   } else {
11185     // Collect the legal value parts into potentially illegal values
11186     // that correspond to the original function's return values.
11187     std::optional<ISD::NodeType> AssertOp;
11188     if (CLI.RetSExt)
11189       AssertOp = ISD::AssertSext;
11190     else if (CLI.RetZExt)
11191       AssertOp = ISD::AssertZext;
11192     unsigned CurReg = 0;
11193     for (EVT VT : RetTys) {
11194       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11195                                                      CLI.CallConv, VT);
11196       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11197                                                        CLI.CallConv, VT);
11198 
11199       ReturnValues.push_back(getCopyFromParts(
11200           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11201           CLI.Chain, CLI.CallConv, AssertOp));
11202       CurReg += NumRegs;
11203     }
11204 
11205     // For a function returning void, there is no return value. We can't create
11206     // such a node, so we just return a null return value in that case. In
11207     // that case, nothing will actually look at the value.
11208     if (ReturnValues.empty())
11209       return std::make_pair(SDValue(), CLI.Chain);
11210   }
11211 
11212   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11213                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11214   return std::make_pair(Res, CLI.Chain);
11215 }
11216 
11217 /// Places new result values for the node in Results (their number
11218 /// and types must exactly match those of the original return values of
11219 /// the node), or leaves Results empty, which indicates that the node is not
11220 /// to be custom lowered after all.
11221 void TargetLowering::LowerOperationWrapper(SDNode *N,
11222                                            SmallVectorImpl<SDValue> &Results,
11223                                            SelectionDAG &DAG) const {
11224   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11225 
11226   if (!Res.getNode())
11227     return;
11228 
11229   // If the original node has one result, take the return value from
11230   // LowerOperation as is. It might not be result number 0.
11231   if (N->getNumValues() == 1) {
11232     Results.push_back(Res);
11233     return;
11234   }
11235 
11236   // If the original node has multiple results, then the return node should
11237   // have the same number of results.
11238   assert((N->getNumValues() == Res->getNumValues()) &&
11239       "Lowering returned the wrong number of results!");
11240 
11241   // Places new result values base on N result number.
11242   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11243     Results.push_back(Res.getValue(I));
11244 }
11245 
11246 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11247   llvm_unreachable("LowerOperation not implemented for this target!");
11248 }
11249 
11250 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11251                                                      unsigned Reg,
11252                                                      ISD::NodeType ExtendType) {
11253   SDValue Op = getNonRegisterValue(V);
11254   assert((Op.getOpcode() != ISD::CopyFromReg ||
11255           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11256          "Copy from a reg to the same reg!");
11257   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11258 
11259   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11260   // If this is an InlineAsm we have to match the registers required, not the
11261   // notional registers required by the type.
11262 
11263   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11264                    std::nullopt); // This is not an ABI copy.
11265   SDValue Chain = DAG.getEntryNode();
11266 
11267   if (ExtendType == ISD::ANY_EXTEND) {
11268     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11269     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11270       ExtendType = PreferredExtendIt->second;
11271   }
11272   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11273   PendingExports.push_back(Chain);
11274 }
11275 
11276 #include "llvm/CodeGen/SelectionDAGISel.h"
11277 
11278 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11279 /// entry block, return true.  This includes arguments used by switches, since
11280 /// the switch may expand into multiple basic blocks.
11281 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11282   // With FastISel active, we may be splitting blocks, so force creation
11283   // of virtual registers for all non-dead arguments.
11284   if (FastISel)
11285     return A->use_empty();
11286 
11287   const BasicBlock &Entry = A->getParent()->front();
11288   for (const User *U : A->users())
11289     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11290       return false;  // Use not in entry block.
11291 
11292   return true;
11293 }
11294 
11295 using ArgCopyElisionMapTy =
11296     DenseMap<const Argument *,
11297              std::pair<const AllocaInst *, const StoreInst *>>;
11298 
11299 /// Scan the entry block of the function in FuncInfo for arguments that look
11300 /// like copies into a local alloca. Record any copied arguments in
11301 /// ArgCopyElisionCandidates.
11302 static void
11303 findArgumentCopyElisionCandidates(const DataLayout &DL,
11304                                   FunctionLoweringInfo *FuncInfo,
11305                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11306   // Record the state of every static alloca used in the entry block. Argument
11307   // allocas are all used in the entry block, so we need approximately as many
11308   // entries as we have arguments.
11309   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11310   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11311   unsigned NumArgs = FuncInfo->Fn->arg_size();
11312   StaticAllocas.reserve(NumArgs * 2);
11313 
11314   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11315     if (!V)
11316       return nullptr;
11317     V = V->stripPointerCasts();
11318     const auto *AI = dyn_cast<AllocaInst>(V);
11319     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11320       return nullptr;
11321     auto Iter = StaticAllocas.insert({AI, Unknown});
11322     return &Iter.first->second;
11323   };
11324 
11325   // Look for stores of arguments to static allocas. Look through bitcasts and
11326   // GEPs to handle type coercions, as long as the alloca is fully initialized
11327   // by the store. Any non-store use of an alloca escapes it and any subsequent
11328   // unanalyzed store might write it.
11329   // FIXME: Handle structs initialized with multiple stores.
11330   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11331     // Look for stores, and handle non-store uses conservatively.
11332     const auto *SI = dyn_cast<StoreInst>(&I);
11333     if (!SI) {
11334       // We will look through cast uses, so ignore them completely.
11335       if (I.isCast())
11336         continue;
11337       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11338       // to allocas.
11339       if (I.isDebugOrPseudoInst())
11340         continue;
11341       // This is an unknown instruction. Assume it escapes or writes to all
11342       // static alloca operands.
11343       for (const Use &U : I.operands()) {
11344         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11345           *Info = StaticAllocaInfo::Clobbered;
11346       }
11347       continue;
11348     }
11349 
11350     // If the stored value is a static alloca, mark it as escaped.
11351     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11352       *Info = StaticAllocaInfo::Clobbered;
11353 
11354     // Check if the destination is a static alloca.
11355     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11356     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11357     if (!Info)
11358       continue;
11359     const AllocaInst *AI = cast<AllocaInst>(Dst);
11360 
11361     // Skip allocas that have been initialized or clobbered.
11362     if (*Info != StaticAllocaInfo::Unknown)
11363       continue;
11364 
11365     // Check if the stored value is an argument, and that this store fully
11366     // initializes the alloca.
11367     // If the argument type has padding bits we can't directly forward a pointer
11368     // as the upper bits may contain garbage.
11369     // Don't elide copies from the same argument twice.
11370     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11371     const auto *Arg = dyn_cast<Argument>(Val);
11372     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11373         Arg->getType()->isEmptyTy() ||
11374         DL.getTypeStoreSize(Arg->getType()) !=
11375             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11376         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11377         ArgCopyElisionCandidates.count(Arg)) {
11378       *Info = StaticAllocaInfo::Clobbered;
11379       continue;
11380     }
11381 
11382     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11383                       << '\n');
11384 
11385     // Mark this alloca and store for argument copy elision.
11386     *Info = StaticAllocaInfo::Elidable;
11387     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11388 
11389     // Stop scanning if we've seen all arguments. This will happen early in -O0
11390     // builds, which is useful, because -O0 builds have large entry blocks and
11391     // many allocas.
11392     if (ArgCopyElisionCandidates.size() == NumArgs)
11393       break;
11394   }
11395 }
11396 
11397 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11398 /// ArgVal is a load from a suitable fixed stack object.
11399 static void tryToElideArgumentCopy(
11400     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11401     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11402     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11403     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11404     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11405   // Check if this is a load from a fixed stack object.
11406   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11407   if (!LNode)
11408     return;
11409   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11410   if (!FINode)
11411     return;
11412 
11413   // Check that the fixed stack object is the right size and alignment.
11414   // Look at the alignment that the user wrote on the alloca instead of looking
11415   // at the stack object.
11416   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11417   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11418   const AllocaInst *AI = ArgCopyIter->second.first;
11419   int FixedIndex = FINode->getIndex();
11420   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11421   int OldIndex = AllocaIndex;
11422   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11423   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11424     LLVM_DEBUG(
11425         dbgs() << "  argument copy elision failed due to bad fixed stack "
11426                   "object size\n");
11427     return;
11428   }
11429   Align RequiredAlignment = AI->getAlign();
11430   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11431     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11432                          "greater than stack argument alignment ("
11433                       << DebugStr(RequiredAlignment) << " vs "
11434                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11435     return;
11436   }
11437 
11438   // Perform the elision. Delete the old stack object and replace its only use
11439   // in the variable info map. Mark the stack object as mutable and aliased.
11440   LLVM_DEBUG({
11441     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11442            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11443            << '\n';
11444   });
11445   MFI.RemoveStackObject(OldIndex);
11446   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11447   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11448   AllocaIndex = FixedIndex;
11449   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11450   for (SDValue ArgVal : ArgVals)
11451     Chains.push_back(ArgVal.getValue(1));
11452 
11453   // Avoid emitting code for the store implementing the copy.
11454   const StoreInst *SI = ArgCopyIter->second.second;
11455   ElidedArgCopyInstrs.insert(SI);
11456 
11457   // Check for uses of the argument again so that we can avoid exporting ArgVal
11458   // if it is't used by anything other than the store.
11459   for (const Value *U : Arg.users()) {
11460     if (U != SI) {
11461       ArgHasUses = true;
11462       break;
11463     }
11464   }
11465 }
11466 
11467 void SelectionDAGISel::LowerArguments(const Function &F) {
11468   SelectionDAG &DAG = SDB->DAG;
11469   SDLoc dl = SDB->getCurSDLoc();
11470   const DataLayout &DL = DAG.getDataLayout();
11471   SmallVector<ISD::InputArg, 16> Ins;
11472 
11473   // In Naked functions we aren't going to save any registers.
11474   if (F.hasFnAttribute(Attribute::Naked))
11475     return;
11476 
11477   if (!FuncInfo->CanLowerReturn) {
11478     // Put in an sret pointer parameter before all the other parameters.
11479     SmallVector<EVT, 1> ValueVTs;
11480     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11481                     PointerType::get(F.getContext(),
11482                                      DAG.getDataLayout().getAllocaAddrSpace()),
11483                     ValueVTs);
11484 
11485     // NOTE: Assuming that a pointer will never break down to more than one VT
11486     // or one register.
11487     ISD::ArgFlagsTy Flags;
11488     Flags.setSRet();
11489     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVTs[0]);
11490     ISD::InputArg RetArg(Flags, RegisterVT, ValueVTs[0], true,
11491                          ISD::InputArg::NoArgIndex, 0);
11492     Ins.push_back(RetArg);
11493   }
11494 
11495   // Look for stores of arguments to static allocas. Mark such arguments with a
11496   // flag to ask the target to give us the memory location of that argument if
11497   // available.
11498   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11499   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11500                                     ArgCopyElisionCandidates);
11501 
11502   // Set up the incoming argument description vector.
11503   for (const Argument &Arg : F.args()) {
11504     unsigned ArgNo = Arg.getArgNo();
11505     SmallVector<EVT, 4> ValueVTs;
11506     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11507     bool isArgValueUsed = !Arg.use_empty();
11508     unsigned PartBase = 0;
11509     Type *FinalType = Arg.getType();
11510     if (Arg.hasAttribute(Attribute::ByVal))
11511       FinalType = Arg.getParamByValType();
11512     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11513         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11514     for (unsigned Value = 0, NumValues = ValueVTs.size();
11515          Value != NumValues; ++Value) {
11516       EVT VT = ValueVTs[Value];
11517       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11518       ISD::ArgFlagsTy Flags;
11519 
11520 
11521       if (Arg.getType()->isPointerTy()) {
11522         Flags.setPointer();
11523         Flags.setPointerAddrSpace(
11524             cast<PointerType>(Arg.getType())->getAddressSpace());
11525       }
11526       if (Arg.hasAttribute(Attribute::ZExt))
11527         Flags.setZExt();
11528       if (Arg.hasAttribute(Attribute::SExt))
11529         Flags.setSExt();
11530       if (Arg.hasAttribute(Attribute::InReg)) {
11531         // If we are using vectorcall calling convention, a structure that is
11532         // passed InReg - is surely an HVA
11533         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11534             isa<StructType>(Arg.getType())) {
11535           // The first value of a structure is marked
11536           if (0 == Value)
11537             Flags.setHvaStart();
11538           Flags.setHva();
11539         }
11540         // Set InReg Flag
11541         Flags.setInReg();
11542       }
11543       if (Arg.hasAttribute(Attribute::StructRet))
11544         Flags.setSRet();
11545       if (Arg.hasAttribute(Attribute::SwiftSelf))
11546         Flags.setSwiftSelf();
11547       if (Arg.hasAttribute(Attribute::SwiftAsync))
11548         Flags.setSwiftAsync();
11549       if (Arg.hasAttribute(Attribute::SwiftError))
11550         Flags.setSwiftError();
11551       if (Arg.hasAttribute(Attribute::ByVal))
11552         Flags.setByVal();
11553       if (Arg.hasAttribute(Attribute::ByRef))
11554         Flags.setByRef();
11555       if (Arg.hasAttribute(Attribute::InAlloca)) {
11556         Flags.setInAlloca();
11557         // Set the byval flag for CCAssignFn callbacks that don't know about
11558         // inalloca.  This way we can know how many bytes we should've allocated
11559         // and how many bytes a callee cleanup function will pop.  If we port
11560         // inalloca to more targets, we'll have to add custom inalloca handling
11561         // in the various CC lowering callbacks.
11562         Flags.setByVal();
11563       }
11564       if (Arg.hasAttribute(Attribute::Preallocated)) {
11565         Flags.setPreallocated();
11566         // Set the byval flag for CCAssignFn callbacks that don't know about
11567         // preallocated.  This way we can know how many bytes we should've
11568         // allocated and how many bytes a callee cleanup function will pop.  If
11569         // we port preallocated to more targets, we'll have to add custom
11570         // preallocated handling in the various CC lowering callbacks.
11571         Flags.setByVal();
11572       }
11573 
11574       // Certain targets (such as MIPS), may have a different ABI alignment
11575       // for a type depending on the context. Give the target a chance to
11576       // specify the alignment it wants.
11577       const Align OriginalAlignment(
11578           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11579       Flags.setOrigAlign(OriginalAlignment);
11580 
11581       Align MemAlign;
11582       Type *ArgMemTy = nullptr;
11583       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11584           Flags.isByRef()) {
11585         if (!ArgMemTy)
11586           ArgMemTy = Arg.getPointeeInMemoryValueType();
11587 
11588         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11589 
11590         // For in-memory arguments, size and alignment should be passed from FE.
11591         // BE will guess if this info is not there but there are cases it cannot
11592         // get right.
11593         if (auto ParamAlign = Arg.getParamStackAlign())
11594           MemAlign = *ParamAlign;
11595         else if ((ParamAlign = Arg.getParamAlign()))
11596           MemAlign = *ParamAlign;
11597         else
11598           MemAlign = Align(TLI->getByValTypeAlignment(ArgMemTy, DL));
11599         if (Flags.isByRef())
11600           Flags.setByRefSize(MemSize);
11601         else
11602           Flags.setByValSize(MemSize);
11603       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11604         MemAlign = *ParamAlign;
11605       } else {
11606         MemAlign = OriginalAlignment;
11607       }
11608       Flags.setMemAlign(MemAlign);
11609 
11610       if (Arg.hasAttribute(Attribute::Nest))
11611         Flags.setNest();
11612       if (NeedsRegBlock)
11613         Flags.setInConsecutiveRegs();
11614       if (ArgCopyElisionCandidates.count(&Arg))
11615         Flags.setCopyElisionCandidate();
11616       if (Arg.hasAttribute(Attribute::Returned))
11617         Flags.setReturned();
11618 
11619       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11620           *CurDAG->getContext(), F.getCallingConv(), VT);
11621       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11622           *CurDAG->getContext(), F.getCallingConv(), VT);
11623       for (unsigned i = 0; i != NumRegs; ++i) {
11624         // For scalable vectors, use the minimum size; individual targets
11625         // are responsible for handling scalable vector arguments and
11626         // return values.
11627         ISD::InputArg MyFlags(
11628             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11629             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11630         if (NumRegs > 1 && i == 0)
11631           MyFlags.Flags.setSplit();
11632         // if it isn't first piece, alignment must be 1
11633         else if (i > 0) {
11634           MyFlags.Flags.setOrigAlign(Align(1));
11635           if (i == NumRegs - 1)
11636             MyFlags.Flags.setSplitEnd();
11637         }
11638         Ins.push_back(MyFlags);
11639       }
11640       if (NeedsRegBlock && Value == NumValues - 1)
11641         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11642       PartBase += VT.getStoreSize().getKnownMinValue();
11643     }
11644   }
11645 
11646   // Call the target to set up the argument values.
11647   SmallVector<SDValue, 8> InVals;
11648   SDValue NewRoot = TLI->LowerFormalArguments(
11649       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11650 
11651   // Verify that the target's LowerFormalArguments behaved as expected.
11652   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11653          "LowerFormalArguments didn't return a valid chain!");
11654   assert(InVals.size() == Ins.size() &&
11655          "LowerFormalArguments didn't emit the correct number of values!");
11656   LLVM_DEBUG({
11657     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11658       assert(InVals[i].getNode() &&
11659              "LowerFormalArguments emitted a null value!");
11660       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11661              "LowerFormalArguments emitted a value with the wrong type!");
11662     }
11663   });
11664 
11665   // Update the DAG with the new chain value resulting from argument lowering.
11666   DAG.setRoot(NewRoot);
11667 
11668   // Set up the argument values.
11669   unsigned i = 0;
11670   if (!FuncInfo->CanLowerReturn) {
11671     // Create a virtual register for the sret pointer, and put in a copy
11672     // from the sret argument into it.
11673     SmallVector<EVT, 1> ValueVTs;
11674     ComputeValueVTs(*TLI, DAG.getDataLayout(),
11675                     PointerType::get(F.getContext(),
11676                                      DAG.getDataLayout().getAllocaAddrSpace()),
11677                     ValueVTs);
11678     MVT VT = ValueVTs[0].getSimpleVT();
11679     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11680     std::optional<ISD::NodeType> AssertOp;
11681     SDValue ArgValue =
11682         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11683                          F.getCallingConv(), AssertOp);
11684 
11685     MachineFunction& MF = SDB->DAG.getMachineFunction();
11686     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11687     Register SRetReg =
11688         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11689     FuncInfo->DemoteRegister = SRetReg;
11690     NewRoot =
11691         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11692     DAG.setRoot(NewRoot);
11693 
11694     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11695     ++i;
11696   }
11697 
11698   SmallVector<SDValue, 4> Chains;
11699   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11700   for (const Argument &Arg : F.args()) {
11701     SmallVector<SDValue, 4> ArgValues;
11702     SmallVector<EVT, 4> ValueVTs;
11703     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11704     unsigned NumValues = ValueVTs.size();
11705     if (NumValues == 0)
11706       continue;
11707 
11708     bool ArgHasUses = !Arg.use_empty();
11709 
11710     // Elide the copying store if the target loaded this argument from a
11711     // suitable fixed stack object.
11712     if (Ins[i].Flags.isCopyElisionCandidate()) {
11713       unsigned NumParts = 0;
11714       for (EVT VT : ValueVTs)
11715         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11716                                                        F.getCallingConv(), VT);
11717 
11718       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11719                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11720                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11721     }
11722 
11723     // If this argument is unused then remember its value. It is used to generate
11724     // debugging information.
11725     bool isSwiftErrorArg =
11726         TLI->supportSwiftError() &&
11727         Arg.hasAttribute(Attribute::SwiftError);
11728     if (!ArgHasUses && !isSwiftErrorArg) {
11729       SDB->setUnusedArgValue(&Arg, InVals[i]);
11730 
11731       // Also remember any frame index for use in FastISel.
11732       if (FrameIndexSDNode *FI =
11733           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11734         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11735     }
11736 
11737     for (unsigned Val = 0; Val != NumValues; ++Val) {
11738       EVT VT = ValueVTs[Val];
11739       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11740                                                       F.getCallingConv(), VT);
11741       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11742           *CurDAG->getContext(), F.getCallingConv(), VT);
11743 
11744       // Even an apparent 'unused' swifterror argument needs to be returned. So
11745       // we do generate a copy for it that can be used on return from the
11746       // function.
11747       if (ArgHasUses || isSwiftErrorArg) {
11748         std::optional<ISD::NodeType> AssertOp;
11749         if (Arg.hasAttribute(Attribute::SExt))
11750           AssertOp = ISD::AssertSext;
11751         else if (Arg.hasAttribute(Attribute::ZExt))
11752           AssertOp = ISD::AssertZext;
11753 
11754         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11755                                              PartVT, VT, nullptr, NewRoot,
11756                                              F.getCallingConv(), AssertOp));
11757       }
11758 
11759       i += NumParts;
11760     }
11761 
11762     // We don't need to do anything else for unused arguments.
11763     if (ArgValues.empty())
11764       continue;
11765 
11766     // Note down frame index.
11767     if (FrameIndexSDNode *FI =
11768         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11769       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11770 
11771     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11772                                      SDB->getCurSDLoc());
11773 
11774     SDB->setValue(&Arg, Res);
11775     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11776       // We want to associate the argument with the frame index, among
11777       // involved operands, that correspond to the lowest address. The
11778       // getCopyFromParts function, called earlier, is swapping the order of
11779       // the operands to BUILD_PAIR depending on endianness. The result of
11780       // that swapping is that the least significant bits of the argument will
11781       // be in the first operand of the BUILD_PAIR node, and the most
11782       // significant bits will be in the second operand.
11783       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11784       if (LoadSDNode *LNode =
11785           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11786         if (FrameIndexSDNode *FI =
11787             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11788           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11789     }
11790 
11791     // Analyses past this point are naive and don't expect an assertion.
11792     if (Res.getOpcode() == ISD::AssertZext)
11793       Res = Res.getOperand(0);
11794 
11795     // Update the SwiftErrorVRegDefMap.
11796     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11797       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11798       if (Register::isVirtualRegister(Reg))
11799         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11800                                    Reg);
11801     }
11802 
11803     // If this argument is live outside of the entry block, insert a copy from
11804     // wherever we got it to the vreg that other BB's will reference it as.
11805     if (Res.getOpcode() == ISD::CopyFromReg) {
11806       // If we can, though, try to skip creating an unnecessary vreg.
11807       // FIXME: This isn't very clean... it would be nice to make this more
11808       // general.
11809       unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11810       if (Register::isVirtualRegister(Reg)) {
11811         FuncInfo->ValueMap[&Arg] = Reg;
11812         continue;
11813       }
11814     }
11815     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11816       FuncInfo->InitializeRegForValue(&Arg);
11817       SDB->CopyToExportRegsIfNeeded(&Arg);
11818     }
11819   }
11820 
11821   if (!Chains.empty()) {
11822     Chains.push_back(NewRoot);
11823     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11824   }
11825 
11826   DAG.setRoot(NewRoot);
11827 
11828   assert(i == InVals.size() && "Argument register count mismatch!");
11829 
11830   // If any argument copy elisions occurred and we have debug info, update the
11831   // stale frame indices used in the dbg.declare variable info table.
11832   if (!ArgCopyElisionFrameIndexMap.empty()) {
11833     for (MachineFunction::VariableDbgInfo &VI :
11834          MF->getInStackSlotVariableDbgInfo()) {
11835       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11836       if (I != ArgCopyElisionFrameIndexMap.end())
11837         VI.updateStackSlot(I->second);
11838     }
11839   }
11840 
11841   // Finally, if the target has anything special to do, allow it to do so.
11842   emitFunctionEntryCode();
11843 }
11844 
11845 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11846 /// ensure constants are generated when needed.  Remember the virtual registers
11847 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11848 /// directly add them, because expansion might result in multiple MBB's for one
11849 /// BB.  As such, the start of the BB might correspond to a different MBB than
11850 /// the end.
11851 void
11852 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11853   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11854 
11855   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11856 
11857   // Check PHI nodes in successors that expect a value to be available from this
11858   // block.
11859   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11860     if (!isa<PHINode>(SuccBB->begin())) continue;
11861     MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
11862 
11863     // If this terminator has multiple identical successors (common for
11864     // switches), only handle each succ once.
11865     if (!SuccsHandled.insert(SuccMBB).second)
11866       continue;
11867 
11868     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11869 
11870     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11871     // nodes and Machine PHI nodes, but the incoming operands have not been
11872     // emitted yet.
11873     for (const PHINode &PN : SuccBB->phis()) {
11874       // Ignore dead phi's.
11875       if (PN.use_empty())
11876         continue;
11877 
11878       // Skip empty types
11879       if (PN.getType()->isEmptyTy())
11880         continue;
11881 
11882       unsigned Reg;
11883       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11884 
11885       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
11886         unsigned &RegOut = ConstantsOut[C];
11887         if (RegOut == 0) {
11888           RegOut = FuncInfo.CreateRegs(C);
11889           // We need to zero/sign extend ConstantInt phi operands to match
11890           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
11891           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
11892           if (auto *CI = dyn_cast<ConstantInt>(C))
11893             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
11894                                                     : ISD::ZERO_EXTEND;
11895           CopyValueToVirtualRegister(C, RegOut, ExtendType);
11896         }
11897         Reg = RegOut;
11898       } else {
11899         DenseMap<const Value *, Register>::iterator I =
11900           FuncInfo.ValueMap.find(PHIOp);
11901         if (I != FuncInfo.ValueMap.end())
11902           Reg = I->second;
11903         else {
11904           assert(isa<AllocaInst>(PHIOp) &&
11905                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
11906                  "Didn't codegen value into a register!??");
11907           Reg = FuncInfo.CreateRegs(PHIOp);
11908           CopyValueToVirtualRegister(PHIOp, Reg);
11909         }
11910       }
11911 
11912       // Remember that this register needs to added to the machine PHI node as
11913       // the input for this MBB.
11914       SmallVector<EVT, 4> ValueVTs;
11915       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
11916       for (EVT VT : ValueVTs) {
11917         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
11918         for (unsigned i = 0; i != NumRegisters; ++i)
11919           FuncInfo.PHINodesToUpdate.push_back(
11920               std::make_pair(&*MBBI++, Reg + i));
11921         Reg += NumRegisters;
11922       }
11923     }
11924   }
11925 
11926   ConstantsOut.clear();
11927 }
11928 
11929 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
11930   MachineFunction::iterator I(MBB);
11931   if (++I == FuncInfo.MF->end())
11932     return nullptr;
11933   return &*I;
11934 }
11935 
11936 /// During lowering new call nodes can be created (such as memset, etc.).
11937 /// Those will become new roots of the current DAG, but complications arise
11938 /// when they are tail calls. In such cases, the call lowering will update
11939 /// the root, but the builder still needs to know that a tail call has been
11940 /// lowered in order to avoid generating an additional return.
11941 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
11942   // If the node is null, we do have a tail call.
11943   if (MaybeTC.getNode() != nullptr)
11944     DAG.setRoot(MaybeTC);
11945   else
11946     HasTailCall = true;
11947 }
11948 
11949 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
11950                                         MachineBasicBlock *SwitchMBB,
11951                                         MachineBasicBlock *DefaultMBB) {
11952   MachineFunction *CurMF = FuncInfo.MF;
11953   MachineBasicBlock *NextMBB = nullptr;
11954   MachineFunction::iterator BBI(W.MBB);
11955   if (++BBI != FuncInfo.MF->end())
11956     NextMBB = &*BBI;
11957 
11958   unsigned Size = W.LastCluster - W.FirstCluster + 1;
11959 
11960   BranchProbabilityInfo *BPI = FuncInfo.BPI;
11961 
11962   if (Size == 2 && W.MBB == SwitchMBB) {
11963     // If any two of the cases has the same destination, and if one value
11964     // is the same as the other, but has one bit unset that the other has set,
11965     // use bit manipulation to do two compares at once.  For example:
11966     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
11967     // TODO: This could be extended to merge any 2 cases in switches with 3
11968     // cases.
11969     // TODO: Handle cases where W.CaseBB != SwitchBB.
11970     CaseCluster &Small = *W.FirstCluster;
11971     CaseCluster &Big = *W.LastCluster;
11972 
11973     if (Small.Low == Small.High && Big.Low == Big.High &&
11974         Small.MBB == Big.MBB) {
11975       const APInt &SmallValue = Small.Low->getValue();
11976       const APInt &BigValue = Big.Low->getValue();
11977 
11978       // Check that there is only one bit different.
11979       APInt CommonBit = BigValue ^ SmallValue;
11980       if (CommonBit.isPowerOf2()) {
11981         SDValue CondLHS = getValue(Cond);
11982         EVT VT = CondLHS.getValueType();
11983         SDLoc DL = getCurSDLoc();
11984 
11985         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
11986                                  DAG.getConstant(CommonBit, DL, VT));
11987         SDValue Cond = DAG.getSetCC(
11988             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
11989             ISD::SETEQ);
11990 
11991         // Update successor info.
11992         // Both Small and Big will jump to Small.BB, so we sum up the
11993         // probabilities.
11994         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
11995         if (BPI)
11996           addSuccessorWithProb(
11997               SwitchMBB, DefaultMBB,
11998               // The default destination is the first successor in IR.
11999               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12000         else
12001           addSuccessorWithProb(SwitchMBB, DefaultMBB);
12002 
12003         // Insert the true branch.
12004         SDValue BrCond =
12005             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12006                         DAG.getBasicBlock(Small.MBB));
12007         // Insert the false branch.
12008         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12009                              DAG.getBasicBlock(DefaultMBB));
12010 
12011         DAG.setRoot(BrCond);
12012         return;
12013       }
12014     }
12015   }
12016 
12017   if (TM.getOptLevel() != CodeGenOptLevel::None) {
12018     // Here, we order cases by probability so the most likely case will be
12019     // checked first. However, two clusters can have the same probability in
12020     // which case their relative ordering is non-deterministic. So we use Low
12021     // as a tie-breaker as clusters are guaranteed to never overlap.
12022     llvm::sort(W.FirstCluster, W.LastCluster + 1,
12023                [](const CaseCluster &a, const CaseCluster &b) {
12024       return a.Prob != b.Prob ?
12025              a.Prob > b.Prob :
12026              a.Low->getValue().slt(b.Low->getValue());
12027     });
12028 
12029     // Rearrange the case blocks so that the last one falls through if possible
12030     // without changing the order of probabilities.
12031     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12032       --I;
12033       if (I->Prob > W.LastCluster->Prob)
12034         break;
12035       if (I->Kind == CC_Range && I->MBB == NextMBB) {
12036         std::swap(*I, *W.LastCluster);
12037         break;
12038       }
12039     }
12040   }
12041 
12042   // Compute total probability.
12043   BranchProbability DefaultProb = W.DefaultProb;
12044   BranchProbability UnhandledProbs = DefaultProb;
12045   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12046     UnhandledProbs += I->Prob;
12047 
12048   MachineBasicBlock *CurMBB = W.MBB;
12049   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12050     bool FallthroughUnreachable = false;
12051     MachineBasicBlock *Fallthrough;
12052     if (I == W.LastCluster) {
12053       // For the last cluster, fall through to the default destination.
12054       Fallthrough = DefaultMBB;
12055       FallthroughUnreachable = isa<UnreachableInst>(
12056           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12057     } else {
12058       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12059       CurMF->insert(BBI, Fallthrough);
12060       // Put Cond in a virtual register to make it available from the new blocks.
12061       ExportFromCurrentBlock(Cond);
12062     }
12063     UnhandledProbs -= I->Prob;
12064 
12065     switch (I->Kind) {
12066       case CC_JumpTable: {
12067         // FIXME: Optimize away range check based on pivot comparisons.
12068         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12069         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12070 
12071         // The jump block hasn't been inserted yet; insert it here.
12072         MachineBasicBlock *JumpMBB = JT->MBB;
12073         CurMF->insert(BBI, JumpMBB);
12074 
12075         auto JumpProb = I->Prob;
12076         auto FallthroughProb = UnhandledProbs;
12077 
12078         // If the default statement is a target of the jump table, we evenly
12079         // distribute the default probability to successors of CurMBB. Also
12080         // update the probability on the edge from JumpMBB to Fallthrough.
12081         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12082                                               SE = JumpMBB->succ_end();
12083              SI != SE; ++SI) {
12084           if (*SI == DefaultMBB) {
12085             JumpProb += DefaultProb / 2;
12086             FallthroughProb -= DefaultProb / 2;
12087             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12088             JumpMBB->normalizeSuccProbs();
12089             break;
12090           }
12091         }
12092 
12093         // If the default clause is unreachable, propagate that knowledge into
12094         // JTH->FallthroughUnreachable which will use it to suppress the range
12095         // check.
12096         //
12097         // However, don't do this if we're doing branch target enforcement,
12098         // because a table branch _without_ a range check can be a tempting JOP
12099         // gadget - out-of-bounds inputs that are impossible in correct
12100         // execution become possible again if an attacker can influence the
12101         // control flow. So if an attacker doesn't already have a BTI bypass
12102         // available, we don't want them to be able to get one out of this
12103         // table branch.
12104         if (FallthroughUnreachable) {
12105           Function &CurFunc = CurMF->getFunction();
12106           if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12107             JTH->FallthroughUnreachable = true;
12108         }
12109 
12110         if (!JTH->FallthroughUnreachable)
12111           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12112         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12113         CurMBB->normalizeSuccProbs();
12114 
12115         // The jump table header will be inserted in our current block, do the
12116         // range check, and fall through to our fallthrough block.
12117         JTH->HeaderBB = CurMBB;
12118         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12119 
12120         // If we're in the right place, emit the jump table header right now.
12121         if (CurMBB == SwitchMBB) {
12122           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12123           JTH->Emitted = true;
12124         }
12125         break;
12126       }
12127       case CC_BitTests: {
12128         // FIXME: Optimize away range check based on pivot comparisons.
12129         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12130 
12131         // The bit test blocks haven't been inserted yet; insert them here.
12132         for (BitTestCase &BTC : BTB->Cases)
12133           CurMF->insert(BBI, BTC.ThisBB);
12134 
12135         // Fill in fields of the BitTestBlock.
12136         BTB->Parent = CurMBB;
12137         BTB->Default = Fallthrough;
12138 
12139         BTB->DefaultProb = UnhandledProbs;
12140         // If the cases in bit test don't form a contiguous range, we evenly
12141         // distribute the probability on the edge to Fallthrough to two
12142         // successors of CurMBB.
12143         if (!BTB->ContiguousRange) {
12144           BTB->Prob += DefaultProb / 2;
12145           BTB->DefaultProb -= DefaultProb / 2;
12146         }
12147 
12148         if (FallthroughUnreachable)
12149           BTB->FallthroughUnreachable = true;
12150 
12151         // If we're in the right place, emit the bit test header right now.
12152         if (CurMBB == SwitchMBB) {
12153           visitBitTestHeader(*BTB, SwitchMBB);
12154           BTB->Emitted = true;
12155         }
12156         break;
12157       }
12158       case CC_Range: {
12159         const Value *RHS, *LHS, *MHS;
12160         ISD::CondCode CC;
12161         if (I->Low == I->High) {
12162           // Check Cond == I->Low.
12163           CC = ISD::SETEQ;
12164           LHS = Cond;
12165           RHS=I->Low;
12166           MHS = nullptr;
12167         } else {
12168           // Check I->Low <= Cond <= I->High.
12169           CC = ISD::SETLE;
12170           LHS = I->Low;
12171           MHS = Cond;
12172           RHS = I->High;
12173         }
12174 
12175         // If Fallthrough is unreachable, fold away the comparison.
12176         if (FallthroughUnreachable)
12177           CC = ISD::SETTRUE;
12178 
12179         // The false probability is the sum of all unhandled cases.
12180         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12181                      getCurSDLoc(), I->Prob, UnhandledProbs);
12182 
12183         if (CurMBB == SwitchMBB)
12184           visitSwitchCase(CB, SwitchMBB);
12185         else
12186           SL->SwitchCases.push_back(CB);
12187 
12188         break;
12189       }
12190     }
12191     CurMBB = Fallthrough;
12192   }
12193 }
12194 
12195 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12196                                         const SwitchWorkListItem &W,
12197                                         Value *Cond,
12198                                         MachineBasicBlock *SwitchMBB) {
12199   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12200          "Clusters not sorted?");
12201   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12202 
12203   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12204       SL->computeSplitWorkItemInfo(W);
12205 
12206   // Use the first element on the right as pivot since we will make less-than
12207   // comparisons against it.
12208   CaseClusterIt PivotCluster = FirstRight;
12209   assert(PivotCluster > W.FirstCluster);
12210   assert(PivotCluster <= W.LastCluster);
12211 
12212   CaseClusterIt FirstLeft = W.FirstCluster;
12213   CaseClusterIt LastRight = W.LastCluster;
12214 
12215   const ConstantInt *Pivot = PivotCluster->Low;
12216 
12217   // New blocks will be inserted immediately after the current one.
12218   MachineFunction::iterator BBI(W.MBB);
12219   ++BBI;
12220 
12221   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12222   // we can branch to its destination directly if it's squeezed exactly in
12223   // between the known lower bound and Pivot - 1.
12224   MachineBasicBlock *LeftMBB;
12225   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12226       FirstLeft->Low == W.GE &&
12227       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12228     LeftMBB = FirstLeft->MBB;
12229   } else {
12230     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12231     FuncInfo.MF->insert(BBI, LeftMBB);
12232     WorkList.push_back(
12233         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12234     // Put Cond in a virtual register to make it available from the new blocks.
12235     ExportFromCurrentBlock(Cond);
12236   }
12237 
12238   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12239   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12240   // directly if RHS.High equals the current upper bound.
12241   MachineBasicBlock *RightMBB;
12242   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12243       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12244     RightMBB = FirstRight->MBB;
12245   } else {
12246     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12247     FuncInfo.MF->insert(BBI, RightMBB);
12248     WorkList.push_back(
12249         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12250     // Put Cond in a virtual register to make it available from the new blocks.
12251     ExportFromCurrentBlock(Cond);
12252   }
12253 
12254   // Create the CaseBlock record that will be used to lower the branch.
12255   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12256                getCurSDLoc(), LeftProb, RightProb);
12257 
12258   if (W.MBB == SwitchMBB)
12259     visitSwitchCase(CB, SwitchMBB);
12260   else
12261     SL->SwitchCases.push_back(CB);
12262 }
12263 
12264 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12265 // from the swith statement.
12266 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12267                                             BranchProbability PeeledCaseProb) {
12268   if (PeeledCaseProb == BranchProbability::getOne())
12269     return BranchProbability::getZero();
12270   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12271 
12272   uint32_t Numerator = CaseProb.getNumerator();
12273   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12274   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12275 }
12276 
12277 // Try to peel the top probability case if it exceeds the threshold.
12278 // Return current MachineBasicBlock for the switch statement if the peeling
12279 // does not occur.
12280 // If the peeling is performed, return the newly created MachineBasicBlock
12281 // for the peeled switch statement. Also update Clusters to remove the peeled
12282 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12283 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12284     const SwitchInst &SI, CaseClusterVector &Clusters,
12285     BranchProbability &PeeledCaseProb) {
12286   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12287   // Don't perform if there is only one cluster or optimizing for size.
12288   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12289       TM.getOptLevel() == CodeGenOptLevel::None ||
12290       SwitchMBB->getParent()->getFunction().hasMinSize())
12291     return SwitchMBB;
12292 
12293   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12294   unsigned PeeledCaseIndex = 0;
12295   bool SwitchPeeled = false;
12296   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12297     CaseCluster &CC = Clusters[Index];
12298     if (CC.Prob < TopCaseProb)
12299       continue;
12300     TopCaseProb = CC.Prob;
12301     PeeledCaseIndex = Index;
12302     SwitchPeeled = true;
12303   }
12304   if (!SwitchPeeled)
12305     return SwitchMBB;
12306 
12307   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12308                     << TopCaseProb << "\n");
12309 
12310   // Record the MBB for the peeled switch statement.
12311   MachineFunction::iterator BBI(SwitchMBB);
12312   ++BBI;
12313   MachineBasicBlock *PeeledSwitchMBB =
12314       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12315   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12316 
12317   ExportFromCurrentBlock(SI.getCondition());
12318   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12319   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12320                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12321   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12322 
12323   Clusters.erase(PeeledCaseIt);
12324   for (CaseCluster &CC : Clusters) {
12325     LLVM_DEBUG(
12326         dbgs() << "Scale the probablity for one cluster, before scaling: "
12327                << CC.Prob << "\n");
12328     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12329     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12330   }
12331   PeeledCaseProb = TopCaseProb;
12332   return PeeledSwitchMBB;
12333 }
12334 
12335 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12336   // Extract cases from the switch.
12337   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12338   CaseClusterVector Clusters;
12339   Clusters.reserve(SI.getNumCases());
12340   for (auto I : SI.cases()) {
12341     MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
12342     const ConstantInt *CaseVal = I.getCaseValue();
12343     BranchProbability Prob =
12344         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12345             : BranchProbability(1, SI.getNumCases() + 1);
12346     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12347   }
12348 
12349   MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
12350 
12351   // Cluster adjacent cases with the same destination. We do this at all
12352   // optimization levels because it's cheap to do and will make codegen faster
12353   // if there are many clusters.
12354   sortAndRangeify(Clusters);
12355 
12356   // The branch probablity of the peeled case.
12357   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12358   MachineBasicBlock *PeeledSwitchMBB =
12359       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12360 
12361   // If there is only the default destination, jump there directly.
12362   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12363   if (Clusters.empty()) {
12364     assert(PeeledSwitchMBB == SwitchMBB);
12365     SwitchMBB->addSuccessor(DefaultMBB);
12366     if (DefaultMBB != NextBlock(SwitchMBB)) {
12367       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12368                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12369     }
12370     return;
12371   }
12372 
12373   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12374                      DAG.getBFI());
12375   SL->findBitTestClusters(Clusters, &SI);
12376 
12377   LLVM_DEBUG({
12378     dbgs() << "Case clusters: ";
12379     for (const CaseCluster &C : Clusters) {
12380       if (C.Kind == CC_JumpTable)
12381         dbgs() << "JT:";
12382       if (C.Kind == CC_BitTests)
12383         dbgs() << "BT:";
12384 
12385       C.Low->getValue().print(dbgs(), true);
12386       if (C.Low != C.High) {
12387         dbgs() << '-';
12388         C.High->getValue().print(dbgs(), true);
12389       }
12390       dbgs() << ' ';
12391     }
12392     dbgs() << '\n';
12393   });
12394 
12395   assert(!Clusters.empty());
12396   SwitchWorkList WorkList;
12397   CaseClusterIt First = Clusters.begin();
12398   CaseClusterIt Last = Clusters.end() - 1;
12399   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12400   // Scale the branchprobability for DefaultMBB if the peel occurs and
12401   // DefaultMBB is not replaced.
12402   if (PeeledCaseProb != BranchProbability::getZero() &&
12403       DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
12404     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12405   WorkList.push_back(
12406       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12407 
12408   while (!WorkList.empty()) {
12409     SwitchWorkListItem W = WorkList.pop_back_val();
12410     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12411 
12412     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12413         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12414       // For optimized builds, lower large range as a balanced binary tree.
12415       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12416       continue;
12417     }
12418 
12419     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12420   }
12421 }
12422 
12423 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12424   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12425   auto DL = getCurSDLoc();
12426   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12427   setValue(&I, DAG.getStepVector(DL, ResultVT));
12428 }
12429 
12430 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12431   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12432   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12433 
12434   SDLoc DL = getCurSDLoc();
12435   SDValue V = getValue(I.getOperand(0));
12436   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12437 
12438   if (VT.isScalableVector()) {
12439     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12440     return;
12441   }
12442 
12443   // Use VECTOR_SHUFFLE for the fixed-length vector
12444   // to maintain existing behavior.
12445   SmallVector<int, 8> Mask;
12446   unsigned NumElts = VT.getVectorMinNumElements();
12447   for (unsigned i = 0; i != NumElts; ++i)
12448     Mask.push_back(NumElts - 1 - i);
12449 
12450   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12451 }
12452 
12453 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12454   auto DL = getCurSDLoc();
12455   SDValue InVec = getValue(I.getOperand(0));
12456   EVT OutVT =
12457       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12458 
12459   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12460 
12461   // ISD Node needs the input vectors split into two equal parts
12462   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12463                            DAG.getVectorIdxConstant(0, DL));
12464   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12465                            DAG.getVectorIdxConstant(OutNumElts, DL));
12466 
12467   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12468   // legalisation and combines.
12469   if (OutVT.isFixedLengthVector()) {
12470     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12471                                         createStrideMask(0, 2, OutNumElts));
12472     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12473                                        createStrideMask(1, 2, OutNumElts));
12474     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12475     setValue(&I, Res);
12476     return;
12477   }
12478 
12479   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12480                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12481   setValue(&I, Res);
12482 }
12483 
12484 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12485   auto DL = getCurSDLoc();
12486   EVT InVT = getValue(I.getOperand(0)).getValueType();
12487   SDValue InVec0 = getValue(I.getOperand(0));
12488   SDValue InVec1 = getValue(I.getOperand(1));
12489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12490   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12491 
12492   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12493   // legalisation and combines.
12494   if (OutVT.isFixedLengthVector()) {
12495     unsigned NumElts = InVT.getVectorMinNumElements();
12496     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12497     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12498                                       createInterleaveMask(NumElts, 2)));
12499     return;
12500   }
12501 
12502   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12503                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12504   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12505                     Res.getValue(1));
12506   setValue(&I, Res);
12507 }
12508 
12509 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12510   SmallVector<EVT, 4> ValueVTs;
12511   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12512                   ValueVTs);
12513   unsigned NumValues = ValueVTs.size();
12514   if (NumValues == 0) return;
12515 
12516   SmallVector<SDValue, 4> Values(NumValues);
12517   SDValue Op = getValue(I.getOperand(0));
12518 
12519   for (unsigned i = 0; i != NumValues; ++i)
12520     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12521                             SDValue(Op.getNode(), Op.getResNo() + i));
12522 
12523   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12524                            DAG.getVTList(ValueVTs), Values));
12525 }
12526 
12527 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12528   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12529   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12530 
12531   SDLoc DL = getCurSDLoc();
12532   SDValue V1 = getValue(I.getOperand(0));
12533   SDValue V2 = getValue(I.getOperand(1));
12534   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12535 
12536   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12537   if (VT.isScalableVector()) {
12538     setValue(
12539         &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12540                         DAG.getSignedConstant(
12541                             Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
12542     return;
12543   }
12544 
12545   unsigned NumElts = VT.getVectorNumElements();
12546 
12547   uint64_t Idx = (NumElts + Imm) % NumElts;
12548 
12549   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12550   SmallVector<int, 8> Mask;
12551   for (unsigned i = 0; i < NumElts; ++i)
12552     Mask.push_back(Idx + i);
12553   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12554 }
12555 
12556 // Consider the following MIR after SelectionDAG, which produces output in
12557 // phyregs in the first case or virtregs in the second case.
12558 //
12559 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12560 // %5:gr32 = COPY $ebx
12561 // %6:gr32 = COPY $edx
12562 // %1:gr32 = COPY %6:gr32
12563 // %0:gr32 = COPY %5:gr32
12564 //
12565 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12566 // %1:gr32 = COPY %6:gr32
12567 // %0:gr32 = COPY %5:gr32
12568 //
12569 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12570 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12571 //
12572 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12573 // to a single virtreg (such as %0). The remaining outputs monotonically
12574 // increase in virtreg number from there. If a callbr has no outputs, then it
12575 // should not have a corresponding callbr landingpad; in fact, the callbr
12576 // landingpad would not even be able to refer to such a callbr.
12577 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12578   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12579   // There is definitely at least one copy.
12580   assert(MI->getOpcode() == TargetOpcode::COPY &&
12581          "start of copy chain MUST be COPY");
12582   Reg = MI->getOperand(1).getReg();
12583   MI = MRI.def_begin(Reg)->getParent();
12584   // There may be an optional second copy.
12585   if (MI->getOpcode() == TargetOpcode::COPY) {
12586     assert(Reg.isVirtual() && "expected COPY of virtual register");
12587     Reg = MI->getOperand(1).getReg();
12588     assert(Reg.isPhysical() && "expected COPY of physical register");
12589     MI = MRI.def_begin(Reg)->getParent();
12590   }
12591   // The start of the chain must be an INLINEASM_BR.
12592   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12593          "end of copy chain MUST be INLINEASM_BR");
12594   return Reg;
12595 }
12596 
12597 // We must do this walk rather than the simpler
12598 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12599 // otherwise we will end up with copies of virtregs only valid along direct
12600 // edges.
12601 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12602   SmallVector<EVT, 8> ResultVTs;
12603   SmallVector<SDValue, 8> ResultValues;
12604   const auto *CBR =
12605       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12606 
12607   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12608   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12609   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12610 
12611   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12612   SDValue Chain = DAG.getRoot();
12613 
12614   // Re-parse the asm constraints string.
12615   TargetLowering::AsmOperandInfoVector TargetConstraints =
12616       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12617   for (auto &T : TargetConstraints) {
12618     SDISelAsmOperandInfo OpInfo(T);
12619     if (OpInfo.Type != InlineAsm::isOutput)
12620       continue;
12621 
12622     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12623     // individual constraint.
12624     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12625 
12626     switch (OpInfo.ConstraintType) {
12627     case TargetLowering::C_Register:
12628     case TargetLowering::C_RegisterClass: {
12629       // Fill in OpInfo.AssignedRegs.Regs.
12630       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12631 
12632       // getRegistersForValue may produce 1 to many registers based on whether
12633       // the OpInfo.ConstraintVT is legal on the target or not.
12634       for (unsigned &Reg : OpInfo.AssignedRegs.Regs) {
12635         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12636         if (Register::isPhysicalRegister(OriginalDef))
12637           FuncInfo.MBB->addLiveIn(OriginalDef);
12638         // Update the assigned registers to use the original defs.
12639         Reg = OriginalDef;
12640       }
12641 
12642       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12643           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12644       ResultValues.push_back(V);
12645       ResultVTs.push_back(OpInfo.ConstraintVT);
12646       break;
12647     }
12648     case TargetLowering::C_Other: {
12649       SDValue Flag;
12650       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12651                                                   OpInfo, DAG);
12652       ++InitialDef;
12653       ResultValues.push_back(V);
12654       ResultVTs.push_back(OpInfo.ConstraintVT);
12655       break;
12656     }
12657     default:
12658       break;
12659     }
12660   }
12661   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12662                           DAG.getVTList(ResultVTs), ResultValues);
12663   setValue(&I, V);
12664 }
12665