xref: /llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp (revision 6292a808b3524d9ba6f4ce55bc5b9e547b088dd8)
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/SelectionDAG.h"
48 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
49 #include "llvm/CodeGen/StackMaps.h"
50 #include "llvm/CodeGen/SwiftErrorValueTracking.h"
51 #include "llvm/CodeGen/TargetFrameLowering.h"
52 #include "llvm/CodeGen/TargetInstrInfo.h"
53 #include "llvm/CodeGen/TargetOpcodes.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/TargetSubtargetInfo.h"
56 #include "llvm/CodeGen/WinEHFuncInfo.h"
57 #include "llvm/IR/Argument.h"
58 #include "llvm/IR/Attributes.h"
59 #include "llvm/IR/BasicBlock.h"
60 #include "llvm/IR/CFG.h"
61 #include "llvm/IR/CallingConv.h"
62 #include "llvm/IR/Constant.h"
63 #include "llvm/IR/ConstantRange.h"
64 #include "llvm/IR/Constants.h"
65 #include "llvm/IR/DataLayout.h"
66 #include "llvm/IR/DebugInfo.h"
67 #include "llvm/IR/DebugInfoMetadata.h"
68 #include "llvm/IR/DerivedTypes.h"
69 #include "llvm/IR/DiagnosticInfo.h"
70 #include "llvm/IR/EHPersonalities.h"
71 #include "llvm/IR/Function.h"
72 #include "llvm/IR/GetElementPtrTypeIterator.h"
73 #include "llvm/IR/InlineAsm.h"
74 #include "llvm/IR/InstrTypes.h"
75 #include "llvm/IR/Instructions.h"
76 #include "llvm/IR/IntrinsicInst.h"
77 #include "llvm/IR/Intrinsics.h"
78 #include "llvm/IR/IntrinsicsAArch64.h"
79 #include "llvm/IR/IntrinsicsAMDGPU.h"
80 #include "llvm/IR/IntrinsicsWebAssembly.h"
81 #include "llvm/IR/LLVMContext.h"
82 #include "llvm/IR/MemoryModelRelaxationAnnotations.h"
83 #include "llvm/IR/Metadata.h"
84 #include "llvm/IR/Module.h"
85 #include "llvm/IR/Operator.h"
86 #include "llvm/IR/PatternMatch.h"
87 #include "llvm/IR/Statepoint.h"
88 #include "llvm/IR/Type.h"
89 #include "llvm/IR/User.h"
90 #include "llvm/IR/Value.h"
91 #include "llvm/MC/MCContext.h"
92 #include "llvm/Support/AtomicOrdering.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/InstructionCost.h"
98 #include "llvm/Support/MathExtras.h"
99 #include "llvm/Support/raw_ostream.h"
100 #include "llvm/Target/TargetIntrinsicInfo.h"
101 #include "llvm/Target/TargetMachine.h"
102 #include "llvm/Target/TargetOptions.h"
103 #include "llvm/TargetParser/Triple.h"
104 #include "llvm/Transforms/Utils/Local.h"
105 #include <cstddef>
106 #include <limits>
107 #include <optional>
108 #include <tuple>
109 
110 using namespace llvm;
111 using namespace PatternMatch;
112 using namespace SwitchCG;
113 
114 #define DEBUG_TYPE "isel"
115 
116 /// LimitFloatPrecision - Generate low-precision inline sequences for
117 /// some float libcalls (6, 8 or 12 bits).
118 static unsigned LimitFloatPrecision;
119 
120 static cl::opt<bool>
121     InsertAssertAlign("insert-assert-align", cl::init(true),
122                       cl::desc("Insert the experimental `assertalign` node."),
123                       cl::ReallyHidden);
124 
125 static cl::opt<unsigned, true>
126     LimitFPPrecision("limit-float-precision",
127                      cl::desc("Generate low-precision inline sequences "
128                               "for some float libcalls"),
129                      cl::location(LimitFloatPrecision), cl::Hidden,
130                      cl::init(0));
131 
132 static cl::opt<unsigned> SwitchPeelThreshold(
133     "switch-peel-threshold", cl::Hidden, cl::init(66),
134     cl::desc("Set the case probability threshold for peeling the case from a "
135              "switch statement. A value greater than 100 will void this "
136              "optimization"));
137 
138 // Limit the width of DAG chains. This is important in general to prevent
139 // DAG-based analysis from blowing up. For example, alias analysis and
140 // load clustering may not complete in reasonable time. It is difficult to
141 // recognize and avoid this situation within each individual analysis, and
142 // future analyses are likely to have the same behavior. Limiting DAG width is
143 // the safe approach and will be especially important with global DAGs.
144 //
145 // MaxParallelChains default is arbitrarily high to avoid affecting
146 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
147 // sequence over this should have been converted to llvm.memcpy by the
148 // frontend. It is easy to induce this behavior with .ll code such as:
149 // %buffer = alloca [4096 x i8]
150 // %data = load [4096 x i8]* %argPtr
151 // store [4096 x i8] %data, [4096 x i8]* %buffer
152 static const unsigned MaxParallelChains = 64;
153 
154 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
155                                       const SDValue *Parts, unsigned NumParts,
156                                       MVT PartVT, EVT ValueVT, const Value *V,
157                                       SDValue InChain,
158                                       std::optional<CallingConv::ID> CC);
159 
160 /// getCopyFromParts - Create a value that contains the specified legal parts
161 /// combined into the value they represent.  If the parts combine to a type
162 /// larger than ValueVT then AssertOp can be used to specify whether the extra
163 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
164 /// (ISD::AssertSext).
165 static SDValue
166 getCopyFromParts(SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts,
167                  unsigned NumParts, MVT PartVT, EVT ValueVT, const Value *V,
168                  SDValue InChain,
169                  std::optional<CallingConv::ID> CC = std::nullopt,
170                  std::optional<ISD::NodeType> AssertOp = std::nullopt) {
171   // Let the target assemble the parts if it wants to
172   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
173   if (SDValue Val = TLI.joinRegisterPartsIntoValue(DAG, DL, Parts, NumParts,
174                                                    PartVT, ValueVT, CC))
175     return Val;
176 
177   if (ValueVT.isVector())
178     return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT, V,
179                                   InChain, CC);
180 
181   assert(NumParts > 0 && "No parts to assemble!");
182   SDValue Val = Parts[0];
183 
184   if (NumParts > 1) {
185     // Assemble the value from multiple parts.
186     if (ValueVT.isInteger()) {
187       unsigned PartBits = PartVT.getSizeInBits();
188       unsigned ValueBits = ValueVT.getSizeInBits();
189 
190       // Assemble the power of 2 part.
191       unsigned RoundParts = llvm::bit_floor(NumParts);
192       unsigned RoundBits = PartBits * RoundParts;
193       EVT RoundVT = RoundBits == ValueBits ?
194         ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
195       SDValue Lo, Hi;
196 
197       EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
198 
199       if (RoundParts > 2) {
200         Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2, PartVT, HalfVT, V,
201                               InChain);
202         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2, RoundParts / 2,
203                               PartVT, HalfVT, V, InChain);
204       } else {
205         Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
206         Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
207       }
208 
209       if (DAG.getDataLayout().isBigEndian())
210         std::swap(Lo, Hi);
211 
212       Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
213 
214       if (RoundParts < NumParts) {
215         // Assemble the trailing non-power-of-2 part.
216         unsigned OddParts = NumParts - RoundParts;
217         EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
218         Hi = getCopyFromParts(DAG, DL, Parts + RoundParts, OddParts, PartVT,
219                               OddVT, V, InChain, CC);
220 
221         // Combine the round and odd parts.
222         Lo = Val;
223         if (DAG.getDataLayout().isBigEndian())
224           std::swap(Lo, Hi);
225         EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
226         Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
227         Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
228                          DAG.getConstant(Lo.getValueSizeInBits(), DL,
229                                          TLI.getShiftAmountTy(
230                                              TotalVT, DAG.getDataLayout())));
231         Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
232         Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
233       }
234     } else if (PartVT.isFloatingPoint()) {
235       // FP split into multiple FP parts (for ppcf128)
236       assert(ValueVT == EVT(MVT::ppcf128) && PartVT == MVT::f64 &&
237              "Unexpected split");
238       SDValue Lo, Hi;
239       Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
240       Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
241       if (TLI.hasBigEndianPartOrdering(ValueVT, DAG.getDataLayout()))
242         std::swap(Lo, Hi);
243       Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
244     } else {
245       // FP split into integer parts (soft fp)
246       assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
247              !PartVT.isVector() && "Unexpected split");
248       EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
249       Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V,
250                              InChain, CC);
251     }
252   }
253 
254   // There is now one part, held in Val.  Correct it to match ValueVT.
255   // PartEVT is the type of the register class that holds the value.
256   // ValueVT is the type of the inline asm operation.
257   EVT PartEVT = Val.getValueType();
258 
259   if (PartEVT == ValueVT)
260     return Val;
261 
262   if (PartEVT.isInteger() && ValueVT.isFloatingPoint() &&
263       ValueVT.bitsLT(PartEVT)) {
264     // For an FP value in an integer part, we need to truncate to the right
265     // width first.
266     PartEVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
267     Val = DAG.getNode(ISD::TRUNCATE, DL, PartEVT, Val);
268   }
269 
270   // Handle types that have the same size.
271   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits())
272     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
273 
274   // Handle types with different sizes.
275   if (PartEVT.isInteger() && ValueVT.isInteger()) {
276     if (ValueVT.bitsLT(PartEVT)) {
277       // For a truncate, see if we have any information to
278       // indicate whether the truncated bits will always be
279       // zero or sign-extension.
280       if (AssertOp)
281         Val = DAG.getNode(*AssertOp, DL, PartEVT, Val,
282                           DAG.getValueType(ValueVT));
283       return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
284     }
285     return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
286   }
287 
288   if (PartEVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
289     // FP_ROUND's are always exact here.
290     if (ValueVT.bitsLT(Val.getValueType())) {
291 
292       SDValue NoChange =
293           DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
294 
295       if (DAG.getMachineFunction().getFunction().getAttributes().hasFnAttr(
296               llvm::Attribute::StrictFP)) {
297         return DAG.getNode(ISD::STRICT_FP_ROUND, DL,
298                            DAG.getVTList(ValueVT, MVT::Other), InChain, Val,
299                            NoChange);
300       }
301 
302       return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val, NoChange);
303     }
304 
305     return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
306   }
307 
308   // Handle MMX to a narrower integer type by bitcasting MMX to integer and
309   // then truncating.
310   if (PartEVT == MVT::x86mmx && ValueVT.isInteger() &&
311       ValueVT.bitsLT(PartEVT)) {
312     Val = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Val);
313     return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
314   }
315 
316   report_fatal_error("Unknown mismatch in getCopyFromParts!");
317 }
318 
319 static void diagnosePossiblyInvalidConstraint(LLVMContext &Ctx, const Value *V,
320                                               const Twine &ErrMsg) {
321   const Instruction *I = dyn_cast_or_null<Instruction>(V);
322   if (!I)
323     return Ctx.emitError(ErrMsg);
324 
325   if (const CallInst *CI = dyn_cast<CallInst>(I))
326     if (CI->isInlineAsm()) {
327       return Ctx.diagnose(DiagnosticInfoInlineAsm(
328           *CI, ErrMsg + ", possible invalid constraint for vector type"));
329     }
330 
331   return Ctx.emitError(I, ErrMsg);
332 }
333 
334 /// getCopyFromPartsVector - Create a value that contains the specified legal
335 /// parts combined into the value they represent.  If the parts combine to a
336 /// type larger than ValueVT then AssertOp can be used to specify whether the
337 /// extra bits are known to be zero (ISD::AssertZext) or sign extended from
338 /// ValueVT (ISD::AssertSext).
339 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, const SDLoc &DL,
340                                       const SDValue *Parts, unsigned NumParts,
341                                       MVT PartVT, EVT ValueVT, const Value *V,
342                                       SDValue InChain,
343                                       std::optional<CallingConv::ID> CallConv) {
344   assert(ValueVT.isVector() && "Not a vector value");
345   assert(NumParts > 0 && "No parts to assemble!");
346   const bool IsABIRegCopy = CallConv.has_value();
347 
348   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
349   SDValue Val = Parts[0];
350 
351   // Handle a multi-element vector.
352   if (NumParts > 1) {
353     EVT IntermediateVT;
354     MVT RegisterVT;
355     unsigned NumIntermediates;
356     unsigned NumRegs;
357 
358     if (IsABIRegCopy) {
359       NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
360           *DAG.getContext(), *CallConv, ValueVT, IntermediateVT,
361           NumIntermediates, RegisterVT);
362     } else {
363       NumRegs =
364           TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
365                                      NumIntermediates, RegisterVT);
366     }
367 
368     assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
369     NumParts = NumRegs; // Silence a compiler warning.
370     assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
371     assert(RegisterVT.getSizeInBits() ==
372            Parts[0].getSimpleValueType().getSizeInBits() &&
373            "Part type sizes don't match!");
374 
375     // Assemble the parts into intermediate operands.
376     SmallVector<SDValue, 8> Ops(NumIntermediates);
377     if (NumIntermediates == NumParts) {
378       // If the register was not expanded, truncate or copy the value,
379       // as appropriate.
380       for (unsigned i = 0; i != NumParts; ++i)
381         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1, PartVT, IntermediateVT,
382                                   V, InChain, CallConv);
383     } else if (NumParts > 0) {
384       // If the intermediate type was expanded, build the intermediate
385       // operands from the parts.
386       assert(NumParts % NumIntermediates == 0 &&
387              "Must expand into a divisible number of parts!");
388       unsigned Factor = NumParts / NumIntermediates;
389       for (unsigned i = 0; i != NumIntermediates; ++i)
390         Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor, PartVT,
391                                   IntermediateVT, V, InChain, CallConv);
392     }
393 
394     // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
395     // intermediate operands.
396     EVT BuiltVectorTy =
397         IntermediateVT.isVector()
398             ? EVT::getVectorVT(
399                   *DAG.getContext(), IntermediateVT.getScalarType(),
400                   IntermediateVT.getVectorElementCount() * NumParts)
401             : EVT::getVectorVT(*DAG.getContext(),
402                                IntermediateVT.getScalarType(),
403                                NumIntermediates);
404     Val = DAG.getNode(IntermediateVT.isVector() ? ISD::CONCAT_VECTORS
405                                                 : ISD::BUILD_VECTOR,
406                       DL, BuiltVectorTy, Ops);
407   }
408 
409   // There is now one part, held in Val.  Correct it to match ValueVT.
410   EVT PartEVT = Val.getValueType();
411 
412   if (PartEVT == ValueVT)
413     return Val;
414 
415   if (PartEVT.isVector()) {
416     // Vector/Vector bitcast.
417     if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
418       return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
419 
420     // If the parts vector has more elements than the value vector, then we
421     // have a vector widening case (e.g. <2 x float> -> <4 x float>).
422     // Extract the elements we want.
423     if (PartEVT.getVectorElementCount() != ValueVT.getVectorElementCount()) {
424       assert((PartEVT.getVectorElementCount().getKnownMinValue() >
425               ValueVT.getVectorElementCount().getKnownMinValue()) &&
426              (PartEVT.getVectorElementCount().isScalable() ==
427               ValueVT.getVectorElementCount().isScalable()) &&
428              "Cannot narrow, it would be a lossy transformation");
429       PartEVT =
430           EVT::getVectorVT(*DAG.getContext(), PartEVT.getVectorElementType(),
431                            ValueVT.getVectorElementCount());
432       Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, PartEVT, Val,
433                         DAG.getVectorIdxConstant(0, DL));
434       if (PartEVT == ValueVT)
435         return Val;
436       if (PartEVT.isInteger() && ValueVT.isFloatingPoint())
437         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
438 
439       // Vector/Vector bitcast (e.g. <2 x bfloat> -> <2 x half>).
440       if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits())
441         return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
442     }
443 
444     // Promoted vector extract
445     return DAG.getAnyExtOrTrunc(Val, DL, ValueVT);
446   }
447 
448   // Trivial bitcast if the types are the same size and the destination
449   // vector type is legal.
450   if (PartEVT.getSizeInBits() == ValueVT.getSizeInBits() &&
451       TLI.isTypeLegal(ValueVT))
452     return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
453 
454   if (ValueVT.getVectorNumElements() != 1) {
455      // Certain ABIs require that vectors are passed as integers. For vectors
456      // are the same size, this is an obvious bitcast.
457      if (ValueVT.getSizeInBits() == PartEVT.getSizeInBits()) {
458        return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
459      } else if (ValueVT.bitsLT(PartEVT)) {
460        const uint64_t ValueSize = ValueVT.getFixedSizeInBits();
461        EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
462        // Drop the extra bits.
463        Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
464        return DAG.getBitcast(ValueVT, Val);
465      }
466 
467      diagnosePossiblyInvalidConstraint(
468          *DAG.getContext(), V, "non-trivial scalar-to-vector conversion");
469      return DAG.getUNDEF(ValueVT);
470   }
471 
472   // Handle cases such as i8 -> <1 x i1>
473   EVT ValueSVT = ValueVT.getVectorElementType();
474   if (ValueVT.getVectorNumElements() == 1 && ValueSVT != PartEVT) {
475     unsigned ValueSize = ValueSVT.getSizeInBits();
476     if (ValueSize == PartEVT.getSizeInBits()) {
477       Val = DAG.getNode(ISD::BITCAST, DL, ValueSVT, Val);
478     } else if (ValueSVT.isFloatingPoint() && PartEVT.isInteger()) {
479       // It's possible a scalar floating point type gets softened to integer and
480       // then promoted to a larger integer. If PartEVT is the larger integer
481       // we need to truncate it and then bitcast to the FP type.
482       assert(ValueSVT.bitsLT(PartEVT) && "Unexpected types");
483       EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
484       Val = DAG.getNode(ISD::TRUNCATE, DL, IntermediateType, Val);
485       Val = DAG.getBitcast(ValueSVT, Val);
486     } else {
487       Val = ValueVT.isFloatingPoint()
488                 ? DAG.getFPExtendOrRound(Val, DL, ValueSVT)
489                 : DAG.getAnyExtOrTrunc(Val, DL, ValueSVT);
490     }
491   }
492 
493   return DAG.getBuildVector(ValueVT, DL, Val);
494 }
495 
496 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &dl,
497                                  SDValue Val, SDValue *Parts, unsigned NumParts,
498                                  MVT PartVT, const Value *V,
499                                  std::optional<CallingConv::ID> CallConv);
500 
501 /// getCopyToParts - Create a series of nodes that contain the specified value
502 /// split into legal parts.  If the parts contain more bits than Val, then, for
503 /// integers, ExtendKind can be used to specify how to generate the extra bits.
504 static void
505 getCopyToParts(SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
506                unsigned NumParts, MVT PartVT, const Value *V,
507                std::optional<CallingConv::ID> CallConv = std::nullopt,
508                ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
509   // Let the target split the parts if it wants to
510   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
511   if (TLI.splitValueIntoRegisterParts(DAG, DL, Val, Parts, NumParts, PartVT,
512                                       CallConv))
513     return;
514   EVT ValueVT = Val.getValueType();
515 
516   // Handle the vector case separately.
517   if (ValueVT.isVector())
518     return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V,
519                                 CallConv);
520 
521   unsigned OrigNumParts = NumParts;
522   assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
523          "Copying to an illegal type!");
524 
525   if (NumParts == 0)
526     return;
527 
528   assert(!ValueVT.isVector() && "Vector case handled elsewhere");
529   EVT PartEVT = PartVT;
530   if (PartEVT == ValueVT) {
531     assert(NumParts == 1 && "No-op copy with multiple parts!");
532     Parts[0] = Val;
533     return;
534   }
535 
536   unsigned PartBits = PartVT.getSizeInBits();
537   if (NumParts * PartBits > ValueVT.getSizeInBits()) {
538     // If the parts cover more bits than the value has, promote the value.
539     if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
540       assert(NumParts == 1 && "Do not know what to promote to!");
541       Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
542     } else {
543       if (ValueVT.isFloatingPoint()) {
544         // FP values need to be bitcast, then extended if they are being put
545         // into a larger container.
546         ValueVT = EVT::getIntegerVT(*DAG.getContext(),  ValueVT.getSizeInBits());
547         Val = DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
548       }
549       assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
550              ValueVT.isInteger() &&
551              "Unknown mismatch!");
552       ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
553       Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
554       if (PartVT == MVT::x86mmx)
555         Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
556     }
557   } else if (PartBits == ValueVT.getSizeInBits()) {
558     // Different types of the same size.
559     assert(NumParts == 1 && PartEVT != ValueVT);
560     Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
561   } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
562     // If the parts cover less bits than value has, truncate the value.
563     assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
564            ValueVT.isInteger() &&
565            "Unknown mismatch!");
566     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
567     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
568     if (PartVT == MVT::x86mmx)
569       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
570   }
571 
572   // The value may have changed - recompute ValueVT.
573   ValueVT = Val.getValueType();
574   assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
575          "Failed to tile the value with PartVT!");
576 
577   if (NumParts == 1) {
578     if (PartEVT != ValueVT) {
579       diagnosePossiblyInvalidConstraint(*DAG.getContext(), V,
580                                         "scalar-to-vector conversion failed");
581       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
582     }
583 
584     Parts[0] = Val;
585     return;
586   }
587 
588   // Expand the value into multiple parts.
589   if (NumParts & (NumParts - 1)) {
590     // The number of parts is not a power of 2.  Split off and copy the tail.
591     assert(PartVT.isInteger() && ValueVT.isInteger() &&
592            "Do not know what to expand to!");
593     unsigned RoundParts = llvm::bit_floor(NumParts);
594     unsigned RoundBits = RoundParts * PartBits;
595     unsigned OddParts = NumParts - RoundParts;
596     SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
597       DAG.getShiftAmountConstant(RoundBits, ValueVT, DL));
598 
599     getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V,
600                    CallConv);
601 
602     if (DAG.getDataLayout().isBigEndian())
603       // The odd parts were reversed by getCopyToParts - unreverse them.
604       std::reverse(Parts + RoundParts, Parts + NumParts);
605 
606     NumParts = RoundParts;
607     ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
608     Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
609   }
610 
611   // The number of parts is a power of 2.  Repeatedly bisect the value using
612   // EXTRACT_ELEMENT.
613   Parts[0] = DAG.getNode(ISD::BITCAST, DL,
614                          EVT::getIntegerVT(*DAG.getContext(),
615                                            ValueVT.getSizeInBits()),
616                          Val);
617 
618   for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
619     for (unsigned i = 0; i < NumParts; i += StepSize) {
620       unsigned ThisBits = StepSize * PartBits / 2;
621       EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
622       SDValue &Part0 = Parts[i];
623       SDValue &Part1 = Parts[i+StepSize/2];
624 
625       Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
626                           ThisVT, Part0, DAG.getIntPtrConstant(1, DL));
627       Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
628                           ThisVT, Part0, DAG.getIntPtrConstant(0, DL));
629 
630       if (ThisBits == PartBits && ThisVT != PartVT) {
631         Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
632         Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
633       }
634     }
635   }
636 
637   if (DAG.getDataLayout().isBigEndian())
638     std::reverse(Parts, Parts + OrigNumParts);
639 }
640 
641 static SDValue widenVectorToPartType(SelectionDAG &DAG, SDValue Val,
642                                      const SDLoc &DL, EVT PartVT) {
643   if (!PartVT.isVector())
644     return SDValue();
645 
646   EVT ValueVT = Val.getValueType();
647   EVT PartEVT = PartVT.getVectorElementType();
648   EVT ValueEVT = ValueVT.getVectorElementType();
649   ElementCount PartNumElts = PartVT.getVectorElementCount();
650   ElementCount ValueNumElts = ValueVT.getVectorElementCount();
651 
652   // We only support widening vectors with equivalent element types and
653   // fixed/scalable properties. If a target needs to widen a fixed-length type
654   // to a scalable one, it should be possible to use INSERT_SUBVECTOR below.
655   if (ElementCount::isKnownLE(PartNumElts, ValueNumElts) ||
656       PartNumElts.isScalable() != ValueNumElts.isScalable())
657     return SDValue();
658 
659   // Have a try for bf16 because some targets share its ABI with fp16.
660   if (ValueEVT == MVT::bf16 && PartEVT == MVT::f16) {
661     assert(DAG.getTargetLoweringInfo().isTypeLegal(PartVT) &&
662            "Cannot widen to illegal type");
663     Val = DAG.getNode(ISD::BITCAST, DL,
664                       ValueVT.changeVectorElementType(MVT::f16), Val);
665   } else if (PartEVT != ValueEVT) {
666     return SDValue();
667   }
668 
669   // Widening a scalable vector to another scalable vector is done by inserting
670   // the vector into a larger undef one.
671   if (PartNumElts.isScalable())
672     return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
673                        Val, DAG.getVectorIdxConstant(0, DL));
674 
675   // Vector widening case, e.g. <2 x float> -> <4 x float>.  Shuffle in
676   // undef elements.
677   SmallVector<SDValue, 16> Ops;
678   DAG.ExtractVectorElements(Val, Ops);
679   SDValue EltUndef = DAG.getUNDEF(PartEVT);
680   Ops.append((PartNumElts - ValueNumElts).getFixedValue(), EltUndef);
681 
682   // FIXME: Use CONCAT for 2x -> 4x.
683   return DAG.getBuildVector(PartVT, DL, Ops);
684 }
685 
686 /// getCopyToPartsVector - Create a series of nodes that contain the specified
687 /// value split into legal parts.
688 static void getCopyToPartsVector(SelectionDAG &DAG, const SDLoc &DL,
689                                  SDValue Val, SDValue *Parts, unsigned NumParts,
690                                  MVT PartVT, const Value *V,
691                                  std::optional<CallingConv::ID> CallConv) {
692   EVT ValueVT = Val.getValueType();
693   assert(ValueVT.isVector() && "Not a vector");
694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
695   const bool IsABIRegCopy = CallConv.has_value();
696 
697   if (NumParts == 1) {
698     EVT PartEVT = PartVT;
699     if (PartEVT == ValueVT) {
700       // Nothing to do.
701     } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
702       // Bitconvert vector->vector case.
703       Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
704     } else if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, PartVT)) {
705       Val = Widened;
706     } else if (PartVT.isVector() &&
707                PartEVT.getVectorElementType().bitsGE(
708                    ValueVT.getVectorElementType()) &&
709                PartEVT.getVectorElementCount() ==
710                    ValueVT.getVectorElementCount()) {
711 
712       // Promoted vector extract
713       Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
714     } else if (PartEVT.isVector() &&
715                PartEVT.getVectorElementType() !=
716                    ValueVT.getVectorElementType() &&
717                TLI.getTypeAction(*DAG.getContext(), ValueVT) ==
718                    TargetLowering::TypeWidenVector) {
719       // Combination of widening and promotion.
720       EVT WidenVT =
721           EVT::getVectorVT(*DAG.getContext(), ValueVT.getVectorElementType(),
722                            PartVT.getVectorElementCount());
723       SDValue Widened = widenVectorToPartType(DAG, Val, DL, WidenVT);
724       Val = DAG.getAnyExtOrTrunc(Widened, DL, PartVT);
725     } else {
726       // Don't extract an integer from a float vector. This can happen if the
727       // FP type gets softened to integer and then promoted. The promotion
728       // prevents it from being picked up by the earlier bitcast case.
729       if (ValueVT.getVectorElementCount().isScalar() &&
730           (!ValueVT.isFloatingPoint() || !PartVT.isInteger())) {
731         // If we reach this condition and PartVT is FP, this means that
732         // ValueVT is also FP and both have a different size, otherwise we
733         // would have bitcasted them. Producing an EXTRACT_VECTOR_ELT here
734         // would be invalid since that would mean the smaller FP type has to
735         // be extended to the larger one.
736         if (PartVT.isFloatingPoint()) {
737           Val = DAG.getBitcast(ValueVT.getScalarType(), Val);
738           Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
739         } else
740           Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, PartVT, Val,
741                             DAG.getVectorIdxConstant(0, DL));
742       } else {
743         uint64_t ValueSize = ValueVT.getFixedSizeInBits();
744         assert(PartVT.getFixedSizeInBits() > ValueSize &&
745                "lossy conversion of vector to scalar type");
746         EVT IntermediateType = EVT::getIntegerVT(*DAG.getContext(), ValueSize);
747         Val = DAG.getBitcast(IntermediateType, Val);
748         Val = DAG.getAnyExtOrTrunc(Val, DL, PartVT);
749       }
750     }
751 
752     assert(Val.getValueType() == PartVT && "Unexpected vector part value type");
753     Parts[0] = Val;
754     return;
755   }
756 
757   // Handle a multi-element vector.
758   EVT IntermediateVT;
759   MVT RegisterVT;
760   unsigned NumIntermediates;
761   unsigned NumRegs;
762   if (IsABIRegCopy) {
763     NumRegs = TLI.getVectorTypeBreakdownForCallingConv(
764         *DAG.getContext(), *CallConv, ValueVT, IntermediateVT, NumIntermediates,
765         RegisterVT);
766   } else {
767     NumRegs =
768         TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
769                                    NumIntermediates, RegisterVT);
770   }
771 
772   assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
773   NumParts = NumRegs; // Silence a compiler warning.
774   assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
775 
776   assert(IntermediateVT.isScalableVector() == ValueVT.isScalableVector() &&
777          "Mixing scalable and fixed vectors when copying in parts");
778 
779   std::optional<ElementCount> DestEltCnt;
780 
781   if (IntermediateVT.isVector())
782     DestEltCnt = IntermediateVT.getVectorElementCount() * NumIntermediates;
783   else
784     DestEltCnt = ElementCount::getFixed(NumIntermediates);
785 
786   EVT BuiltVectorTy = EVT::getVectorVT(
787       *DAG.getContext(), IntermediateVT.getScalarType(), *DestEltCnt);
788 
789   if (ValueVT == BuiltVectorTy) {
790     // Nothing to do.
791   } else if (ValueVT.getSizeInBits() == BuiltVectorTy.getSizeInBits()) {
792     // Bitconvert vector->vector case.
793     Val = DAG.getNode(ISD::BITCAST, DL, BuiltVectorTy, Val);
794   } else {
795     if (BuiltVectorTy.getVectorElementType().bitsGT(
796             ValueVT.getVectorElementType())) {
797       // Integer promotion.
798       ValueVT = EVT::getVectorVT(*DAG.getContext(),
799                                  BuiltVectorTy.getVectorElementType(),
800                                  ValueVT.getVectorElementCount());
801       Val = DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
802     }
803 
804     if (SDValue Widened = widenVectorToPartType(DAG, Val, DL, BuiltVectorTy)) {
805       Val = Widened;
806     }
807   }
808 
809   assert(Val.getValueType() == BuiltVectorTy && "Unexpected vector value type");
810 
811   // Split the vector into intermediate operands.
812   SmallVector<SDValue, 8> Ops(NumIntermediates);
813   for (unsigned i = 0; i != NumIntermediates; ++i) {
814     if (IntermediateVT.isVector()) {
815       // This does something sensible for scalable vectors - see the
816       // definition of EXTRACT_SUBVECTOR for further details.
817       unsigned IntermediateNumElts = IntermediateVT.getVectorMinNumElements();
818       Ops[i] =
819           DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, IntermediateVT, Val,
820                       DAG.getVectorIdxConstant(i * IntermediateNumElts, DL));
821     } else {
822       Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, IntermediateVT, Val,
823                            DAG.getVectorIdxConstant(i, DL));
824     }
825   }
826 
827   // Split the intermediate operands into legal parts.
828   if (NumParts == NumIntermediates) {
829     // If the register was not expanded, promote or copy the value,
830     // as appropriate.
831     for (unsigned i = 0; i != NumParts; ++i)
832       getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V, CallConv);
833   } else if (NumParts > 0) {
834     // If the intermediate type was expanded, split each the value into
835     // legal parts.
836     assert(NumIntermediates != 0 && "division by zero");
837     assert(NumParts % NumIntermediates == 0 &&
838            "Must expand into a divisible number of parts!");
839     unsigned Factor = NumParts / NumIntermediates;
840     for (unsigned i = 0; i != NumIntermediates; ++i)
841       getCopyToParts(DAG, DL, Ops[i], &Parts[i * Factor], Factor, PartVT, V,
842                      CallConv);
843   }
844 }
845 
846 RegsForValue::RegsForValue(const SmallVector<Register, 4> &regs, MVT regvt,
847                            EVT valuevt, std::optional<CallingConv::ID> CC)
848     : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs),
849       RegCount(1, regs.size()), CallConv(CC) {}
850 
851 RegsForValue::RegsForValue(LLVMContext &Context, const TargetLowering &TLI,
852                            const DataLayout &DL, Register Reg, Type *Ty,
853                            std::optional<CallingConv::ID> CC) {
854   ComputeValueVTs(TLI, DL, Ty, ValueVTs);
855 
856   CallConv = CC;
857 
858   for (EVT ValueVT : ValueVTs) {
859     unsigned NumRegs =
860         isABIMangled()
861             ? TLI.getNumRegistersForCallingConv(Context, *CC, ValueVT)
862             : TLI.getNumRegisters(Context, ValueVT);
863     MVT RegisterVT =
864         isABIMangled()
865             ? TLI.getRegisterTypeForCallingConv(Context, *CC, ValueVT)
866             : TLI.getRegisterType(Context, ValueVT);
867     for (unsigned i = 0; i != NumRegs; ++i)
868       Regs.push_back(Reg + i);
869     RegVTs.push_back(RegisterVT);
870     RegCount.push_back(NumRegs);
871     Reg = Reg.id() + NumRegs;
872   }
873 }
874 
875 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
876                                       FunctionLoweringInfo &FuncInfo,
877                                       const SDLoc &dl, SDValue &Chain,
878                                       SDValue *Glue, const Value *V) const {
879   // A Value with type {} or [0 x %t] needs no registers.
880   if (ValueVTs.empty())
881     return SDValue();
882 
883   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
884 
885   // Assemble the legal parts into the final values.
886   SmallVector<SDValue, 4> Values(ValueVTs.size());
887   SmallVector<SDValue, 8> Parts;
888   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
889     // Copy the legal parts from the registers.
890     EVT ValueVT = ValueVTs[Value];
891     unsigned NumRegs = RegCount[Value];
892     MVT RegisterVT = isABIMangled()
893                          ? TLI.getRegisterTypeForCallingConv(
894                                *DAG.getContext(), *CallConv, RegVTs[Value])
895                          : RegVTs[Value];
896 
897     Parts.resize(NumRegs);
898     for (unsigned i = 0; i != NumRegs; ++i) {
899       SDValue P;
900       if (!Glue) {
901         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
902       } else {
903         P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Glue);
904         *Glue = P.getValue(2);
905       }
906 
907       Chain = P.getValue(1);
908       Parts[i] = P;
909 
910       // If the source register was virtual and if we know something about it,
911       // add an assert node.
912       if (!Register::isVirtualRegister(Regs[Part + i]) ||
913           !RegisterVT.isInteger())
914         continue;
915 
916       const FunctionLoweringInfo::LiveOutInfo *LOI =
917         FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
918       if (!LOI)
919         continue;
920 
921       unsigned RegSize = RegisterVT.getScalarSizeInBits();
922       unsigned NumSignBits = LOI->NumSignBits;
923       unsigned NumZeroBits = LOI->Known.countMinLeadingZeros();
924 
925       if (NumZeroBits == RegSize) {
926         // The current value is a zero.
927         // Explicitly express that as it would be easier for
928         // optimizations to kick in.
929         Parts[i] = DAG.getConstant(0, dl, RegisterVT);
930         continue;
931       }
932 
933       // FIXME: We capture more information than the dag can represent.  For
934       // now, just use the tightest assertzext/assertsext possible.
935       bool isSExt;
936       EVT FromVT(MVT::Other);
937       if (NumZeroBits) {
938         FromVT = EVT::getIntegerVT(*DAG.getContext(), RegSize - NumZeroBits);
939         isSExt = false;
940       } else if (NumSignBits > 1) {
941         FromVT =
942             EVT::getIntegerVT(*DAG.getContext(), RegSize - NumSignBits + 1);
943         isSExt = true;
944       } else {
945         continue;
946       }
947       // Add an assertion node.
948       assert(FromVT != MVT::Other);
949       Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
950                              RegisterVT, P, DAG.getValueType(FromVT));
951     }
952 
953     Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(), NumRegs,
954                                      RegisterVT, ValueVT, V, Chain, CallConv);
955     Part += NumRegs;
956     Parts.clear();
957   }
958 
959   return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(ValueVTs), Values);
960 }
961 
962 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
963                                  const SDLoc &dl, SDValue &Chain, SDValue *Glue,
964                                  const Value *V,
965                                  ISD::NodeType PreferredExtendType) const {
966   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
967   ISD::NodeType ExtendKind = PreferredExtendType;
968 
969   // Get the list of the values's legal parts.
970   unsigned NumRegs = Regs.size();
971   SmallVector<SDValue, 8> Parts(NumRegs);
972   for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
973     unsigned NumParts = RegCount[Value];
974 
975     MVT RegisterVT = isABIMangled()
976                          ? TLI.getRegisterTypeForCallingConv(
977                                *DAG.getContext(), *CallConv, RegVTs[Value])
978                          : RegVTs[Value];
979 
980     if (ExtendKind == ISD::ANY_EXTEND && TLI.isZExtFree(Val, RegisterVT))
981       ExtendKind = ISD::ZERO_EXTEND;
982 
983     getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value), &Parts[Part],
984                    NumParts, RegisterVT, V, CallConv, ExtendKind);
985     Part += NumParts;
986   }
987 
988   // Copy the parts into the registers.
989   SmallVector<SDValue, 8> Chains(NumRegs);
990   for (unsigned i = 0; i != NumRegs; ++i) {
991     SDValue Part;
992     if (!Glue) {
993       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
994     } else {
995       Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Glue);
996       *Glue = Part.getValue(1);
997     }
998 
999     Chains[i] = Part.getValue(0);
1000   }
1001 
1002   if (NumRegs == 1 || Glue)
1003     // If NumRegs > 1 && Glue is used then the use of the last CopyToReg is
1004     // flagged to it. That is the CopyToReg nodes and the user are considered
1005     // a single scheduling unit. If we create a TokenFactor and return it as
1006     // chain, then the TokenFactor is both a predecessor (operand) of the
1007     // user as well as a successor (the TF operands are flagged to the user).
1008     // c1, f1 = CopyToReg
1009     // c2, f2 = CopyToReg
1010     // c3     = TokenFactor c1, c2
1011     // ...
1012     //        = op c3, ..., f2
1013     Chain = Chains[NumRegs-1];
1014   else
1015     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
1016 }
1017 
1018 void RegsForValue::AddInlineAsmOperands(InlineAsm::Kind Code, bool HasMatching,
1019                                         unsigned MatchingIdx, const SDLoc &dl,
1020                                         SelectionDAG &DAG,
1021                                         std::vector<SDValue> &Ops) const {
1022   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1023 
1024   InlineAsm::Flag Flag(Code, Regs.size());
1025   if (HasMatching)
1026     Flag.setMatchingOp(MatchingIdx);
1027   else if (!Regs.empty() && Register::isVirtualRegister(Regs.front())) {
1028     // Put the register class of the virtual registers in the flag word.  That
1029     // way, later passes can recompute register class constraints for inline
1030     // assembly as well as normal instructions.
1031     // Don't do this for tied operands that can use the regclass information
1032     // from the def.
1033     const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1034     const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
1035     Flag.setRegClass(RC->getID());
1036   }
1037 
1038   SDValue Res = DAG.getTargetConstant(Flag, dl, MVT::i32);
1039   Ops.push_back(Res);
1040 
1041   if (Code == InlineAsm::Kind::Clobber) {
1042     // Clobbers should always have a 1:1 mapping with registers, and may
1043     // reference registers that have illegal (e.g. vector) types. Hence, we
1044     // shouldn't try to apply any sort of splitting logic to them.
1045     assert(Regs.size() == RegVTs.size() && Regs.size() == ValueVTs.size() &&
1046            "No 1:1 mapping from clobbers to regs?");
1047     Register SP = TLI.getStackPointerRegisterToSaveRestore();
1048     (void)SP;
1049     for (unsigned I = 0, E = ValueVTs.size(); I != E; ++I) {
1050       Ops.push_back(DAG.getRegister(Regs[I], RegVTs[I]));
1051       assert(
1052           (Regs[I] != SP ||
1053            DAG.getMachineFunction().getFrameInfo().hasOpaqueSPAdjustment()) &&
1054           "If we clobbered the stack pointer, MFI should know about it.");
1055     }
1056     return;
1057   }
1058 
1059   for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
1060     MVT RegisterVT = RegVTs[Value];
1061     unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value],
1062                                            RegisterVT);
1063     for (unsigned i = 0; i != NumRegs; ++i) {
1064       assert(Reg < Regs.size() && "Mismatch in # registers expected");
1065       unsigned TheReg = Regs[Reg++];
1066       Ops.push_back(DAG.getRegister(TheReg, RegisterVT));
1067     }
1068   }
1069 }
1070 
1071 SmallVector<std::pair<Register, TypeSize>, 4>
1072 RegsForValue::getRegsAndSizes() const {
1073   SmallVector<std::pair<Register, TypeSize>, 4> OutVec;
1074   unsigned I = 0;
1075   for (auto CountAndVT : zip_first(RegCount, RegVTs)) {
1076     unsigned RegCount = std::get<0>(CountAndVT);
1077     MVT RegisterVT = std::get<1>(CountAndVT);
1078     TypeSize RegisterSize = RegisterVT.getSizeInBits();
1079     for (unsigned E = I + RegCount; I != E; ++I)
1080       OutVec.push_back(std::make_pair(Regs[I], RegisterSize));
1081   }
1082   return OutVec;
1083 }
1084 
1085 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, BatchAAResults *aa,
1086                                AssumptionCache *ac,
1087                                const TargetLibraryInfo *li) {
1088   BatchAA = aa;
1089   AC = ac;
1090   GFI = gfi;
1091   LibInfo = li;
1092   Context = DAG.getContext();
1093   LPadToCallSiteMap.clear();
1094   SL->init(DAG.getTargetLoweringInfo(), TM, DAG.getDataLayout());
1095   AssignmentTrackingEnabled = isAssignmentTrackingEnabled(
1096       *DAG.getMachineFunction().getFunction().getParent());
1097 }
1098 
1099 void SelectionDAGBuilder::clear() {
1100   NodeMap.clear();
1101   UnusedArgNodeMap.clear();
1102   PendingLoads.clear();
1103   PendingExports.clear();
1104   PendingConstrainedFP.clear();
1105   PendingConstrainedFPStrict.clear();
1106   CurInst = nullptr;
1107   HasTailCall = false;
1108   SDNodeOrder = LowestSDNodeOrder;
1109   StatepointLowering.clear();
1110 }
1111 
1112 void SelectionDAGBuilder::clearDanglingDebugInfo() {
1113   DanglingDebugInfoMap.clear();
1114 }
1115 
1116 // Update DAG root to include dependencies on Pending chains.
1117 SDValue SelectionDAGBuilder::updateRoot(SmallVectorImpl<SDValue> &Pending) {
1118   SDValue Root = DAG.getRoot();
1119 
1120   if (Pending.empty())
1121     return Root;
1122 
1123   // Add current root to PendingChains, unless we already indirectly
1124   // depend on it.
1125   if (Root.getOpcode() != ISD::EntryToken) {
1126     unsigned i = 0, e = Pending.size();
1127     for (; i != e; ++i) {
1128       assert(Pending[i].getNode()->getNumOperands() > 1);
1129       if (Pending[i].getNode()->getOperand(0) == Root)
1130         break;  // Don't add the root if we already indirectly depend on it.
1131     }
1132 
1133     if (i == e)
1134       Pending.push_back(Root);
1135   }
1136 
1137   if (Pending.size() == 1)
1138     Root = Pending[0];
1139   else
1140     Root = DAG.getTokenFactor(getCurSDLoc(), Pending);
1141 
1142   DAG.setRoot(Root);
1143   Pending.clear();
1144   return Root;
1145 }
1146 
1147 SDValue SelectionDAGBuilder::getMemoryRoot() {
1148   return updateRoot(PendingLoads);
1149 }
1150 
1151 SDValue SelectionDAGBuilder::getRoot() {
1152   // Chain up all pending constrained intrinsics together with all
1153   // pending loads, by simply appending them to PendingLoads and
1154   // then calling getMemoryRoot().
1155   PendingLoads.reserve(PendingLoads.size() +
1156                        PendingConstrainedFP.size() +
1157                        PendingConstrainedFPStrict.size());
1158   PendingLoads.append(PendingConstrainedFP.begin(),
1159                       PendingConstrainedFP.end());
1160   PendingLoads.append(PendingConstrainedFPStrict.begin(),
1161                       PendingConstrainedFPStrict.end());
1162   PendingConstrainedFP.clear();
1163   PendingConstrainedFPStrict.clear();
1164   return getMemoryRoot();
1165 }
1166 
1167 SDValue SelectionDAGBuilder::getControlRoot() {
1168   // We need to emit pending fpexcept.strict constrained intrinsics,
1169   // so append them to the PendingExports list.
1170   PendingExports.append(PendingConstrainedFPStrict.begin(),
1171                         PendingConstrainedFPStrict.end());
1172   PendingConstrainedFPStrict.clear();
1173   return updateRoot(PendingExports);
1174 }
1175 
1176 void SelectionDAGBuilder::handleDebugDeclare(Value *Address,
1177                                              DILocalVariable *Variable,
1178                                              DIExpression *Expression,
1179                                              DebugLoc DL) {
1180   assert(Variable && "Missing variable");
1181 
1182   // Check if address has undef value.
1183   if (!Address || isa<UndefValue>(Address) ||
1184       (Address->use_empty() && !isa<Argument>(Address))) {
1185     LLVM_DEBUG(
1186         dbgs()
1187         << "dbg_declare: Dropping debug info (bad/undef/unused-arg address)\n");
1188     return;
1189   }
1190 
1191   bool IsParameter = Variable->isParameter() || isa<Argument>(Address);
1192 
1193   SDValue &N = NodeMap[Address];
1194   if (!N.getNode() && isa<Argument>(Address))
1195     // Check unused arguments map.
1196     N = UnusedArgNodeMap[Address];
1197   SDDbgValue *SDV;
1198   if (N.getNode()) {
1199     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
1200       Address = BCI->getOperand(0);
1201     // Parameters are handled specially.
1202     auto *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
1203     if (IsParameter && FINode) {
1204       // Byval parameter. We have a frame index at this point.
1205       SDV = DAG.getFrameIndexDbgValue(Variable, Expression, FINode->getIndex(),
1206                                       /*IsIndirect*/ true, DL, SDNodeOrder);
1207     } else if (isa<Argument>(Address)) {
1208       // Address is an argument, so try to emit its dbg value using
1209       // virtual register info from the FuncInfo.ValueMap.
1210       EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1211                                FuncArgumentDbgValueKind::Declare, N);
1212       return;
1213     } else {
1214       SDV = DAG.getDbgValue(Variable, Expression, N.getNode(), N.getResNo(),
1215                             true, DL, SDNodeOrder);
1216     }
1217     DAG.AddDbgValue(SDV, IsParameter);
1218   } else {
1219     // If Address is an argument then try to emit its dbg value using
1220     // virtual register info from the FuncInfo.ValueMap.
1221     if (!EmitFuncArgumentDbgValue(Address, Variable, Expression, DL,
1222                                   FuncArgumentDbgValueKind::Declare, N)) {
1223       LLVM_DEBUG(dbgs() << "dbg_declare: Dropping debug info"
1224                         << " (could not emit func-arg dbg_value)\n");
1225     }
1226   }
1227 }
1228 
1229 void SelectionDAGBuilder::visitDbgInfo(const Instruction &I) {
1230   // Add SDDbgValue nodes for any var locs here. Do so before updating
1231   // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1232   if (FunctionVarLocs const *FnVarLocs = DAG.getFunctionVarLocs()) {
1233     // Add SDDbgValue nodes for any var locs here. Do so before updating
1234     // SDNodeOrder, as this mapping is {Inst -> Locs BEFORE Inst}.
1235     for (auto It = FnVarLocs->locs_begin(&I), End = FnVarLocs->locs_end(&I);
1236          It != End; ++It) {
1237       auto *Var = FnVarLocs->getDILocalVariable(It->VariableID);
1238       dropDanglingDebugInfo(Var, It->Expr);
1239       if (It->Values.isKillLocation(It->Expr)) {
1240         handleKillDebugValue(Var, It->Expr, It->DL, SDNodeOrder);
1241         continue;
1242       }
1243       SmallVector<Value *> Values(It->Values.location_ops());
1244       if (!handleDebugValue(Values, Var, It->Expr, It->DL, SDNodeOrder,
1245                             It->Values.hasArgList())) {
1246         SmallVector<Value *, 4> Vals(It->Values.location_ops());
1247         addDanglingDebugInfo(Vals,
1248                              FnVarLocs->getDILocalVariable(It->VariableID),
1249                              It->Expr, Vals.size() > 1, It->DL, SDNodeOrder);
1250       }
1251     }
1252   }
1253 
1254   // We must skip DbgVariableRecords if they've already been processed above as
1255   // we have just emitted the debug values resulting from assignment tracking
1256   // analysis, making any existing DbgVariableRecords redundant (and probably
1257   // less correct). We still need to process DbgLabelRecords. This does sink
1258   // DbgLabelRecords to the bottom of the group of debug records. That sholdn't
1259   // be important as it does so deterministcally and ordering between
1260   // DbgLabelRecords and DbgVariableRecords is immaterial (other than for MIR/IR
1261   // printing).
1262   bool SkipDbgVariableRecords = DAG.getFunctionVarLocs();
1263   // Is there is any debug-info attached to this instruction, in the form of
1264   // DbgRecord non-instruction debug-info records.
1265   for (DbgRecord &DR : I.getDbgRecordRange()) {
1266     if (DbgLabelRecord *DLR = dyn_cast<DbgLabelRecord>(&DR)) {
1267       assert(DLR->getLabel() && "Missing label");
1268       SDDbgLabel *SDV =
1269           DAG.getDbgLabel(DLR->getLabel(), DLR->getDebugLoc(), SDNodeOrder);
1270       DAG.AddDbgLabel(SDV);
1271       continue;
1272     }
1273 
1274     if (SkipDbgVariableRecords)
1275       continue;
1276     DbgVariableRecord &DVR = cast<DbgVariableRecord>(DR);
1277     DILocalVariable *Variable = DVR.getVariable();
1278     DIExpression *Expression = DVR.getExpression();
1279     dropDanglingDebugInfo(Variable, Expression);
1280 
1281     if (DVR.getType() == DbgVariableRecord::LocationType::Declare) {
1282       if (FuncInfo.PreprocessedDVRDeclares.contains(&DVR))
1283         continue;
1284       LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DVR
1285                         << "\n");
1286       handleDebugDeclare(DVR.getVariableLocationOp(0), Variable, Expression,
1287                          DVR.getDebugLoc());
1288       continue;
1289     }
1290 
1291     // A DbgVariableRecord with no locations is a kill location.
1292     SmallVector<Value *, 4> Values(DVR.location_ops());
1293     if (Values.empty()) {
1294       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1295                            SDNodeOrder);
1296       continue;
1297     }
1298 
1299     // A DbgVariableRecord with an undef or absent location is also a kill
1300     // location.
1301     if (llvm::any_of(Values,
1302                      [](Value *V) { return !V || isa<UndefValue>(V); })) {
1303       handleKillDebugValue(Variable, Expression, DVR.getDebugLoc(),
1304                            SDNodeOrder);
1305       continue;
1306     }
1307 
1308     bool IsVariadic = DVR.hasArgList();
1309     if (!handleDebugValue(Values, Variable, Expression, DVR.getDebugLoc(),
1310                           SDNodeOrder, IsVariadic)) {
1311       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
1312                            DVR.getDebugLoc(), SDNodeOrder);
1313     }
1314   }
1315 }
1316 
1317 void SelectionDAGBuilder::visit(const Instruction &I) {
1318   visitDbgInfo(I);
1319 
1320   // Set up outgoing PHI node register values before emitting the terminator.
1321   if (I.isTerminator()) {
1322     HandlePHINodesInSuccessorBlocks(I.getParent());
1323   }
1324 
1325   // Increase the SDNodeOrder if dealing with a non-debug instruction.
1326   if (!isa<DbgInfoIntrinsic>(I))
1327     ++SDNodeOrder;
1328 
1329   CurInst = &I;
1330 
1331   // Set inserted listener only if required.
1332   bool NodeInserted = false;
1333   std::unique_ptr<SelectionDAG::DAGNodeInsertedListener> InsertedListener;
1334   MDNode *PCSectionsMD = I.getMetadata(LLVMContext::MD_pcsections);
1335   MDNode *MMRA = I.getMetadata(LLVMContext::MD_mmra);
1336   if (PCSectionsMD || MMRA) {
1337     InsertedListener = std::make_unique<SelectionDAG::DAGNodeInsertedListener>(
1338         DAG, [&](SDNode *) { NodeInserted = true; });
1339   }
1340 
1341   visit(I.getOpcode(), I);
1342 
1343   if (!I.isTerminator() && !HasTailCall &&
1344       !isa<GCStatepointInst>(I)) // statepoints handle their exports internally
1345     CopyToExportRegsIfNeeded(&I);
1346 
1347   // Handle metadata.
1348   if (PCSectionsMD || MMRA) {
1349     auto It = NodeMap.find(&I);
1350     if (It != NodeMap.end()) {
1351       if (PCSectionsMD)
1352         DAG.addPCSections(It->second.getNode(), PCSectionsMD);
1353       if (MMRA)
1354         DAG.addMMRAMetadata(It->second.getNode(), MMRA);
1355     } else if (NodeInserted) {
1356       // This should not happen; if it does, don't let it go unnoticed so we can
1357       // fix it. Relevant visit*() function is probably missing a setValue().
1358       errs() << "warning: loosing !pcsections and/or !mmra metadata ["
1359              << I.getModule()->getName() << "]\n";
1360       LLVM_DEBUG(I.dump());
1361       assert(false);
1362     }
1363   }
1364 
1365   CurInst = nullptr;
1366 }
1367 
1368 void SelectionDAGBuilder::visitPHI(const PHINode &) {
1369   llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
1370 }
1371 
1372 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
1373   // Note: this doesn't use InstVisitor, because it has to work with
1374   // ConstantExpr's in addition to instructions.
1375   switch (Opcode) {
1376   default: llvm_unreachable("Unknown instruction type encountered!");
1377     // Build the switch statement using the Instruction.def file.
1378 #define HANDLE_INST(NUM, OPCODE, CLASS) \
1379     case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
1380 #include "llvm/IR/Instruction.def"
1381   }
1382 }
1383 
1384 static bool handleDanglingVariadicDebugInfo(SelectionDAG &DAG,
1385                                             DILocalVariable *Variable,
1386                                             DebugLoc DL, unsigned Order,
1387                                             SmallVectorImpl<Value *> &Values,
1388                                             DIExpression *Expression) {
1389   // For variadic dbg_values we will now insert an undef.
1390   // FIXME: We can potentially recover these!
1391   SmallVector<SDDbgOperand, 2> Locs;
1392   for (const Value *V : Values) {
1393     auto *Undef = UndefValue::get(V->getType());
1394     Locs.push_back(SDDbgOperand::fromConst(Undef));
1395   }
1396   SDDbgValue *SDV = DAG.getDbgValueList(Variable, Expression, Locs, {},
1397                                         /*IsIndirect=*/false, DL, Order,
1398                                         /*IsVariadic=*/true);
1399   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1400   return true;
1401 }
1402 
1403 void SelectionDAGBuilder::addDanglingDebugInfo(SmallVectorImpl<Value *> &Values,
1404                                                DILocalVariable *Var,
1405                                                DIExpression *Expr,
1406                                                bool IsVariadic, DebugLoc DL,
1407                                                unsigned Order) {
1408   if (IsVariadic) {
1409     handleDanglingVariadicDebugInfo(DAG, Var, DL, Order, Values, Expr);
1410     return;
1411   }
1412   // TODO: Dangling debug info will eventually either be resolved or produce
1413   // an Undef DBG_VALUE. However in the resolution case, a gap may appear
1414   // between the original dbg.value location and its resolved DBG_VALUE,
1415   // which we should ideally fill with an extra Undef DBG_VALUE.
1416   assert(Values.size() == 1);
1417   DanglingDebugInfoMap[Values[0]].emplace_back(Var, Expr, DL, Order);
1418 }
1419 
1420 void SelectionDAGBuilder::dropDanglingDebugInfo(const DILocalVariable *Variable,
1421                                                 const DIExpression *Expr) {
1422   auto isMatchingDbgValue = [&](DanglingDebugInfo &DDI) {
1423     DIVariable *DanglingVariable = DDI.getVariable();
1424     DIExpression *DanglingExpr = DDI.getExpression();
1425     if (DanglingVariable == Variable && Expr->fragmentsOverlap(DanglingExpr)) {
1426       LLVM_DEBUG(dbgs() << "Dropping dangling debug info for "
1427                         << printDDI(nullptr, DDI) << "\n");
1428       return true;
1429     }
1430     return false;
1431   };
1432 
1433   for (auto &DDIMI : DanglingDebugInfoMap) {
1434     DanglingDebugInfoVector &DDIV = DDIMI.second;
1435 
1436     // If debug info is to be dropped, run it through final checks to see
1437     // whether it can be salvaged.
1438     for (auto &DDI : DDIV)
1439       if (isMatchingDbgValue(DDI))
1440         salvageUnresolvedDbgValue(DDIMI.first, DDI);
1441 
1442     erase_if(DDIV, isMatchingDbgValue);
1443   }
1444 }
1445 
1446 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
1447 // generate the debug data structures now that we've seen its definition.
1448 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
1449                                                    SDValue Val) {
1450   auto DanglingDbgInfoIt = DanglingDebugInfoMap.find(V);
1451   if (DanglingDbgInfoIt == DanglingDebugInfoMap.end())
1452     return;
1453 
1454   DanglingDebugInfoVector &DDIV = DanglingDbgInfoIt->second;
1455   for (auto &DDI : DDIV) {
1456     DebugLoc DL = DDI.getDebugLoc();
1457     unsigned ValSDNodeOrder = Val.getNode()->getIROrder();
1458     unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
1459     DILocalVariable *Variable = DDI.getVariable();
1460     DIExpression *Expr = DDI.getExpression();
1461     assert(Variable->isValidLocationForIntrinsic(DL) &&
1462            "Expected inlined-at fields to agree");
1463     SDDbgValue *SDV;
1464     if (Val.getNode()) {
1465       // FIXME: I doubt that it is correct to resolve a dangling DbgValue as a
1466       // FuncArgumentDbgValue (it would be hoisted to the function entry, and if
1467       // we couldn't resolve it directly when examining the DbgValue intrinsic
1468       // in the first place we should not be more successful here). Unless we
1469       // have some test case that prove this to be correct we should avoid
1470       // calling EmitFuncArgumentDbgValue here.
1471       if (!EmitFuncArgumentDbgValue(V, Variable, Expr, DL,
1472                                     FuncArgumentDbgValueKind::Value, Val)) {
1473         LLVM_DEBUG(dbgs() << "Resolve dangling debug info for "
1474                           << printDDI(V, DDI) << "\n");
1475         LLVM_DEBUG(dbgs() << "  By mapping to:\n    "; Val.dump());
1476         // Increase the SDNodeOrder for the DbgValue here to make sure it is
1477         // inserted after the definition of Val when emitting the instructions
1478         // after ISel. An alternative could be to teach
1479         // ScheduleDAGSDNodes::EmitSchedule to delay the insertion properly.
1480         LLVM_DEBUG(if (ValSDNodeOrder > DbgSDNodeOrder) dbgs()
1481                    << "changing SDNodeOrder from " << DbgSDNodeOrder << " to "
1482                    << ValSDNodeOrder << "\n");
1483         SDV = getDbgValue(Val, Variable, Expr, DL,
1484                           std::max(DbgSDNodeOrder, ValSDNodeOrder));
1485         DAG.AddDbgValue(SDV, false);
1486       } else
1487         LLVM_DEBUG(dbgs() << "Resolved dangling debug info for "
1488                           << printDDI(V, DDI)
1489                           << " in EmitFuncArgumentDbgValue\n");
1490     } else {
1491       LLVM_DEBUG(dbgs() << "Dropping debug info for " << printDDI(V, DDI)
1492                         << "\n");
1493       auto Undef = UndefValue::get(V->getType());
1494       auto SDV =
1495           DAG.getConstantDbgValue(Variable, Expr, Undef, DL, DbgSDNodeOrder);
1496       DAG.AddDbgValue(SDV, false);
1497     }
1498   }
1499   DDIV.clear();
1500 }
1501 
1502 void SelectionDAGBuilder::salvageUnresolvedDbgValue(const Value *V,
1503                                                     DanglingDebugInfo &DDI) {
1504   // TODO: For the variadic implementation, instead of only checking the fail
1505   // state of `handleDebugValue`, we need know specifically which values were
1506   // invalid, so that we attempt to salvage only those values when processing
1507   // a DIArgList.
1508   const Value *OrigV = V;
1509   DILocalVariable *Var = DDI.getVariable();
1510   DIExpression *Expr = DDI.getExpression();
1511   DebugLoc DL = DDI.getDebugLoc();
1512   unsigned SDOrder = DDI.getSDNodeOrder();
1513 
1514   // Currently we consider only dbg.value intrinsics -- we tell the salvager
1515   // that DW_OP_stack_value is desired.
1516   bool StackValue = true;
1517 
1518   // Can this Value can be encoded without any further work?
1519   if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false))
1520     return;
1521 
1522   // Attempt to salvage back through as many instructions as possible. Bail if
1523   // a non-instruction is seen, such as a constant expression or global
1524   // variable. FIXME: Further work could recover those too.
1525   while (isa<Instruction>(V)) {
1526     const Instruction &VAsInst = *cast<const Instruction>(V);
1527     // Temporary "0", awaiting real implementation.
1528     SmallVector<uint64_t, 16> Ops;
1529     SmallVector<Value *, 4> AdditionalValues;
1530     V = salvageDebugInfoImpl(const_cast<Instruction &>(VAsInst),
1531                              Expr->getNumLocationOperands(), Ops,
1532                              AdditionalValues);
1533     // If we cannot salvage any further, and haven't yet found a suitable debug
1534     // expression, bail out.
1535     if (!V)
1536       break;
1537 
1538     // TODO: If AdditionalValues isn't empty, then the salvage can only be
1539     // represented with a DBG_VALUE_LIST, so we give up. When we have support
1540     // here for variadic dbg_values, remove that condition.
1541     if (!AdditionalValues.empty())
1542       break;
1543 
1544     // New value and expr now represent this debuginfo.
1545     Expr = DIExpression::appendOpsToArg(Expr, Ops, 0, StackValue);
1546 
1547     // Some kind of simplification occurred: check whether the operand of the
1548     // salvaged debug expression can be encoded in this DAG.
1549     if (handleDebugValue(V, Var, Expr, DL, SDOrder, /*IsVariadic=*/false)) {
1550       LLVM_DEBUG(
1551           dbgs() << "Salvaged debug location info for:\n  " << *Var << "\n"
1552                  << *OrigV << "\nBy stripping back to:\n  " << *V << "\n");
1553       return;
1554     }
1555   }
1556 
1557   // This was the final opportunity to salvage this debug information, and it
1558   // couldn't be done. Place an undef DBG_VALUE at this location to terminate
1559   // any earlier variable location.
1560   assert(OrigV && "V shouldn't be null");
1561   auto *Undef = UndefValue::get(OrigV->getType());
1562   auto *SDV = DAG.getConstantDbgValue(Var, Expr, Undef, DL, SDNodeOrder);
1563   DAG.AddDbgValue(SDV, false);
1564   LLVM_DEBUG(dbgs() << "Dropping debug value info for:\n  "
1565                     << printDDI(OrigV, DDI) << "\n");
1566 }
1567 
1568 void SelectionDAGBuilder::handleKillDebugValue(DILocalVariable *Var,
1569                                                DIExpression *Expr,
1570                                                DebugLoc DbgLoc,
1571                                                unsigned Order) {
1572   Value *Poison = PoisonValue::get(Type::getInt1Ty(*Context));
1573   DIExpression *NewExpr =
1574       const_cast<DIExpression *>(DIExpression::convertToUndefExpression(Expr));
1575   handleDebugValue(Poison, Var, NewExpr, DbgLoc, Order,
1576                    /*IsVariadic*/ false);
1577 }
1578 
1579 bool SelectionDAGBuilder::handleDebugValue(ArrayRef<const Value *> Values,
1580                                            DILocalVariable *Var,
1581                                            DIExpression *Expr, DebugLoc DbgLoc,
1582                                            unsigned Order, bool IsVariadic) {
1583   if (Values.empty())
1584     return true;
1585 
1586   // Filter EntryValue locations out early.
1587   if (visitEntryValueDbgValue(Values, Var, Expr, DbgLoc))
1588     return true;
1589 
1590   SmallVector<SDDbgOperand> LocationOps;
1591   SmallVector<SDNode *> Dependencies;
1592   for (const Value *V : Values) {
1593     // Constant value.
1594     if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V) ||
1595         isa<ConstantPointerNull>(V)) {
1596       LocationOps.emplace_back(SDDbgOperand::fromConst(V));
1597       continue;
1598     }
1599 
1600     // Look through IntToPtr constants.
1601     if (auto *CE = dyn_cast<ConstantExpr>(V))
1602       if (CE->getOpcode() == Instruction::IntToPtr) {
1603         LocationOps.emplace_back(SDDbgOperand::fromConst(CE->getOperand(0)));
1604         continue;
1605       }
1606 
1607     // If the Value is a frame index, we can create a FrameIndex debug value
1608     // without relying on the DAG at all.
1609     if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1610       auto SI = FuncInfo.StaticAllocaMap.find(AI);
1611       if (SI != FuncInfo.StaticAllocaMap.end()) {
1612         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(SI->second));
1613         continue;
1614       }
1615     }
1616 
1617     // Do not use getValue() in here; we don't want to generate code at
1618     // this point if it hasn't been done yet.
1619     SDValue N = NodeMap[V];
1620     if (!N.getNode() && isa<Argument>(V)) // Check unused arguments map.
1621       N = UnusedArgNodeMap[V];
1622 
1623     if (N.getNode()) {
1624       // Only emit func arg dbg value for non-variadic dbg.values for now.
1625       if (!IsVariadic &&
1626           EmitFuncArgumentDbgValue(V, Var, Expr, DbgLoc,
1627                                    FuncArgumentDbgValueKind::Value, N))
1628         return true;
1629       if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
1630         // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can
1631         // describe stack slot locations.
1632         //
1633         // Consider "int x = 0; int *px = &x;". There are two kinds of
1634         // interesting debug values here after optimization:
1635         //
1636         //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
1637         //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
1638         //
1639         // Both describe the direct values of their associated variables.
1640         Dependencies.push_back(N.getNode());
1641         LocationOps.emplace_back(SDDbgOperand::fromFrameIdx(FISDN->getIndex()));
1642         continue;
1643       }
1644       LocationOps.emplace_back(
1645           SDDbgOperand::fromNode(N.getNode(), N.getResNo()));
1646       continue;
1647     }
1648 
1649     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1650     // Special rules apply for the first dbg.values of parameter variables in a
1651     // function. Identify them by the fact they reference Argument Values, that
1652     // they're parameters, and they are parameters of the current function. We
1653     // need to let them dangle until they get an SDNode.
1654     bool IsParamOfFunc =
1655         isa<Argument>(V) && Var->isParameter() && !DbgLoc.getInlinedAt();
1656     if (IsParamOfFunc)
1657       return false;
1658 
1659     // The value is not used in this block yet (or it would have an SDNode).
1660     // We still want the value to appear for the user if possible -- if it has
1661     // an associated VReg, we can refer to that instead.
1662     auto VMI = FuncInfo.ValueMap.find(V);
1663     if (VMI != FuncInfo.ValueMap.end()) {
1664       unsigned Reg = VMI->second;
1665       // If this is a PHI node, it may be split up into several MI PHI nodes
1666       // (in FunctionLoweringInfo::set).
1667       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg,
1668                        V->getType(), std::nullopt);
1669       if (RFV.occupiesMultipleRegs()) {
1670         // FIXME: We could potentially support variadic dbg_values here.
1671         if (IsVariadic)
1672           return false;
1673         unsigned Offset = 0;
1674         unsigned BitsToDescribe = 0;
1675         if (auto VarSize = Var->getSizeInBits())
1676           BitsToDescribe = *VarSize;
1677         if (auto Fragment = Expr->getFragmentInfo())
1678           BitsToDescribe = Fragment->SizeInBits;
1679         for (const auto &RegAndSize : RFV.getRegsAndSizes()) {
1680           // Bail out if all bits are described already.
1681           if (Offset >= BitsToDescribe)
1682             break;
1683           // TODO: handle scalable vectors.
1684           unsigned RegisterSize = RegAndSize.second;
1685           unsigned FragmentSize = (Offset + RegisterSize > BitsToDescribe)
1686                                       ? BitsToDescribe - Offset
1687                                       : RegisterSize;
1688           auto FragmentExpr = DIExpression::createFragmentExpression(
1689               Expr, Offset, FragmentSize);
1690           if (!FragmentExpr)
1691             continue;
1692           SDDbgValue *SDV = DAG.getVRegDbgValue(
1693               Var, *FragmentExpr, RegAndSize.first, false, DbgLoc, Order);
1694           DAG.AddDbgValue(SDV, false);
1695           Offset += RegisterSize;
1696         }
1697         return true;
1698       }
1699       // We can use simple vreg locations for variadic dbg_values as well.
1700       LocationOps.emplace_back(SDDbgOperand::fromVReg(Reg));
1701       continue;
1702     }
1703     // We failed to create a SDDbgOperand for V.
1704     return false;
1705   }
1706 
1707   // We have created a SDDbgOperand for each Value in Values.
1708   assert(!LocationOps.empty());
1709   SDDbgValue *SDV =
1710       DAG.getDbgValueList(Var, Expr, LocationOps, Dependencies,
1711                           /*IsIndirect=*/false, DbgLoc, Order, IsVariadic);
1712   DAG.AddDbgValue(SDV, /*isParameter=*/false);
1713   return true;
1714 }
1715 
1716 void SelectionDAGBuilder::resolveOrClearDbgInfo() {
1717   // Try to fixup any remaining dangling debug info -- and drop it if we can't.
1718   for (auto &Pair : DanglingDebugInfoMap)
1719     for (auto &DDI : Pair.second)
1720       salvageUnresolvedDbgValue(const_cast<Value *>(Pair.first), DDI);
1721   clearDanglingDebugInfo();
1722 }
1723 
1724 /// getCopyFromRegs - If there was virtual register allocated for the value V
1725 /// emit CopyFromReg of the specified type Ty. Return empty SDValue() otherwise.
1726 SDValue SelectionDAGBuilder::getCopyFromRegs(const Value *V, Type *Ty) {
1727   DenseMap<const Value *, Register>::iterator It = FuncInfo.ValueMap.find(V);
1728   SDValue Result;
1729 
1730   if (It != FuncInfo.ValueMap.end()) {
1731     Register InReg = It->second;
1732 
1733     RegsForValue RFV(*DAG.getContext(), DAG.getTargetLoweringInfo(),
1734                      DAG.getDataLayout(), InReg, Ty,
1735                      std::nullopt); // This is not an ABI copy.
1736     SDValue Chain = DAG.getEntryNode();
1737     Result = RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr,
1738                                  V);
1739     resolveDanglingDebugInfo(V, Result);
1740   }
1741 
1742   return Result;
1743 }
1744 
1745 /// getValue - Return an SDValue for the given Value.
1746 SDValue SelectionDAGBuilder::getValue(const Value *V) {
1747   // If we already have an SDValue for this value, use it. It's important
1748   // to do this first, so that we don't create a CopyFromReg if we already
1749   // have a regular SDValue.
1750   SDValue &N = NodeMap[V];
1751   if (N.getNode()) return N;
1752 
1753   // If there's a virtual register allocated and initialized for this
1754   // value, use it.
1755   if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
1756     return copyFromReg;
1757 
1758   // Otherwise create a new SDValue and remember it.
1759   SDValue Val = getValueImpl(V);
1760   NodeMap[V] = Val;
1761   resolveDanglingDebugInfo(V, Val);
1762   return Val;
1763 }
1764 
1765 /// getNonRegisterValue - Return an SDValue for the given Value, but
1766 /// don't look in FuncInfo.ValueMap for a virtual register.
1767 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1768   // If we already have an SDValue for this value, use it.
1769   SDValue &N = NodeMap[V];
1770   if (N.getNode()) {
1771     if (isIntOrFPConstant(N)) {
1772       // Remove the debug location from the node as the node is about to be used
1773       // in a location which may differ from the original debug location.  This
1774       // is relevant to Constant and ConstantFP nodes because they can appear
1775       // as constant expressions inside PHI nodes.
1776       N->setDebugLoc(DebugLoc());
1777     }
1778     return N;
1779   }
1780 
1781   // Otherwise create a new SDValue and remember it.
1782   SDValue Val = getValueImpl(V);
1783   NodeMap[V] = Val;
1784   resolveDanglingDebugInfo(V, Val);
1785   return Val;
1786 }
1787 
1788 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1789 /// Create an SDValue for the given value.
1790 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1791   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
1792 
1793   if (const Constant *C = dyn_cast<Constant>(V)) {
1794     EVT VT = TLI.getValueType(DAG.getDataLayout(), V->getType(), true);
1795 
1796     if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1797       return DAG.getConstant(*CI, getCurSDLoc(), VT);
1798 
1799     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1800       return DAG.getGlobalAddress(GV, getCurSDLoc(), VT);
1801 
1802     if (const ConstantPtrAuth *CPA = dyn_cast<ConstantPtrAuth>(C)) {
1803       return DAG.getNode(ISD::PtrAuthGlobalAddress, getCurSDLoc(), VT,
1804                          getValue(CPA->getPointer()), getValue(CPA->getKey()),
1805                          getValue(CPA->getAddrDiscriminator()),
1806                          getValue(CPA->getDiscriminator()));
1807     }
1808 
1809     if (isa<ConstantPointerNull>(C)) {
1810       unsigned AS = V->getType()->getPointerAddressSpace();
1811       return DAG.getConstant(0, getCurSDLoc(),
1812                              TLI.getPointerTy(DAG.getDataLayout(), AS));
1813     }
1814 
1815     if (match(C, m_VScale()))
1816       return DAG.getVScale(getCurSDLoc(), VT, APInt(VT.getSizeInBits(), 1));
1817 
1818     if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1819       return DAG.getConstantFP(*CFP, getCurSDLoc(), VT);
1820 
1821     if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1822       return DAG.getUNDEF(VT);
1823 
1824     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1825       visit(CE->getOpcode(), *CE);
1826       SDValue N1 = NodeMap[V];
1827       assert(N1.getNode() && "visit didn't populate the NodeMap!");
1828       return N1;
1829     }
1830 
1831     if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1832       SmallVector<SDValue, 4> Constants;
1833       for (const Use &U : C->operands()) {
1834         SDNode *Val = getValue(U).getNode();
1835         // If the operand is an empty aggregate, there are no values.
1836         if (!Val) continue;
1837         // Add each leaf value from the operand to the Constants list
1838         // to form a flattened list of all the values.
1839         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1840           Constants.push_back(SDValue(Val, i));
1841       }
1842 
1843       return DAG.getMergeValues(Constants, getCurSDLoc());
1844     }
1845 
1846     if (const ConstantDataSequential *CDS =
1847           dyn_cast<ConstantDataSequential>(C)) {
1848       SmallVector<SDValue, 4> Ops;
1849       for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
1850         SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1851         // Add each leaf value from the operand to the Constants list
1852         // to form a flattened list of all the values.
1853         for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1854           Ops.push_back(SDValue(Val, i));
1855       }
1856 
1857       if (isa<ArrayType>(CDS->getType()))
1858         return DAG.getMergeValues(Ops, getCurSDLoc());
1859       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1860     }
1861 
1862     if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1863       assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1864              "Unknown struct or array constant!");
1865 
1866       SmallVector<EVT, 4> ValueVTs;
1867       ComputeValueVTs(TLI, DAG.getDataLayout(), C->getType(), ValueVTs);
1868       unsigned NumElts = ValueVTs.size();
1869       if (NumElts == 0)
1870         return SDValue(); // empty struct
1871       SmallVector<SDValue, 4> Constants(NumElts);
1872       for (unsigned i = 0; i != NumElts; ++i) {
1873         EVT EltVT = ValueVTs[i];
1874         if (isa<UndefValue>(C))
1875           Constants[i] = DAG.getUNDEF(EltVT);
1876         else if (EltVT.isFloatingPoint())
1877           Constants[i] = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1878         else
1879           Constants[i] = DAG.getConstant(0, getCurSDLoc(), EltVT);
1880       }
1881 
1882       return DAG.getMergeValues(Constants, getCurSDLoc());
1883     }
1884 
1885     if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1886       return DAG.getBlockAddress(BA, VT);
1887 
1888     if (const auto *Equiv = dyn_cast<DSOLocalEquivalent>(C))
1889       return getValue(Equiv->getGlobalValue());
1890 
1891     if (const auto *NC = dyn_cast<NoCFIValue>(C))
1892       return getValue(NC->getGlobalValue());
1893 
1894     if (VT == MVT::aarch64svcount) {
1895       assert(C->isNullValue() && "Can only zero this target type!");
1896       return DAG.getNode(ISD::BITCAST, getCurSDLoc(), VT,
1897                          DAG.getConstant(0, getCurSDLoc(), MVT::nxv16i1));
1898     }
1899 
1900     if (VT.isRISCVVectorTuple()) {
1901       assert(C->isNullValue() && "Can only zero this target type!");
1902       return NodeMap[V] = DAG.getNode(
1903                  ISD::BITCAST, getCurSDLoc(), VT,
1904                  DAG.getNode(
1905                      ISD::SPLAT_VECTOR, getCurSDLoc(),
1906                      EVT::getVectorVT(*DAG.getContext(), MVT::i8,
1907                                       VT.getSizeInBits().getKnownMinValue() / 8,
1908                                       true),
1909                      DAG.getConstant(0, getCurSDLoc(), MVT::getIntegerVT(8))));
1910     }
1911 
1912     VectorType *VecTy = cast<VectorType>(V->getType());
1913 
1914     // Now that we know the number and type of the elements, get that number of
1915     // elements into the Ops array based on what kind of constant it is.
1916     if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
1917       SmallVector<SDValue, 16> Ops;
1918       unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1919       for (unsigned i = 0; i != NumElements; ++i)
1920         Ops.push_back(getValue(CV->getOperand(i)));
1921 
1922       return NodeMap[V] = DAG.getBuildVector(VT, getCurSDLoc(), Ops);
1923     }
1924 
1925     if (isa<ConstantAggregateZero>(C)) {
1926       EVT EltVT =
1927           TLI.getValueType(DAG.getDataLayout(), VecTy->getElementType());
1928 
1929       SDValue Op;
1930       if (EltVT.isFloatingPoint())
1931         Op = DAG.getConstantFP(0, getCurSDLoc(), EltVT);
1932       else
1933         Op = DAG.getConstant(0, getCurSDLoc(), EltVT);
1934 
1935       return NodeMap[V] = DAG.getSplat(VT, getCurSDLoc(), Op);
1936     }
1937 
1938     llvm_unreachable("Unknown vector constant");
1939   }
1940 
1941   // If this is a static alloca, generate it as the frameindex instead of
1942   // computation.
1943   if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1944     DenseMap<const AllocaInst*, int>::iterator SI =
1945       FuncInfo.StaticAllocaMap.find(AI);
1946     if (SI != FuncInfo.StaticAllocaMap.end())
1947       return DAG.getFrameIndex(
1948           SI->second, TLI.getValueType(DAG.getDataLayout(), AI->getType()));
1949   }
1950 
1951   // If this is an instruction which fast-isel has deferred, select it now.
1952   if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1953     Register InReg = FuncInfo.InitializeRegForValue(Inst);
1954 
1955     RegsForValue RFV(*DAG.getContext(), TLI, DAG.getDataLayout(), InReg,
1956                      Inst->getType(), std::nullopt);
1957     SDValue Chain = DAG.getEntryNode();
1958     return RFV.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, V);
1959   }
1960 
1961   if (const MetadataAsValue *MD = dyn_cast<MetadataAsValue>(V))
1962     return DAG.getMDNode(cast<MDNode>(MD->getMetadata()));
1963 
1964   if (const auto *BB = dyn_cast<BasicBlock>(V))
1965     return DAG.getBasicBlock(FuncInfo.getMBB(BB));
1966 
1967   llvm_unreachable("Can't get register for value!");
1968 }
1969 
1970 void SelectionDAGBuilder::visitCatchPad(const CatchPadInst &I) {
1971   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1972   bool IsMSVCCXX = Pers == EHPersonality::MSVC_CXX;
1973   bool IsCoreCLR = Pers == EHPersonality::CoreCLR;
1974   bool IsSEH = isAsynchronousEHPersonality(Pers);
1975   MachineBasicBlock *CatchPadMBB = FuncInfo.MBB;
1976   if (!IsSEH)
1977     CatchPadMBB->setIsEHScopeEntry();
1978   // In MSVC C++ and CoreCLR, catchblocks are funclets and need prologues.
1979   if (IsMSVCCXX || IsCoreCLR)
1980     CatchPadMBB->setIsEHFuncletEntry();
1981 }
1982 
1983 void SelectionDAGBuilder::visitCatchRet(const CatchReturnInst &I) {
1984   // Update machine-CFG edge.
1985   MachineBasicBlock *TargetMBB = FuncInfo.getMBB(I.getSuccessor());
1986   FuncInfo.MBB->addSuccessor(TargetMBB);
1987   TargetMBB->setIsEHCatchretTarget(true);
1988   DAG.getMachineFunction().setHasEHCatchret(true);
1989 
1990   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
1991   bool IsSEH = isAsynchronousEHPersonality(Pers);
1992   if (IsSEH) {
1993     // If this is not a fall-through branch or optimizations are switched off,
1994     // emit the branch.
1995     if (TargetMBB != NextBlock(FuncInfo.MBB) ||
1996         TM.getOptLevel() == CodeGenOptLevel::None)
1997       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
1998                               getControlRoot(), DAG.getBasicBlock(TargetMBB)));
1999     return;
2000   }
2001 
2002   // Figure out the funclet membership for the catchret's successor.
2003   // This will be used by the FuncletLayout pass to determine how to order the
2004   // BB's.
2005   // A 'catchret' returns to the outer scope's color.
2006   Value *ParentPad = I.getCatchSwitchParentPad();
2007   const BasicBlock *SuccessorColor;
2008   if (isa<ConstantTokenNone>(ParentPad))
2009     SuccessorColor = &FuncInfo.Fn->getEntryBlock();
2010   else
2011     SuccessorColor = cast<Instruction>(ParentPad)->getParent();
2012   assert(SuccessorColor && "No parent funclet for catchret!");
2013   MachineBasicBlock *SuccessorColorMBB = FuncInfo.getMBB(SuccessorColor);
2014   assert(SuccessorColorMBB && "No MBB for SuccessorColor!");
2015 
2016   // Create the terminator node.
2017   SDValue Ret = DAG.getNode(ISD::CATCHRET, getCurSDLoc(), MVT::Other,
2018                             getControlRoot(), DAG.getBasicBlock(TargetMBB),
2019                             DAG.getBasicBlock(SuccessorColorMBB));
2020   DAG.setRoot(Ret);
2021 }
2022 
2023 void SelectionDAGBuilder::visitCleanupPad(const CleanupPadInst &CPI) {
2024   // Don't emit any special code for the cleanuppad instruction. It just marks
2025   // the start of an EH scope/funclet.
2026   FuncInfo.MBB->setIsEHScopeEntry();
2027   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2028   if (Pers != EHPersonality::Wasm_CXX) {
2029     FuncInfo.MBB->setIsEHFuncletEntry();
2030     FuncInfo.MBB->setIsCleanupFuncletEntry();
2031   }
2032 }
2033 
2034 // In wasm EH, even though a catchpad may not catch an exception if a tag does
2035 // not match, it is OK to add only the first unwind destination catchpad to the
2036 // successors, because there will be at least one invoke instruction within the
2037 // catch scope that points to the next unwind destination, if one exists, so
2038 // CFGSort cannot mess up with BB sorting order.
2039 // (All catchpads with 'catch (type)' clauses have a 'llvm.rethrow' intrinsic
2040 // call within them, and catchpads only consisting of 'catch (...)' have a
2041 // '__cxa_end_catch' call within them, both of which generate invokes in case
2042 // the next unwind destination exists, i.e., the next unwind destination is not
2043 // the caller.)
2044 //
2045 // Having at most one EH pad successor is also simpler and helps later
2046 // transformations.
2047 //
2048 // For example,
2049 // current:
2050 //   invoke void @foo to ... unwind label %catch.dispatch
2051 // catch.dispatch:
2052 //   %0 = catchswitch within ... [label %catch.start] unwind label %next
2053 // catch.start:
2054 //   ...
2055 //   ... in this BB or some other child BB dominated by this BB there will be an
2056 //   invoke that points to 'next' BB as an unwind destination
2057 //
2058 // next: ; We don't need to add this to 'current' BB's successor
2059 //   ...
2060 static void findWasmUnwindDestinations(
2061     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2062     BranchProbability Prob,
2063     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2064         &UnwindDests) {
2065   while (EHPadBB) {
2066     BasicBlock::const_iterator Pad = EHPadBB->getFirstNonPHIIt();
2067     if (isa<CleanupPadInst>(Pad)) {
2068       // Stop on cleanup pads.
2069       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2070       UnwindDests.back().first->setIsEHScopeEntry();
2071       break;
2072     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2073       // Add the catchpad handlers to the possible destinations. We don't
2074       // continue to the unwind destination of the catchswitch for wasm.
2075       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2076         UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2077         UnwindDests.back().first->setIsEHScopeEntry();
2078       }
2079       break;
2080     } else {
2081       continue;
2082     }
2083   }
2084 }
2085 
2086 /// When an invoke or a cleanupret unwinds to the next EH pad, there are
2087 /// many places it could ultimately go. In the IR, we have a single unwind
2088 /// destination, but in the machine CFG, we enumerate all the possible blocks.
2089 /// This function skips over imaginary basic blocks that hold catchswitch
2090 /// instructions, and finds all the "real" machine
2091 /// basic block destinations. As those destinations may not be successors of
2092 /// EHPadBB, here we also calculate the edge probability to those destinations.
2093 /// The passed-in Prob is the edge probability to EHPadBB.
2094 static void findUnwindDestinations(
2095     FunctionLoweringInfo &FuncInfo, const BasicBlock *EHPadBB,
2096     BranchProbability Prob,
2097     SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>>
2098         &UnwindDests) {
2099   EHPersonality Personality =
2100     classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
2101   bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX;
2102   bool IsCoreCLR = Personality == EHPersonality::CoreCLR;
2103   bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX;
2104   bool IsSEH = isAsynchronousEHPersonality(Personality);
2105 
2106   if (IsWasmCXX) {
2107     findWasmUnwindDestinations(FuncInfo, EHPadBB, Prob, UnwindDests);
2108     assert(UnwindDests.size() <= 1 &&
2109            "There should be at most one unwind destination for wasm");
2110     return;
2111   }
2112 
2113   while (EHPadBB) {
2114     BasicBlock::const_iterator Pad = EHPadBB->getFirstNonPHIIt();
2115     BasicBlock *NewEHPadBB = nullptr;
2116     if (isa<LandingPadInst>(Pad)) {
2117       // Stop on landingpads. They are not funclets.
2118       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2119       break;
2120     } else if (isa<CleanupPadInst>(Pad)) {
2121       // Stop on cleanup pads. Cleanups are always funclet entries for all known
2122       // personalities.
2123       UnwindDests.emplace_back(FuncInfo.getMBB(EHPadBB), Prob);
2124       UnwindDests.back().first->setIsEHScopeEntry();
2125       UnwindDests.back().first->setIsEHFuncletEntry();
2126       break;
2127     } else if (const auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) {
2128       // Add the catchpad handlers to the possible destinations.
2129       for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) {
2130         UnwindDests.emplace_back(FuncInfo.getMBB(CatchPadBB), Prob);
2131         // For MSVC++ and the CLR, catchblocks are funclets and need prologues.
2132         if (IsMSVCCXX || IsCoreCLR)
2133           UnwindDests.back().first->setIsEHFuncletEntry();
2134         if (!IsSEH)
2135           UnwindDests.back().first->setIsEHScopeEntry();
2136       }
2137       NewEHPadBB = CatchSwitch->getUnwindDest();
2138     } else {
2139       continue;
2140     }
2141 
2142     BranchProbabilityInfo *BPI = FuncInfo.BPI;
2143     if (BPI && NewEHPadBB)
2144       Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB);
2145     EHPadBB = NewEHPadBB;
2146   }
2147 }
2148 
2149 void SelectionDAGBuilder::visitCleanupRet(const CleanupReturnInst &I) {
2150   // Update successor info.
2151   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
2152   auto UnwindDest = I.getUnwindDest();
2153   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2154   BranchProbability UnwindDestProb =
2155       (BPI && UnwindDest)
2156           ? BPI->getEdgeProbability(FuncInfo.MBB->getBasicBlock(), UnwindDest)
2157           : BranchProbability::getZero();
2158   findUnwindDestinations(FuncInfo, UnwindDest, UnwindDestProb, UnwindDests);
2159   for (auto &UnwindDest : UnwindDests) {
2160     UnwindDest.first->setIsEHPad();
2161     addSuccessorWithProb(FuncInfo.MBB, UnwindDest.first, UnwindDest.second);
2162   }
2163   FuncInfo.MBB->normalizeSuccProbs();
2164 
2165   // Create the terminator node.
2166   MachineBasicBlock *CleanupPadMBB =
2167       FuncInfo.getMBB(I.getCleanupPad()->getParent());
2168   SDValue Ret = DAG.getNode(ISD::CLEANUPRET, getCurSDLoc(), MVT::Other,
2169                             getControlRoot(), DAG.getBasicBlock(CleanupPadMBB));
2170   DAG.setRoot(Ret);
2171 }
2172 
2173 void SelectionDAGBuilder::visitCatchSwitch(const CatchSwitchInst &CSI) {
2174   report_fatal_error("visitCatchSwitch not yet implemented!");
2175 }
2176 
2177 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
2178   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2179   auto &DL = DAG.getDataLayout();
2180   SDValue Chain = getControlRoot();
2181   SmallVector<ISD::OutputArg, 8> Outs;
2182   SmallVector<SDValue, 8> OutVals;
2183 
2184   // Calls to @llvm.experimental.deoptimize don't generate a return value, so
2185   // lower
2186   //
2187   //   %val = call <ty> @llvm.experimental.deoptimize()
2188   //   ret <ty> %val
2189   //
2190   // differently.
2191   if (I.getParent()->getTerminatingDeoptimizeCall()) {
2192     LowerDeoptimizingReturn();
2193     return;
2194   }
2195 
2196   if (!FuncInfo.CanLowerReturn) {
2197     Register DemoteReg = FuncInfo.DemoteRegister;
2198 
2199     // Emit a store of the return value through the virtual register.
2200     // Leave Outs empty so that LowerReturn won't try to load return
2201     // registers the usual way.
2202     MVT PtrValueVT = TLI.getPointerTy(DL, DL.getAllocaAddrSpace());
2203     SDValue RetPtr =
2204         DAG.getCopyFromReg(Chain, getCurSDLoc(), DemoteReg, PtrValueVT);
2205     SDValue RetOp = getValue(I.getOperand(0));
2206 
2207     SmallVector<EVT, 4> ValueVTs, MemVTs;
2208     SmallVector<uint64_t, 4> Offsets;
2209     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs, &MemVTs,
2210                     &Offsets, 0);
2211     unsigned NumValues = ValueVTs.size();
2212 
2213     SmallVector<SDValue, 4> Chains(NumValues);
2214     Align BaseAlign = DL.getPrefTypeAlign(I.getOperand(0)->getType());
2215     for (unsigned i = 0; i != NumValues; ++i) {
2216       // An aggregate return value cannot wrap around the address space, so
2217       // offsets to its parts don't wrap either.
2218       SDValue Ptr = DAG.getObjectPtrOffset(getCurSDLoc(), RetPtr,
2219                                            TypeSize::getFixed(Offsets[i]));
2220 
2221       SDValue Val = RetOp.getValue(RetOp.getResNo() + i);
2222       if (MemVTs[i] != ValueVTs[i])
2223         Val = DAG.getPtrExtOrTrunc(Val, getCurSDLoc(), MemVTs[i]);
2224       Chains[i] = DAG.getStore(
2225           Chain, getCurSDLoc(), Val,
2226           // FIXME: better loc info would be nice.
2227           Ptr, MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()),
2228           commonAlignment(BaseAlign, Offsets[i]));
2229     }
2230 
2231     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(),
2232                         MVT::Other, Chains);
2233   } else if (I.getNumOperands() != 0) {
2234     SmallVector<EVT, 4> ValueVTs;
2235     ComputeValueVTs(TLI, DL, I.getOperand(0)->getType(), ValueVTs);
2236     unsigned NumValues = ValueVTs.size();
2237     if (NumValues) {
2238       SDValue RetOp = getValue(I.getOperand(0));
2239 
2240       const Function *F = I.getParent()->getParent();
2241 
2242       bool NeedsRegBlock = TLI.functionArgumentNeedsConsecutiveRegisters(
2243           I.getOperand(0)->getType(), F->getCallingConv(),
2244           /*IsVarArg*/ false, DL);
2245 
2246       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
2247       if (F->getAttributes().hasRetAttr(Attribute::SExt))
2248         ExtendKind = ISD::SIGN_EXTEND;
2249       else if (F->getAttributes().hasRetAttr(Attribute::ZExt))
2250         ExtendKind = ISD::ZERO_EXTEND;
2251 
2252       LLVMContext &Context = F->getContext();
2253       bool RetInReg = F->getAttributes().hasRetAttr(Attribute::InReg);
2254 
2255       for (unsigned j = 0; j != NumValues; ++j) {
2256         EVT VT = ValueVTs[j];
2257 
2258         if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
2259           VT = TLI.getTypeForExtReturn(Context, VT, ExtendKind);
2260 
2261         CallingConv::ID CC = F->getCallingConv();
2262 
2263         unsigned NumParts = TLI.getNumRegistersForCallingConv(Context, CC, VT);
2264         MVT PartVT = TLI.getRegisterTypeForCallingConv(Context, CC, VT);
2265         SmallVector<SDValue, 4> Parts(NumParts);
2266         getCopyToParts(DAG, getCurSDLoc(),
2267                        SDValue(RetOp.getNode(), RetOp.getResNo() + j),
2268                        &Parts[0], NumParts, PartVT, &I, CC, ExtendKind);
2269 
2270         // 'inreg' on function refers to return value
2271         ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2272         if (RetInReg)
2273           Flags.setInReg();
2274 
2275         if (I.getOperand(0)->getType()->isPointerTy()) {
2276           Flags.setPointer();
2277           Flags.setPointerAddrSpace(
2278               cast<PointerType>(I.getOperand(0)->getType())->getAddressSpace());
2279         }
2280 
2281         if (NeedsRegBlock) {
2282           Flags.setInConsecutiveRegs();
2283           if (j == NumValues - 1)
2284             Flags.setInConsecutiveRegsLast();
2285         }
2286 
2287         // Propagate extension type if any
2288         if (ExtendKind == ISD::SIGN_EXTEND)
2289           Flags.setSExt();
2290         else if (ExtendKind == ISD::ZERO_EXTEND)
2291           Flags.setZExt();
2292         else if (F->getAttributes().hasRetAttr(Attribute::NoExt))
2293           Flags.setNoExt();
2294 
2295         for (unsigned i = 0; i < NumParts; ++i) {
2296           Outs.push_back(ISD::OutputArg(Flags,
2297                                         Parts[i].getValueType().getSimpleVT(),
2298                                         VT, /*isfixed=*/true, 0, 0));
2299           OutVals.push_back(Parts[i]);
2300         }
2301       }
2302     }
2303   }
2304 
2305   // Push in swifterror virtual register as the last element of Outs. This makes
2306   // sure swifterror virtual register will be returned in the swifterror
2307   // physical register.
2308   const Function *F = I.getParent()->getParent();
2309   if (TLI.supportSwiftError() &&
2310       F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) {
2311     assert(SwiftError.getFunctionArg() && "Need a swift error argument");
2312     ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
2313     Flags.setSwiftError();
2314     Outs.push_back(ISD::OutputArg(
2315         Flags, /*vt=*/TLI.getPointerTy(DL), /*argvt=*/EVT(TLI.getPointerTy(DL)),
2316         /*isfixed=*/true, /*origidx=*/1, /*partOffs=*/0));
2317     // Create SDNode for the swifterror virtual register.
2318     OutVals.push_back(
2319         DAG.getRegister(SwiftError.getOrCreateVRegUseAt(
2320                             &I, FuncInfo.MBB, SwiftError.getFunctionArg()),
2321                         EVT(TLI.getPointerTy(DL))));
2322   }
2323 
2324   bool isVarArg = DAG.getMachineFunction().getFunction().isVarArg();
2325   CallingConv::ID CallConv =
2326     DAG.getMachineFunction().getFunction().getCallingConv();
2327   Chain = DAG.getTargetLoweringInfo().LowerReturn(
2328       Chain, CallConv, isVarArg, Outs, OutVals, getCurSDLoc(), DAG);
2329 
2330   // Verify that the target's LowerReturn behaved as expected.
2331   assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
2332          "LowerReturn didn't return a valid chain!");
2333 
2334   // Update the DAG with the new chain value resulting from return lowering.
2335   DAG.setRoot(Chain);
2336 }
2337 
2338 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
2339 /// created for it, emit nodes to copy the value into the virtual
2340 /// registers.
2341 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
2342   // Skip empty types
2343   if (V->getType()->isEmptyTy())
2344     return;
2345 
2346   DenseMap<const Value *, Register>::iterator VMI = FuncInfo.ValueMap.find(V);
2347   if (VMI != FuncInfo.ValueMap.end()) {
2348     assert((!V->use_empty() || isa<CallBrInst>(V)) &&
2349            "Unused value assigned virtual registers!");
2350     CopyValueToVirtualRegister(V, VMI->second);
2351   }
2352 }
2353 
2354 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
2355 /// the current basic block, add it to ValueMap now so that we'll get a
2356 /// CopyTo/FromReg.
2357 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
2358   // No need to export constants.
2359   if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
2360 
2361   // Already exported?
2362   if (FuncInfo.isExportedInst(V)) return;
2363 
2364   Register Reg = FuncInfo.InitializeRegForValue(V);
2365   CopyValueToVirtualRegister(V, Reg);
2366 }
2367 
2368 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
2369                                                      const BasicBlock *FromBB) {
2370   // The operands of the setcc have to be in this block.  We don't know
2371   // how to export them from some other block.
2372   if (const Instruction *VI = dyn_cast<Instruction>(V)) {
2373     // Can export from current BB.
2374     if (VI->getParent() == FromBB)
2375       return true;
2376 
2377     // Is already exported, noop.
2378     return FuncInfo.isExportedInst(V);
2379   }
2380 
2381   // If this is an argument, we can export it if the BB is the entry block or
2382   // if it is already exported.
2383   if (isa<Argument>(V)) {
2384     if (FromBB->isEntryBlock())
2385       return true;
2386 
2387     // Otherwise, can only export this if it is already exported.
2388     return FuncInfo.isExportedInst(V);
2389   }
2390 
2391   // Otherwise, constants can always be exported.
2392   return true;
2393 }
2394 
2395 /// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
2396 BranchProbability
2397 SelectionDAGBuilder::getEdgeProbability(const MachineBasicBlock *Src,
2398                                         const MachineBasicBlock *Dst) const {
2399   BranchProbabilityInfo *BPI = FuncInfo.BPI;
2400   const BasicBlock *SrcBB = Src->getBasicBlock();
2401   const BasicBlock *DstBB = Dst->getBasicBlock();
2402   if (!BPI) {
2403     // If BPI is not available, set the default probability as 1 / N, where N is
2404     // the number of successors.
2405     auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1);
2406     return BranchProbability(1, SuccSize);
2407   }
2408   return BPI->getEdgeProbability(SrcBB, DstBB);
2409 }
2410 
2411 void SelectionDAGBuilder::addSuccessorWithProb(MachineBasicBlock *Src,
2412                                                MachineBasicBlock *Dst,
2413                                                BranchProbability Prob) {
2414   if (!FuncInfo.BPI)
2415     Src->addSuccessorWithoutProb(Dst);
2416   else {
2417     if (Prob.isUnknown())
2418       Prob = getEdgeProbability(Src, Dst);
2419     Src->addSuccessor(Dst, Prob);
2420   }
2421 }
2422 
2423 static bool InBlock(const Value *V, const BasicBlock *BB) {
2424   if (const Instruction *I = dyn_cast<Instruction>(V))
2425     return I->getParent() == BB;
2426   return true;
2427 }
2428 
2429 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
2430 /// This function emits a branch and is used at the leaves of an OR or an
2431 /// AND operator tree.
2432 void
2433 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
2434                                                   MachineBasicBlock *TBB,
2435                                                   MachineBasicBlock *FBB,
2436                                                   MachineBasicBlock *CurBB,
2437                                                   MachineBasicBlock *SwitchBB,
2438                                                   BranchProbability TProb,
2439                                                   BranchProbability FProb,
2440                                                   bool InvertCond) {
2441   const BasicBlock *BB = CurBB->getBasicBlock();
2442 
2443   // If the leaf of the tree is a comparison, merge the condition into
2444   // the caseblock.
2445   if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
2446     // The operands of the cmp have to be in this block.  We don't know
2447     // how to export them from some other block.  If this is the first block
2448     // of the sequence, no exporting is needed.
2449     if (CurBB == SwitchBB ||
2450         (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
2451          isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
2452       ISD::CondCode Condition;
2453       if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
2454         ICmpInst::Predicate Pred =
2455             InvertCond ? IC->getInversePredicate() : IC->getPredicate();
2456         Condition = getICmpCondCode(Pred);
2457       } else {
2458         const FCmpInst *FC = cast<FCmpInst>(Cond);
2459         FCmpInst::Predicate Pred =
2460             InvertCond ? FC->getInversePredicate() : FC->getPredicate();
2461         Condition = getFCmpCondCode(Pred);
2462         if (TM.Options.NoNaNsFPMath)
2463           Condition = getFCmpCodeWithoutNaN(Condition);
2464       }
2465 
2466       CaseBlock CB(Condition, BOp->getOperand(0), BOp->getOperand(1), nullptr,
2467                    TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2468       SL->SwitchCases.push_back(CB);
2469       return;
2470     }
2471   }
2472 
2473   // Create a CaseBlock record representing this branch.
2474   ISD::CondCode Opc = InvertCond ? ISD::SETNE : ISD::SETEQ;
2475   CaseBlock CB(Opc, Cond, ConstantInt::getTrue(*DAG.getContext()),
2476                nullptr, TBB, FBB, CurBB, getCurSDLoc(), TProb, FProb);
2477   SL->SwitchCases.push_back(CB);
2478 }
2479 
2480 // Collect dependencies on V recursively. This is used for the cost analysis in
2481 // `shouldKeepJumpConditionsTogether`.
2482 static bool collectInstructionDeps(
2483     SmallMapVector<const Instruction *, bool, 8> *Deps, const Value *V,
2484     SmallMapVector<const Instruction *, bool, 8> *Necessary = nullptr,
2485     unsigned Depth = 0) {
2486   // Return false if we have an incomplete count.
2487   if (Depth >= SelectionDAG::MaxRecursionDepth)
2488     return false;
2489 
2490   auto *I = dyn_cast<Instruction>(V);
2491   if (I == nullptr)
2492     return true;
2493 
2494   if (Necessary != nullptr) {
2495     // This instruction is necessary for the other side of the condition so
2496     // don't count it.
2497     if (Necessary->contains(I))
2498       return true;
2499   }
2500 
2501   // Already added this dep.
2502   if (!Deps->try_emplace(I, false).second)
2503     return true;
2504 
2505   for (unsigned OpIdx = 0, E = I->getNumOperands(); OpIdx < E; ++OpIdx)
2506     if (!collectInstructionDeps(Deps, I->getOperand(OpIdx), Necessary,
2507                                 Depth + 1))
2508       return false;
2509   return true;
2510 }
2511 
2512 bool SelectionDAGBuilder::shouldKeepJumpConditionsTogether(
2513     const FunctionLoweringInfo &FuncInfo, const BranchInst &I,
2514     Instruction::BinaryOps Opc, const Value *Lhs, const Value *Rhs,
2515     TargetLoweringBase::CondMergingParams Params) const {
2516   if (I.getNumSuccessors() != 2)
2517     return false;
2518 
2519   if (!I.isConditional())
2520     return false;
2521 
2522   if (Params.BaseCost < 0)
2523     return false;
2524 
2525   // Baseline cost.
2526   InstructionCost CostThresh = Params.BaseCost;
2527 
2528   BranchProbabilityInfo *BPI = nullptr;
2529   if (Params.LikelyBias || Params.UnlikelyBias)
2530     BPI = FuncInfo.BPI;
2531   if (BPI != nullptr) {
2532     // See if we are either likely to get an early out or compute both lhs/rhs
2533     // of the condition.
2534     BasicBlock *IfFalse = I.getSuccessor(0);
2535     BasicBlock *IfTrue = I.getSuccessor(1);
2536 
2537     std::optional<bool> Likely;
2538     if (BPI->isEdgeHot(I.getParent(), IfTrue))
2539       Likely = true;
2540     else if (BPI->isEdgeHot(I.getParent(), IfFalse))
2541       Likely = false;
2542 
2543     if (Likely) {
2544       if (Opc == (*Likely ? Instruction::And : Instruction::Or))
2545         // Its likely we will have to compute both lhs and rhs of condition
2546         CostThresh += Params.LikelyBias;
2547       else {
2548         if (Params.UnlikelyBias < 0)
2549           return false;
2550         // Its likely we will get an early out.
2551         CostThresh -= Params.UnlikelyBias;
2552       }
2553     }
2554   }
2555 
2556   if (CostThresh <= 0)
2557     return false;
2558 
2559   // Collect "all" instructions that lhs condition is dependent on.
2560   // Use map for stable iteration (to avoid non-determanism of iteration of
2561   // SmallPtrSet). The `bool` value is just a dummy.
2562   SmallMapVector<const Instruction *, bool, 8> LhsDeps, RhsDeps;
2563   collectInstructionDeps(&LhsDeps, Lhs);
2564   // Collect "all" instructions that rhs condition is dependent on AND are
2565   // dependencies of lhs. This gives us an estimate on which instructions we
2566   // stand to save by splitting the condition.
2567   if (!collectInstructionDeps(&RhsDeps, Rhs, &LhsDeps))
2568     return false;
2569   // Add the compare instruction itself unless its a dependency on the LHS.
2570   if (const auto *RhsI = dyn_cast<Instruction>(Rhs))
2571     if (!LhsDeps.contains(RhsI))
2572       RhsDeps.try_emplace(RhsI, false);
2573 
2574   const auto &TLI = DAG.getTargetLoweringInfo();
2575   const auto &TTI =
2576       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
2577 
2578   InstructionCost CostOfIncluding = 0;
2579   // See if this instruction will need to computed independently of whether RHS
2580   // is.
2581   Value *BrCond = I.getCondition();
2582   auto ShouldCountInsn = [&RhsDeps, &BrCond](const Instruction *Ins) {
2583     for (const auto *U : Ins->users()) {
2584       // If user is independent of RHS calculation we don't need to count it.
2585       if (auto *UIns = dyn_cast<Instruction>(U))
2586         if (UIns != BrCond && !RhsDeps.contains(UIns))
2587           return false;
2588     }
2589     return true;
2590   };
2591 
2592   // Prune instructions from RHS Deps that are dependencies of unrelated
2593   // instructions. The value (SelectionDAG::MaxRecursionDepth) is fairly
2594   // arbitrary and just meant to cap the how much time we spend in the pruning
2595   // loop. Its highly unlikely to come into affect.
2596   const unsigned MaxPruneIters = SelectionDAG::MaxRecursionDepth;
2597   // Stop after a certain point. No incorrectness from including too many
2598   // instructions.
2599   for (unsigned PruneIters = 0; PruneIters < MaxPruneIters; ++PruneIters) {
2600     const Instruction *ToDrop = nullptr;
2601     for (const auto &InsPair : RhsDeps) {
2602       if (!ShouldCountInsn(InsPair.first)) {
2603         ToDrop = InsPair.first;
2604         break;
2605       }
2606     }
2607     if (ToDrop == nullptr)
2608       break;
2609     RhsDeps.erase(ToDrop);
2610   }
2611 
2612   for (const auto &InsPair : RhsDeps) {
2613     // Finally accumulate latency that we can only attribute to computing the
2614     // RHS condition. Use latency because we are essentially trying to calculate
2615     // the cost of the dependency chain.
2616     // Possible TODO: We could try to estimate ILP and make this more precise.
2617     CostOfIncluding +=
2618         TTI.getInstructionCost(InsPair.first, TargetTransformInfo::TCK_Latency);
2619 
2620     if (CostOfIncluding > CostThresh)
2621       return false;
2622   }
2623   return true;
2624 }
2625 
2626 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
2627                                                MachineBasicBlock *TBB,
2628                                                MachineBasicBlock *FBB,
2629                                                MachineBasicBlock *CurBB,
2630                                                MachineBasicBlock *SwitchBB,
2631                                                Instruction::BinaryOps Opc,
2632                                                BranchProbability TProb,
2633                                                BranchProbability FProb,
2634                                                bool InvertCond) {
2635   // Skip over not part of the tree and remember to invert op and operands at
2636   // next level.
2637   Value *NotCond;
2638   if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) &&
2639       InBlock(NotCond, CurBB->getBasicBlock())) {
2640     FindMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb,
2641                          !InvertCond);
2642     return;
2643   }
2644 
2645   const Instruction *BOp = dyn_cast<Instruction>(Cond);
2646   const Value *BOpOp0, *BOpOp1;
2647   // Compute the effective opcode for Cond, taking into account whether it needs
2648   // to be inverted, e.g.
2649   //   and (not (or A, B)), C
2650   // gets lowered as
2651   //   and (and (not A, not B), C)
2652   Instruction::BinaryOps BOpc = (Instruction::BinaryOps)0;
2653   if (BOp) {
2654     BOpc = match(BOp, m_LogicalAnd(m_Value(BOpOp0), m_Value(BOpOp1)))
2655                ? Instruction::And
2656                : (match(BOp, m_LogicalOr(m_Value(BOpOp0), m_Value(BOpOp1)))
2657                       ? Instruction::Or
2658                       : (Instruction::BinaryOps)0);
2659     if (InvertCond) {
2660       if (BOpc == Instruction::And)
2661         BOpc = Instruction::Or;
2662       else if (BOpc == Instruction::Or)
2663         BOpc = Instruction::And;
2664     }
2665   }
2666 
2667   // If this node is not part of the or/and tree, emit it as a branch.
2668   // Note that all nodes in the tree should have same opcode.
2669   bool BOpIsInOrAndTree = BOpc && BOpc == Opc && BOp->hasOneUse();
2670   if (!BOpIsInOrAndTree || BOp->getParent() != CurBB->getBasicBlock() ||
2671       !InBlock(BOpOp0, CurBB->getBasicBlock()) ||
2672       !InBlock(BOpOp1, CurBB->getBasicBlock())) {
2673     EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB,
2674                                  TProb, FProb, InvertCond);
2675     return;
2676   }
2677 
2678   //  Create TmpBB after CurBB.
2679   MachineFunction::iterator BBI(CurBB);
2680   MachineFunction &MF = DAG.getMachineFunction();
2681   MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
2682   CurBB->getParent()->insert(++BBI, TmpBB);
2683 
2684   if (Opc == Instruction::Or) {
2685     // Codegen X | Y as:
2686     // BB1:
2687     //   jmp_if_X TBB
2688     //   jmp TmpBB
2689     // TmpBB:
2690     //   jmp_if_Y TBB
2691     //   jmp FBB
2692     //
2693 
2694     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2695     // The requirement is that
2696     //   TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
2697     //     = TrueProb for original BB.
2698     // Assuming the original probabilities are A and B, one choice is to set
2699     // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to
2700     // A/(1+B) and 2B/(1+B). This choice assumes that
2701     //   TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
2702     // Another choice is to assume TrueProb for BB1 equals to TrueProb for
2703     // TmpBB, but the math is more complicated.
2704 
2705     auto NewTrueProb = TProb / 2;
2706     auto NewFalseProb = TProb / 2 + FProb;
2707     // Emit the LHS condition.
2708     FindMergedConditions(BOpOp0, TBB, TmpBB, CurBB, SwitchBB, Opc, NewTrueProb,
2709                          NewFalseProb, InvertCond);
2710 
2711     // Normalize A/2 and B to get A/(1+B) and 2B/(1+B).
2712     SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb};
2713     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2714     // Emit the RHS condition into TmpBB.
2715     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2716                          Probs[1], InvertCond);
2717   } else {
2718     assert(Opc == Instruction::And && "Unknown merge op!");
2719     // Codegen X & Y as:
2720     // BB1:
2721     //   jmp_if_X TmpBB
2722     //   jmp FBB
2723     // TmpBB:
2724     //   jmp_if_Y TBB
2725     //   jmp FBB
2726     //
2727     //  This requires creation of TmpBB after CurBB.
2728 
2729     // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
2730     // The requirement is that
2731     //   FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
2732     //     = FalseProb for original BB.
2733     // Assuming the original probabilities are A and B, one choice is to set
2734     // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to
2735     // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 ==
2736     // TrueProb for BB1 * FalseProb for TmpBB.
2737 
2738     auto NewTrueProb = TProb + FProb / 2;
2739     auto NewFalseProb = FProb / 2;
2740     // Emit the LHS condition.
2741     FindMergedConditions(BOpOp0, TmpBB, FBB, CurBB, SwitchBB, Opc, NewTrueProb,
2742                          NewFalseProb, InvertCond);
2743 
2744     // Normalize A and B/2 to get 2A/(1+A) and B/(1+A).
2745     SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2};
2746     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
2747     // Emit the RHS condition into TmpBB.
2748     FindMergedConditions(BOpOp1, TBB, FBB, TmpBB, SwitchBB, Opc, Probs[0],
2749                          Probs[1], InvertCond);
2750   }
2751 }
2752 
2753 /// If the set of cases should be emitted as a series of branches, return true.
2754 /// If we should emit this as a bunch of and/or'd together conditions, return
2755 /// false.
2756 bool
2757 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases) {
2758   if (Cases.size() != 2) return true;
2759 
2760   // If this is two comparisons of the same values or'd or and'd together, they
2761   // will get folded into a single comparison, so don't emit two blocks.
2762   if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
2763        Cases[0].CmpRHS == Cases[1].CmpRHS) ||
2764       (Cases[0].CmpRHS == Cases[1].CmpLHS &&
2765        Cases[0].CmpLHS == Cases[1].CmpRHS)) {
2766     return false;
2767   }
2768 
2769   // Handle: (X != null) | (Y != null) --> (X|Y) != 0
2770   // Handle: (X == null) & (Y == null) --> (X|Y) == 0
2771   if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
2772       Cases[0].CC == Cases[1].CC &&
2773       isa<Constant>(Cases[0].CmpRHS) &&
2774       cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
2775     if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
2776       return false;
2777     if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
2778       return false;
2779   }
2780 
2781   return true;
2782 }
2783 
2784 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
2785   MachineBasicBlock *BrMBB = FuncInfo.MBB;
2786 
2787   // Update machine-CFG edges.
2788   MachineBasicBlock *Succ0MBB = FuncInfo.getMBB(I.getSuccessor(0));
2789 
2790   if (I.isUnconditional()) {
2791     // Update machine-CFG edges.
2792     BrMBB->addSuccessor(Succ0MBB);
2793 
2794     // If this is not a fall-through branch or optimizations are switched off,
2795     // emit the branch.
2796     if (Succ0MBB != NextBlock(BrMBB) ||
2797         TM.getOptLevel() == CodeGenOptLevel::None) {
2798       auto Br = DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
2799                             getControlRoot(), DAG.getBasicBlock(Succ0MBB));
2800       setValue(&I, Br);
2801       DAG.setRoot(Br);
2802     }
2803 
2804     return;
2805   }
2806 
2807   // If this condition is one of the special cases we handle, do special stuff
2808   // now.
2809   const Value *CondVal = I.getCondition();
2810   MachineBasicBlock *Succ1MBB = FuncInfo.getMBB(I.getSuccessor(1));
2811 
2812   // If this is a series of conditions that are or'd or and'd together, emit
2813   // this as a sequence of branches instead of setcc's with and/or operations.
2814   // As long as jumps are not expensive (exceptions for multi-use logic ops,
2815   // unpredictable branches, and vector extracts because those jumps are likely
2816   // expensive for any target), this should improve performance.
2817   // For example, instead of something like:
2818   //     cmp A, B
2819   //     C = seteq
2820   //     cmp D, E
2821   //     F = setle
2822   //     or C, F
2823   //     jnz foo
2824   // Emit:
2825   //     cmp A, B
2826   //     je foo
2827   //     cmp D, E
2828   //     jle foo
2829   bool IsUnpredictable = I.hasMetadata(LLVMContext::MD_unpredictable);
2830   const Instruction *BOp = dyn_cast<Instruction>(CondVal);
2831   if (!DAG.getTargetLoweringInfo().isJumpExpensive() && BOp &&
2832       BOp->hasOneUse() && !IsUnpredictable) {
2833     Value *Vec;
2834     const Value *BOp0, *BOp1;
2835     Instruction::BinaryOps Opcode = (Instruction::BinaryOps)0;
2836     if (match(BOp, m_LogicalAnd(m_Value(BOp0), m_Value(BOp1))))
2837       Opcode = Instruction::And;
2838     else if (match(BOp, m_LogicalOr(m_Value(BOp0), m_Value(BOp1))))
2839       Opcode = Instruction::Or;
2840 
2841     if (Opcode &&
2842         !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) &&
2843           match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value()))) &&
2844         !shouldKeepJumpConditionsTogether(
2845             FuncInfo, I, Opcode, BOp0, BOp1,
2846             DAG.getTargetLoweringInfo().getJumpConditionMergingParams(
2847                 Opcode, BOp0, BOp1))) {
2848       FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB, Opcode,
2849                            getEdgeProbability(BrMBB, Succ0MBB),
2850                            getEdgeProbability(BrMBB, Succ1MBB),
2851                            /*InvertCond=*/false);
2852       // If the compares in later blocks need to use values not currently
2853       // exported from this block, export them now.  This block should always
2854       // be the first entry.
2855       assert(SL->SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
2856 
2857       // Allow some cases to be rejected.
2858       if (ShouldEmitAsBranches(SL->SwitchCases)) {
2859         for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i) {
2860           ExportFromCurrentBlock(SL->SwitchCases[i].CmpLHS);
2861           ExportFromCurrentBlock(SL->SwitchCases[i].CmpRHS);
2862         }
2863 
2864         // Emit the branch for this block.
2865         visitSwitchCase(SL->SwitchCases[0], BrMBB);
2866         SL->SwitchCases.erase(SL->SwitchCases.begin());
2867         return;
2868       }
2869 
2870       // Okay, we decided not to do this, remove any inserted MBB's and clear
2871       // SwitchCases.
2872       for (unsigned i = 1, e = SL->SwitchCases.size(); i != e; ++i)
2873         FuncInfo.MF->erase(SL->SwitchCases[i].ThisBB);
2874 
2875       SL->SwitchCases.clear();
2876     }
2877   }
2878 
2879   // Create a CaseBlock record representing this branch.
2880   CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
2881                nullptr, Succ0MBB, Succ1MBB, BrMBB, getCurSDLoc(),
2882                BranchProbability::getUnknown(), BranchProbability::getUnknown(),
2883                IsUnpredictable);
2884 
2885   // Use visitSwitchCase to actually insert the fast branch sequence for this
2886   // cond branch.
2887   visitSwitchCase(CB, BrMBB);
2888 }
2889 
2890 /// visitSwitchCase - Emits the necessary code to represent a single node in
2891 /// the binary search tree resulting from lowering a switch instruction.
2892 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
2893                                           MachineBasicBlock *SwitchBB) {
2894   SDValue Cond;
2895   SDValue CondLHS = getValue(CB.CmpLHS);
2896   SDLoc dl = CB.DL;
2897 
2898   if (CB.CC == ISD::SETTRUE) {
2899     // Branch or fall through to TrueBB.
2900     addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2901     SwitchBB->normalizeSuccProbs();
2902     if (CB.TrueBB != NextBlock(SwitchBB)) {
2903       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, getControlRoot(),
2904                               DAG.getBasicBlock(CB.TrueBB)));
2905     }
2906     return;
2907   }
2908 
2909   auto &TLI = DAG.getTargetLoweringInfo();
2910   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), CB.CmpLHS->getType());
2911 
2912   // Build the setcc now.
2913   if (!CB.CmpMHS) {
2914     // Fold "(X == true)" to X and "(X == false)" to !X to
2915     // handle common cases produced by branch lowering.
2916     if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
2917         CB.CC == ISD::SETEQ)
2918       Cond = CondLHS;
2919     else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
2920              CB.CC == ISD::SETEQ) {
2921       SDValue True = DAG.getConstant(1, dl, CondLHS.getValueType());
2922       Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
2923     } else {
2924       SDValue CondRHS = getValue(CB.CmpRHS);
2925 
2926       // If a pointer's DAG type is larger than its memory type then the DAG
2927       // values are zero-extended. This breaks signed comparisons so truncate
2928       // back to the underlying type before doing the compare.
2929       if (CondLHS.getValueType() != MemVT) {
2930         CondLHS = DAG.getPtrExtOrTrunc(CondLHS, getCurSDLoc(), MemVT);
2931         CondRHS = DAG.getPtrExtOrTrunc(CondRHS, getCurSDLoc(), MemVT);
2932       }
2933       Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, CondRHS, CB.CC);
2934     }
2935   } else {
2936     assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
2937 
2938     const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
2939     const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
2940 
2941     SDValue CmpOp = getValue(CB.CmpMHS);
2942     EVT VT = CmpOp.getValueType();
2943 
2944     if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
2945       Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, dl, VT),
2946                           ISD::SETLE);
2947     } else {
2948       SDValue SUB = DAG.getNode(ISD::SUB, dl,
2949                                 VT, CmpOp, DAG.getConstant(Low, dl, VT));
2950       Cond = DAG.getSetCC(dl, MVT::i1, SUB,
2951                           DAG.getConstant(High-Low, dl, VT), ISD::SETULE);
2952     }
2953   }
2954 
2955   // Update successor info
2956   addSuccessorWithProb(SwitchBB, CB.TrueBB, CB.TrueProb);
2957   // TrueBB and FalseBB are always different unless the incoming IR is
2958   // degenerate. This only happens when running llc on weird IR.
2959   if (CB.TrueBB != CB.FalseBB)
2960     addSuccessorWithProb(SwitchBB, CB.FalseBB, CB.FalseProb);
2961   SwitchBB->normalizeSuccProbs();
2962 
2963   // If the lhs block is the next block, invert the condition so that we can
2964   // fall through to the lhs instead of the rhs block.
2965   if (CB.TrueBB == NextBlock(SwitchBB)) {
2966     std::swap(CB.TrueBB, CB.FalseBB);
2967     SDValue True = DAG.getConstant(1, dl, Cond.getValueType());
2968     Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
2969   }
2970 
2971   SDNodeFlags Flags;
2972   Flags.setUnpredictable(CB.IsUnpredictable);
2973   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl, MVT::Other, getControlRoot(),
2974                                Cond, DAG.getBasicBlock(CB.TrueBB), Flags);
2975 
2976   setValue(CurInst, BrCond);
2977 
2978   // Insert the false branch. Do this even if it's a fall through branch,
2979   // this makes it easier to do DAG optimizations which require inverting
2980   // the branch condition.
2981   BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
2982                        DAG.getBasicBlock(CB.FalseBB));
2983 
2984   DAG.setRoot(BrCond);
2985 }
2986 
2987 /// visitJumpTable - Emit JumpTable node in the current MBB
2988 void SelectionDAGBuilder::visitJumpTable(SwitchCG::JumpTable &JT) {
2989   // Emit the code for the jump table
2990   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
2991   assert(JT.Reg && "Should lower JT Header first!");
2992   EVT PTy = DAG.getTargetLoweringInfo().getJumpTableRegTy(DAG.getDataLayout());
2993   SDValue Index = DAG.getCopyFromReg(getControlRoot(), *JT.SL, JT.Reg, PTy);
2994   SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
2995   SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, *JT.SL, MVT::Other,
2996                                     Index.getValue(1), Table, Index);
2997   DAG.setRoot(BrJumpTable);
2998 }
2999 
3000 /// visitJumpTableHeader - This function emits necessary code to produce index
3001 /// in the JumpTable from switch case.
3002 void SelectionDAGBuilder::visitJumpTableHeader(SwitchCG::JumpTable &JT,
3003                                                JumpTableHeader &JTH,
3004                                                MachineBasicBlock *SwitchBB) {
3005   assert(JT.SL && "Should set SDLoc for SelectionDAG!");
3006   const SDLoc &dl = *JT.SL;
3007 
3008   // Subtract the lowest switch case value from the value being switched on.
3009   SDValue SwitchOp = getValue(JTH.SValue);
3010   EVT VT = SwitchOp.getValueType();
3011   SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, SwitchOp,
3012                             DAG.getConstant(JTH.First, dl, VT));
3013 
3014   // The SDNode we just created, which holds the value being switched on minus
3015   // the smallest case value, needs to be copied to a virtual register so it
3016   // can be used as an index into the jump table in a subsequent basic block.
3017   // This value may be smaller or larger than the target's pointer type, and
3018   // therefore require extension or truncating.
3019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3020   SwitchOp =
3021       DAG.getZExtOrTrunc(Sub, dl, TLI.getJumpTableRegTy(DAG.getDataLayout()));
3022 
3023   Register JumpTableReg =
3024       FuncInfo.CreateReg(TLI.getJumpTableRegTy(DAG.getDataLayout()));
3025   SDValue CopyTo =
3026       DAG.getCopyToReg(getControlRoot(), dl, JumpTableReg, SwitchOp);
3027   JT.Reg = JumpTableReg;
3028 
3029   if (!JTH.FallthroughUnreachable) {
3030     // Emit the range check for the jump table, and branch to the default block
3031     // for the switch statement if the value being switched on exceeds the
3032     // largest case in the switch.
3033     SDValue CMP = DAG.getSetCC(
3034         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3035                                    Sub.getValueType()),
3036         Sub, DAG.getConstant(JTH.Last - JTH.First, dl, VT), ISD::SETUGT);
3037 
3038     SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3039                                  MVT::Other, CopyTo, CMP,
3040                                  DAG.getBasicBlock(JT.Default));
3041 
3042     // Avoid emitting unnecessary branches to the next block.
3043     if (JT.MBB != NextBlock(SwitchBB))
3044       BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
3045                            DAG.getBasicBlock(JT.MBB));
3046 
3047     DAG.setRoot(BrCond);
3048   } else {
3049     // Avoid emitting unnecessary branches to the next block.
3050     if (JT.MBB != NextBlock(SwitchBB))
3051       DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, CopyTo,
3052                               DAG.getBasicBlock(JT.MBB)));
3053     else
3054       DAG.setRoot(CopyTo);
3055   }
3056 }
3057 
3058 /// Create a LOAD_STACK_GUARD node, and let it carry the target specific global
3059 /// variable if there exists one.
3060 static SDValue getLoadStackGuard(SelectionDAG &DAG, const SDLoc &DL,
3061                                  SDValue &Chain) {
3062   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3063   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3064   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3065   MachineFunction &MF = DAG.getMachineFunction();
3066   Value *Global = TLI.getSDagStackGuard(*MF.getFunction().getParent());
3067   MachineSDNode *Node =
3068       DAG.getMachineNode(TargetOpcode::LOAD_STACK_GUARD, DL, PtrTy, Chain);
3069   if (Global) {
3070     MachinePointerInfo MPInfo(Global);
3071     auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant |
3072                  MachineMemOperand::MODereferenceable;
3073     MachineMemOperand *MemRef = MF.getMachineMemOperand(
3074         MPInfo, Flags, LocationSize::precise(PtrTy.getSizeInBits() / 8),
3075         DAG.getEVTAlign(PtrTy));
3076     DAG.setNodeMemRefs(Node, {MemRef});
3077   }
3078   if (PtrTy != PtrMemTy)
3079     return DAG.getPtrExtOrTrunc(SDValue(Node, 0), DL, PtrMemTy);
3080   return SDValue(Node, 0);
3081 }
3082 
3083 /// Codegen a new tail for a stack protector check ParentMBB which has had its
3084 /// tail spliced into a stack protector check success bb.
3085 ///
3086 /// For a high level explanation of how this fits into the stack protector
3087 /// generation see the comment on the declaration of class
3088 /// StackProtectorDescriptor.
3089 void SelectionDAGBuilder::visitSPDescriptorParent(StackProtectorDescriptor &SPD,
3090                                                   MachineBasicBlock *ParentBB) {
3091 
3092   // First create the loads to the guard/stack slot for the comparison.
3093   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3094   EVT PtrTy = TLI.getPointerTy(DAG.getDataLayout());
3095   EVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout());
3096 
3097   MachineFrameInfo &MFI = ParentBB->getParent()->getFrameInfo();
3098   int FI = MFI.getStackProtectorIndex();
3099 
3100   SDValue Guard;
3101   SDLoc dl = getCurSDLoc();
3102   SDValue StackSlotPtr = DAG.getFrameIndex(FI, PtrTy);
3103   const Module &M = *ParentBB->getParent()->getFunction().getParent();
3104   Align Align =
3105       DAG.getDataLayout().getPrefTypeAlign(PointerType::get(M.getContext(), 0));
3106 
3107   // Generate code to load the content of the guard slot.
3108   SDValue GuardVal = DAG.getLoad(
3109       PtrMemTy, dl, DAG.getEntryNode(), StackSlotPtr,
3110       MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), Align,
3111       MachineMemOperand::MOVolatile);
3112 
3113   if (TLI.useStackGuardXorFP())
3114     GuardVal = TLI.emitStackGuardXorFP(DAG, GuardVal, dl);
3115 
3116   // Retrieve guard check function, nullptr if instrumentation is inlined.
3117   if (const Function *GuardCheckFn = TLI.getSSPStackGuardCheck(M)) {
3118     // The target provides a guard check function to validate the guard value.
3119     // Generate a call to that function with the content of the guard slot as
3120     // argument.
3121     FunctionType *FnTy = GuardCheckFn->getFunctionType();
3122     assert(FnTy->getNumParams() == 1 && "Invalid function signature");
3123 
3124     TargetLowering::ArgListTy Args;
3125     TargetLowering::ArgListEntry Entry;
3126     Entry.Node = GuardVal;
3127     Entry.Ty = FnTy->getParamType(0);
3128     if (GuardCheckFn->hasParamAttribute(0, Attribute::AttrKind::InReg))
3129       Entry.IsInReg = true;
3130     Args.push_back(Entry);
3131 
3132     TargetLowering::CallLoweringInfo CLI(DAG);
3133     CLI.setDebugLoc(getCurSDLoc())
3134         .setChain(DAG.getEntryNode())
3135         .setCallee(GuardCheckFn->getCallingConv(), FnTy->getReturnType(),
3136                    getValue(GuardCheckFn), std::move(Args));
3137 
3138     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
3139     DAG.setRoot(Result.second);
3140     return;
3141   }
3142 
3143   // If useLoadStackGuardNode returns true, generate LOAD_STACK_GUARD.
3144   // Otherwise, emit a volatile load to retrieve the stack guard value.
3145   SDValue Chain = DAG.getEntryNode();
3146   if (TLI.useLoadStackGuardNode(M)) {
3147     Guard = getLoadStackGuard(DAG, dl, Chain);
3148   } else {
3149     const Value *IRGuard = TLI.getSDagStackGuard(M);
3150     SDValue GuardPtr = getValue(IRGuard);
3151 
3152     Guard = DAG.getLoad(PtrMemTy, dl, Chain, GuardPtr,
3153                         MachinePointerInfo(IRGuard, 0), Align,
3154                         MachineMemOperand::MOVolatile);
3155   }
3156 
3157   // Perform the comparison via a getsetcc.
3158   SDValue Cmp = DAG.getSetCC(dl, TLI.getSetCCResultType(DAG.getDataLayout(),
3159                                                         *DAG.getContext(),
3160                                                         Guard.getValueType()),
3161                              Guard, GuardVal, ISD::SETNE);
3162 
3163   // If the guard/stackslot do not equal, branch to failure MBB.
3164   SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
3165                                MVT::Other, GuardVal.getOperand(0),
3166                                Cmp, DAG.getBasicBlock(SPD.getFailureMBB()));
3167   // Otherwise branch to success MBB.
3168   SDValue Br = DAG.getNode(ISD::BR, dl,
3169                            MVT::Other, BrCond,
3170                            DAG.getBasicBlock(SPD.getSuccessMBB()));
3171 
3172   DAG.setRoot(Br);
3173 }
3174 
3175 /// Codegen the failure basic block for a stack protector check.
3176 ///
3177 /// A failure stack protector machine basic block consists simply of a call to
3178 /// __stack_chk_fail().
3179 ///
3180 /// For a high level explanation of how this fits into the stack protector
3181 /// generation see the comment on the declaration of class
3182 /// StackProtectorDescriptor.
3183 void
3184 SelectionDAGBuilder::visitSPDescriptorFailure(StackProtectorDescriptor &SPD) {
3185   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3186   TargetLowering::MakeLibCallOptions CallOptions;
3187   CallOptions.setDiscardResult(true);
3188   SDValue Chain = TLI.makeLibCall(DAG, RTLIB::STACKPROTECTOR_CHECK_FAIL,
3189                                   MVT::isVoid, {}, CallOptions, getCurSDLoc())
3190                       .second;
3191 
3192   // Emit a trap instruction if we are required to do so.
3193   const TargetOptions &TargetOpts = DAG.getTarget().Options;
3194   if (TargetOpts.TrapUnreachable && !TargetOpts.NoTrapAfterNoreturn)
3195     Chain = DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, Chain);
3196 
3197   DAG.setRoot(Chain);
3198 }
3199 
3200 /// visitBitTestHeader - This function emits necessary code to produce value
3201 /// suitable for "bit tests"
3202 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
3203                                              MachineBasicBlock *SwitchBB) {
3204   SDLoc dl = getCurSDLoc();
3205 
3206   // Subtract the minimum value.
3207   SDValue SwitchOp = getValue(B.SValue);
3208   EVT VT = SwitchOp.getValueType();
3209   SDValue RangeSub =
3210       DAG.getNode(ISD::SUB, dl, VT, SwitchOp, DAG.getConstant(B.First, dl, VT));
3211 
3212   // Determine the type of the test operands.
3213   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3214   bool UsePtrType = false;
3215   if (!TLI.isTypeLegal(VT)) {
3216     UsePtrType = true;
3217   } else {
3218     for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
3219       if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
3220         // Switch table case range are encoded into series of masks.
3221         // Just use pointer type, it's guaranteed to fit.
3222         UsePtrType = true;
3223         break;
3224       }
3225   }
3226   SDValue Sub = RangeSub;
3227   if (UsePtrType) {
3228     VT = TLI.getPointerTy(DAG.getDataLayout());
3229     Sub = DAG.getZExtOrTrunc(Sub, dl, VT);
3230   }
3231 
3232   B.RegVT = VT.getSimpleVT();
3233   B.Reg = FuncInfo.CreateReg(B.RegVT);
3234   SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), dl, B.Reg, Sub);
3235 
3236   MachineBasicBlock* MBB = B.Cases[0].ThisBB;
3237 
3238   if (!B.FallthroughUnreachable)
3239     addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb);
3240   addSuccessorWithProb(SwitchBB, MBB, B.Prob);
3241   SwitchBB->normalizeSuccProbs();
3242 
3243   SDValue Root = CopyTo;
3244   if (!B.FallthroughUnreachable) {
3245     // Conditional branch to the default block.
3246     SDValue RangeCmp = DAG.getSetCC(dl,
3247         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3248                                RangeSub.getValueType()),
3249         RangeSub, DAG.getConstant(B.Range, dl, RangeSub.getValueType()),
3250         ISD::SETUGT);
3251 
3252     Root = DAG.getNode(ISD::BRCOND, dl, MVT::Other, Root, RangeCmp,
3253                        DAG.getBasicBlock(B.Default));
3254   }
3255 
3256   // Avoid emitting unnecessary branches to the next block.
3257   if (MBB != NextBlock(SwitchBB))
3258     Root = DAG.getNode(ISD::BR, dl, MVT::Other, Root, DAG.getBasicBlock(MBB));
3259 
3260   DAG.setRoot(Root);
3261 }
3262 
3263 /// visitBitTestCase - this function produces one "bit test"
3264 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
3265                                            MachineBasicBlock *NextMBB,
3266                                            BranchProbability BranchProbToNext,
3267                                            Register Reg, BitTestCase &B,
3268                                            MachineBasicBlock *SwitchBB) {
3269   SDLoc dl = getCurSDLoc();
3270   MVT VT = BB.RegVT;
3271   SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), dl, Reg, VT);
3272   SDValue Cmp;
3273   unsigned PopCount = llvm::popcount(B.Mask);
3274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3275   if (PopCount == 1) {
3276     // Testing for a single bit; just compare the shift count with what it
3277     // would need to be to shift a 1 bit in that position.
3278     Cmp = DAG.getSetCC(
3279         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3280         ShiftOp, DAG.getConstant(llvm::countr_zero(B.Mask), dl, VT),
3281         ISD::SETEQ);
3282   } else if (PopCount == BB.Range) {
3283     // There is only one zero bit in the range, test for it directly.
3284     Cmp = DAG.getSetCC(
3285         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3286         ShiftOp, DAG.getConstant(llvm::countr_one(B.Mask), dl, VT), ISD::SETNE);
3287   } else {
3288     // Make desired shift
3289     SDValue SwitchVal = DAG.getNode(ISD::SHL, dl, VT,
3290                                     DAG.getConstant(1, dl, VT), ShiftOp);
3291 
3292     // Emit bit tests and jumps
3293     SDValue AndOp = DAG.getNode(ISD::AND, dl,
3294                                 VT, SwitchVal, DAG.getConstant(B.Mask, dl, VT));
3295     Cmp = DAG.getSetCC(
3296         dl, TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT),
3297         AndOp, DAG.getConstant(0, dl, VT), ISD::SETNE);
3298   }
3299 
3300   // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb.
3301   addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb);
3302   // The branch probability from SwitchBB to NextMBB is BranchProbToNext.
3303   addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext);
3304   // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is
3305   // one as they are relative probabilities (and thus work more like weights),
3306   // and hence we need to normalize them to let the sum of them become one.
3307   SwitchBB->normalizeSuccProbs();
3308 
3309   SDValue BrAnd = DAG.getNode(ISD::BRCOND, dl,
3310                               MVT::Other, getControlRoot(),
3311                               Cmp, DAG.getBasicBlock(B.TargetBB));
3312 
3313   // Avoid emitting unnecessary branches to the next block.
3314   if (NextMBB != NextBlock(SwitchBB))
3315     BrAnd = DAG.getNode(ISD::BR, dl, MVT::Other, BrAnd,
3316                         DAG.getBasicBlock(NextMBB));
3317 
3318   DAG.setRoot(BrAnd);
3319 }
3320 
3321 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
3322   MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
3323 
3324   // Retrieve successors. Look through artificial IR level blocks like
3325   // catchswitch for successors.
3326   MachineBasicBlock *Return = FuncInfo.getMBB(I.getSuccessor(0));
3327   const BasicBlock *EHPadBB = I.getSuccessor(1);
3328   MachineBasicBlock *EHPadMBB = FuncInfo.getMBB(EHPadBB);
3329 
3330   // Deopt and ptrauth bundles are lowered in helper functions, and we don't
3331   // have to do anything here to lower funclet bundles.
3332   assert(!I.hasOperandBundlesOtherThan(
3333              {LLVMContext::OB_deopt, LLVMContext::OB_gc_transition,
3334               LLVMContext::OB_gc_live, LLVMContext::OB_funclet,
3335               LLVMContext::OB_cfguardtarget, LLVMContext::OB_ptrauth,
3336               LLVMContext::OB_clang_arc_attachedcall}) &&
3337          "Cannot lower invokes with arbitrary operand bundles yet!");
3338 
3339   const Value *Callee(I.getCalledOperand());
3340   const Function *Fn = dyn_cast<Function>(Callee);
3341   if (isa<InlineAsm>(Callee))
3342     visitInlineAsm(I, EHPadBB);
3343   else if (Fn && Fn->isIntrinsic()) {
3344     switch (Fn->getIntrinsicID()) {
3345     default:
3346       llvm_unreachable("Cannot invoke this intrinsic");
3347     case Intrinsic::donothing:
3348       // Ignore invokes to @llvm.donothing: jump directly to the next BB.
3349     case Intrinsic::seh_try_begin:
3350     case Intrinsic::seh_scope_begin:
3351     case Intrinsic::seh_try_end:
3352     case Intrinsic::seh_scope_end:
3353       if (EHPadMBB)
3354           // a block referenced by EH table
3355           // so dtor-funclet not removed by opts
3356           EHPadMBB->setMachineBlockAddressTaken();
3357       break;
3358     case Intrinsic::experimental_patchpoint_void:
3359     case Intrinsic::experimental_patchpoint:
3360       visitPatchpoint(I, EHPadBB);
3361       break;
3362     case Intrinsic::experimental_gc_statepoint:
3363       LowerStatepoint(cast<GCStatepointInst>(I), EHPadBB);
3364       break;
3365     case Intrinsic::wasm_rethrow: {
3366       // This is usually done in visitTargetIntrinsic, but this intrinsic is
3367       // special because it can be invoked, so we manually lower it to a DAG
3368       // node here.
3369       SmallVector<SDValue, 8> Ops;
3370       Ops.push_back(getControlRoot()); // inchain for the terminator node
3371       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3372       Ops.push_back(
3373           DAG.getTargetConstant(Intrinsic::wasm_rethrow, getCurSDLoc(),
3374                                 TLI.getPointerTy(DAG.getDataLayout())));
3375       SDVTList VTs = DAG.getVTList(ArrayRef<EVT>({MVT::Other})); // outchain
3376       DAG.setRoot(DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops));
3377       break;
3378     }
3379     }
3380   } else if (I.hasDeoptState()) {
3381     // Currently we do not lower any intrinsic calls with deopt operand bundles.
3382     // Eventually we will support lowering the @llvm.experimental.deoptimize
3383     // intrinsic, and right now there are no plans to support other intrinsics
3384     // with deopt state.
3385     LowerCallSiteWithDeoptBundle(&I, getValue(Callee), EHPadBB);
3386   } else if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
3387     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), EHPadBB);
3388   } else {
3389     LowerCallTo(I, getValue(Callee), false, false, EHPadBB);
3390   }
3391 
3392   // If the value of the invoke is used outside of its defining block, make it
3393   // available as a virtual register.
3394   // We already took care of the exported value for the statepoint instruction
3395   // during call to the LowerStatepoint.
3396   if (!isa<GCStatepointInst>(I)) {
3397     CopyToExportRegsIfNeeded(&I);
3398   }
3399 
3400   SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests;
3401   BranchProbabilityInfo *BPI = FuncInfo.BPI;
3402   BranchProbability EHPadBBProb =
3403       BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB)
3404           : BranchProbability::getZero();
3405   findUnwindDestinations(FuncInfo, EHPadBB, EHPadBBProb, UnwindDests);
3406 
3407   // Update successor info.
3408   addSuccessorWithProb(InvokeMBB, Return);
3409   for (auto &UnwindDest : UnwindDests) {
3410     UnwindDest.first->setIsEHPad();
3411     addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second);
3412   }
3413   InvokeMBB->normalizeSuccProbs();
3414 
3415   // Drop into normal successor.
3416   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other, getControlRoot(),
3417                           DAG.getBasicBlock(Return)));
3418 }
3419 
3420 void SelectionDAGBuilder::visitCallBr(const CallBrInst &I) {
3421   MachineBasicBlock *CallBrMBB = FuncInfo.MBB;
3422 
3423   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
3424   // have to do anything here to lower funclet bundles.
3425   assert(!I.hasOperandBundlesOtherThan(
3426              {LLVMContext::OB_deopt, LLVMContext::OB_funclet}) &&
3427          "Cannot lower callbrs with arbitrary operand bundles yet!");
3428 
3429   assert(I.isInlineAsm() && "Only know how to handle inlineasm callbr");
3430   visitInlineAsm(I);
3431   CopyToExportRegsIfNeeded(&I);
3432 
3433   // Retrieve successors.
3434   SmallPtrSet<BasicBlock *, 8> Dests;
3435   Dests.insert(I.getDefaultDest());
3436   MachineBasicBlock *Return = FuncInfo.getMBB(I.getDefaultDest());
3437 
3438   // Update successor info.
3439   addSuccessorWithProb(CallBrMBB, Return, BranchProbability::getOne());
3440   for (unsigned i = 0, e = I.getNumIndirectDests(); i < e; ++i) {
3441     BasicBlock *Dest = I.getIndirectDest(i);
3442     MachineBasicBlock *Target = FuncInfo.getMBB(Dest);
3443     Target->setIsInlineAsmBrIndirectTarget();
3444     Target->setMachineBlockAddressTaken();
3445     Target->setLabelMustBeEmitted();
3446     // Don't add duplicate machine successors.
3447     if (Dests.insert(Dest).second)
3448       addSuccessorWithProb(CallBrMBB, Target, BranchProbability::getZero());
3449   }
3450   CallBrMBB->normalizeSuccProbs();
3451 
3452   // Drop into default successor.
3453   DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(),
3454                           MVT::Other, getControlRoot(),
3455                           DAG.getBasicBlock(Return)));
3456 }
3457 
3458 void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
3459   llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
3460 }
3461 
3462 void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
3463   assert(FuncInfo.MBB->isEHPad() &&
3464          "Call to landingpad not in landing pad!");
3465 
3466   // If there aren't registers to copy the values into (e.g., during SjLj
3467   // exceptions), then don't bother to create these DAG nodes.
3468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3469   const Constant *PersonalityFn = FuncInfo.Fn->getPersonalityFn();
3470   if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 &&
3471       TLI.getExceptionSelectorRegister(PersonalityFn) == 0)
3472     return;
3473 
3474   // If landingpad's return type is token type, we don't create DAG nodes
3475   // for its exception pointer and selector value. The extraction of exception
3476   // pointer or selector value from token type landingpads is not currently
3477   // supported.
3478   if (LP.getType()->isTokenTy())
3479     return;
3480 
3481   SmallVector<EVT, 2> ValueVTs;
3482   SDLoc dl = getCurSDLoc();
3483   ComputeValueVTs(TLI, DAG.getDataLayout(), LP.getType(), ValueVTs);
3484   assert(ValueVTs.size() == 2 && "Only two-valued landingpads are supported");
3485 
3486   // Get the two live-in registers as SDValues. The physregs have already been
3487   // copied into virtual registers.
3488   SDValue Ops[2];
3489   if (FuncInfo.ExceptionPointerVirtReg) {
3490     Ops[0] = DAG.getZExtOrTrunc(
3491         DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3492                            FuncInfo.ExceptionPointerVirtReg,
3493                            TLI.getPointerTy(DAG.getDataLayout())),
3494         dl, ValueVTs[0]);
3495   } else {
3496     Ops[0] = DAG.getConstant(0, dl, TLI.getPointerTy(DAG.getDataLayout()));
3497   }
3498   Ops[1] = DAG.getZExtOrTrunc(
3499       DAG.getCopyFromReg(DAG.getEntryNode(), dl,
3500                          FuncInfo.ExceptionSelectorVirtReg,
3501                          TLI.getPointerTy(DAG.getDataLayout())),
3502       dl, ValueVTs[1]);
3503 
3504   // Merge into one.
3505   SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
3506                             DAG.getVTList(ValueVTs), Ops);
3507   setValue(&LP, Res);
3508 }
3509 
3510 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
3511                                            MachineBasicBlock *Last) {
3512   // Update JTCases.
3513   for (JumpTableBlock &JTB : SL->JTCases)
3514     if (JTB.first.HeaderBB == First)
3515       JTB.first.HeaderBB = Last;
3516 
3517   // Update BitTestCases.
3518   for (BitTestBlock &BTB : SL->BitTestCases)
3519     if (BTB.Parent == First)
3520       BTB.Parent = Last;
3521 }
3522 
3523 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
3524   MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
3525 
3526   // Update machine-CFG edges with unique successors.
3527   SmallSet<BasicBlock*, 32> Done;
3528   for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
3529     BasicBlock *BB = I.getSuccessor(i);
3530     bool Inserted = Done.insert(BB).second;
3531     if (!Inserted)
3532         continue;
3533 
3534     MachineBasicBlock *Succ = FuncInfo.getMBB(BB);
3535     addSuccessorWithProb(IndirectBrMBB, Succ);
3536   }
3537   IndirectBrMBB->normalizeSuccProbs();
3538 
3539   DAG.setRoot(DAG.getNode(ISD::BRIND, getCurSDLoc(),
3540                           MVT::Other, getControlRoot(),
3541                           getValue(I.getAddress())));
3542 }
3543 
3544 void SelectionDAGBuilder::visitUnreachable(const UnreachableInst &I) {
3545   if (!DAG.getTarget().Options.TrapUnreachable)
3546     return;
3547 
3548   // We may be able to ignore unreachable behind a noreturn call.
3549   if (const CallInst *Call = dyn_cast_or_null<CallInst>(I.getPrevNode());
3550       Call && Call->doesNotReturn()) {
3551     if (DAG.getTarget().Options.NoTrapAfterNoreturn)
3552       return;
3553     // Do not emit an additional trap instruction.
3554     if (Call->isNonContinuableTrap())
3555       return;
3556   }
3557 
3558   DAG.setRoot(DAG.getNode(ISD::TRAP, getCurSDLoc(), MVT::Other, DAG.getRoot()));
3559 }
3560 
3561 void SelectionDAGBuilder::visitUnary(const User &I, unsigned Opcode) {
3562   SDNodeFlags Flags;
3563   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3564     Flags.copyFMF(*FPOp);
3565 
3566   SDValue Op = getValue(I.getOperand(0));
3567   SDValue UnNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op.getValueType(),
3568                                     Op, Flags);
3569   setValue(&I, UnNodeValue);
3570 }
3571 
3572 void SelectionDAGBuilder::visitBinary(const User &I, unsigned Opcode) {
3573   SDNodeFlags Flags;
3574   if (auto *OFBinOp = dyn_cast<OverflowingBinaryOperator>(&I)) {
3575     Flags.setNoSignedWrap(OFBinOp->hasNoSignedWrap());
3576     Flags.setNoUnsignedWrap(OFBinOp->hasNoUnsignedWrap());
3577   }
3578   if (auto *ExactOp = dyn_cast<PossiblyExactOperator>(&I))
3579     Flags.setExact(ExactOp->isExact());
3580   if (auto *DisjointOp = dyn_cast<PossiblyDisjointInst>(&I))
3581     Flags.setDisjoint(DisjointOp->isDisjoint());
3582   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3583     Flags.copyFMF(*FPOp);
3584 
3585   SDValue Op1 = getValue(I.getOperand(0));
3586   SDValue Op2 = getValue(I.getOperand(1));
3587   SDValue BinNodeValue = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(),
3588                                      Op1, Op2, Flags);
3589   setValue(&I, BinNodeValue);
3590 }
3591 
3592 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
3593   SDValue Op1 = getValue(I.getOperand(0));
3594   SDValue Op2 = getValue(I.getOperand(1));
3595 
3596   EVT ShiftTy = DAG.getTargetLoweringInfo().getShiftAmountTy(
3597       Op1.getValueType(), DAG.getDataLayout());
3598 
3599   // Coerce the shift amount to the right type if we can. This exposes the
3600   // truncate or zext to optimization early.
3601   if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
3602     assert(ShiftTy.getSizeInBits() >= Log2_32_Ceil(Op1.getValueSizeInBits()) &&
3603            "Unexpected shift type");
3604     Op2 = DAG.getZExtOrTrunc(Op2, getCurSDLoc(), ShiftTy);
3605   }
3606 
3607   bool nuw = false;
3608   bool nsw = false;
3609   bool exact = false;
3610 
3611   if (Opcode == ISD::SRL || Opcode == ISD::SRA || Opcode == ISD::SHL) {
3612 
3613     if (const OverflowingBinaryOperator *OFBinOp =
3614             dyn_cast<const OverflowingBinaryOperator>(&I)) {
3615       nuw = OFBinOp->hasNoUnsignedWrap();
3616       nsw = OFBinOp->hasNoSignedWrap();
3617     }
3618     if (const PossiblyExactOperator *ExactOp =
3619             dyn_cast<const PossiblyExactOperator>(&I))
3620       exact = ExactOp->isExact();
3621   }
3622   SDNodeFlags Flags;
3623   Flags.setExact(exact);
3624   Flags.setNoSignedWrap(nsw);
3625   Flags.setNoUnsignedWrap(nuw);
3626   SDValue Res = DAG.getNode(Opcode, getCurSDLoc(), Op1.getValueType(), Op1, Op2,
3627                             Flags);
3628   setValue(&I, Res);
3629 }
3630 
3631 void SelectionDAGBuilder::visitSDiv(const User &I) {
3632   SDValue Op1 = getValue(I.getOperand(0));
3633   SDValue Op2 = getValue(I.getOperand(1));
3634 
3635   SDNodeFlags Flags;
3636   Flags.setExact(isa<PossiblyExactOperator>(&I) &&
3637                  cast<PossiblyExactOperator>(&I)->isExact());
3638   setValue(&I, DAG.getNode(ISD::SDIV, getCurSDLoc(), Op1.getValueType(), Op1,
3639                            Op2, Flags));
3640 }
3641 
3642 void SelectionDAGBuilder::visitICmp(const ICmpInst &I) {
3643   ICmpInst::Predicate predicate = I.getPredicate();
3644   SDValue Op1 = getValue(I.getOperand(0));
3645   SDValue Op2 = getValue(I.getOperand(1));
3646   ISD::CondCode Opcode = getICmpCondCode(predicate);
3647 
3648   auto &TLI = DAG.getTargetLoweringInfo();
3649   EVT MemVT =
3650       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3651 
3652   // If a pointer's DAG type is larger than its memory type then the DAG values
3653   // are zero-extended. This breaks signed comparisons so truncate back to the
3654   // underlying type before doing the compare.
3655   if (Op1.getValueType() != MemVT) {
3656     Op1 = DAG.getPtrExtOrTrunc(Op1, getCurSDLoc(), MemVT);
3657     Op2 = DAG.getPtrExtOrTrunc(Op2, getCurSDLoc(), MemVT);
3658   }
3659 
3660   SDNodeFlags Flags;
3661   Flags.setSameSign(I.hasSameSign());
3662   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3663 
3664   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3665                                                         I.getType());
3666   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Opcode));
3667 }
3668 
3669 void SelectionDAGBuilder::visitFCmp(const FCmpInst &I) {
3670   FCmpInst::Predicate predicate = I.getPredicate();
3671   SDValue Op1 = getValue(I.getOperand(0));
3672   SDValue Op2 = getValue(I.getOperand(1));
3673 
3674   ISD::CondCode Condition = getFCmpCondCode(predicate);
3675   auto *FPMO = cast<FPMathOperator>(&I);
3676   if (FPMO->hasNoNaNs() || TM.Options.NoNaNsFPMath)
3677     Condition = getFCmpCodeWithoutNaN(Condition);
3678 
3679   SDNodeFlags Flags;
3680   Flags.copyFMF(*FPMO);
3681   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
3682 
3683   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3684                                                         I.getType());
3685   setValue(&I, DAG.getSetCC(getCurSDLoc(), DestVT, Op1, Op2, Condition));
3686 }
3687 
3688 // Check if the condition of the select has one use or two users that are both
3689 // selects with the same condition.
3690 static bool hasOnlySelectUsers(const Value *Cond) {
3691   return llvm::all_of(Cond->users(), [](const Value *V) {
3692     return isa<SelectInst>(V);
3693   });
3694 }
3695 
3696 void SelectionDAGBuilder::visitSelect(const User &I) {
3697   SmallVector<EVT, 4> ValueVTs;
3698   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
3699                   ValueVTs);
3700   unsigned NumValues = ValueVTs.size();
3701   if (NumValues == 0) return;
3702 
3703   SmallVector<SDValue, 4> Values(NumValues);
3704   SDValue Cond     = getValue(I.getOperand(0));
3705   SDValue LHSVal   = getValue(I.getOperand(1));
3706   SDValue RHSVal   = getValue(I.getOperand(2));
3707   SmallVector<SDValue, 1> BaseOps(1, Cond);
3708   ISD::NodeType OpCode =
3709       Cond.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT;
3710 
3711   bool IsUnaryAbs = false;
3712   bool Negate = false;
3713 
3714   SDNodeFlags Flags;
3715   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
3716     Flags.copyFMF(*FPOp);
3717 
3718   Flags.setUnpredictable(
3719       cast<SelectInst>(I).getMetadata(LLVMContext::MD_unpredictable));
3720 
3721   // Min/max matching is only viable if all output VTs are the same.
3722   if (all_equal(ValueVTs)) {
3723     EVT VT = ValueVTs[0];
3724     LLVMContext &Ctx = *DAG.getContext();
3725     auto &TLI = DAG.getTargetLoweringInfo();
3726 
3727     // We care about the legality of the operation after it has been type
3728     // legalized.
3729     while (TLI.getTypeAction(Ctx, VT) != TargetLoweringBase::TypeLegal)
3730       VT = TLI.getTypeToTransformTo(Ctx, VT);
3731 
3732     // If the vselect is legal, assume we want to leave this as a vector setcc +
3733     // vselect. Otherwise, if this is going to be scalarized, we want to see if
3734     // min/max is legal on the scalar type.
3735     bool UseScalarMinMax = VT.isVector() &&
3736       !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT);
3737 
3738     // ValueTracking's select pattern matching does not account for -0.0,
3739     // so we can't lower to FMINIMUM/FMAXIMUM because those nodes specify that
3740     // -0.0 is less than +0.0.
3741     const Value *LHS, *RHS;
3742     auto SPR = matchSelectPattern(&I, LHS, RHS);
3743     ISD::NodeType Opc = ISD::DELETED_NODE;
3744     switch (SPR.Flavor) {
3745     case SPF_UMAX:    Opc = ISD::UMAX; break;
3746     case SPF_UMIN:    Opc = ISD::UMIN; break;
3747     case SPF_SMAX:    Opc = ISD::SMAX; break;
3748     case SPF_SMIN:    Opc = ISD::SMIN; break;
3749     case SPF_FMINNUM:
3750       switch (SPR.NaNBehavior) {
3751       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3752       case SPNB_RETURNS_NAN: break;
3753       case SPNB_RETURNS_OTHER: Opc = ISD::FMINNUM; break;
3754       case SPNB_RETURNS_ANY:
3755         if (TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT) ||
3756             (UseScalarMinMax &&
3757              TLI.isOperationLegalOrCustom(ISD::FMINNUM, VT.getScalarType())))
3758           Opc = ISD::FMINNUM;
3759         break;
3760       }
3761       break;
3762     case SPF_FMAXNUM:
3763       switch (SPR.NaNBehavior) {
3764       case SPNB_NA: llvm_unreachable("No NaN behavior for FP op?");
3765       case SPNB_RETURNS_NAN: break;
3766       case SPNB_RETURNS_OTHER: Opc = ISD::FMAXNUM; break;
3767       case SPNB_RETURNS_ANY:
3768         if (TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT) ||
3769             (UseScalarMinMax &&
3770              TLI.isOperationLegalOrCustom(ISD::FMAXNUM, VT.getScalarType())))
3771           Opc = ISD::FMAXNUM;
3772         break;
3773       }
3774       break;
3775     case SPF_NABS:
3776       Negate = true;
3777       [[fallthrough]];
3778     case SPF_ABS:
3779       IsUnaryAbs = true;
3780       Opc = ISD::ABS;
3781       break;
3782     default: break;
3783     }
3784 
3785     if (!IsUnaryAbs && Opc != ISD::DELETED_NODE &&
3786         (TLI.isOperationLegalOrCustom(Opc, VT) ||
3787          (UseScalarMinMax &&
3788           TLI.isOperationLegalOrCustom(Opc, VT.getScalarType()))) &&
3789         // If the underlying comparison instruction is used by any other
3790         // instruction, the consumed instructions won't be destroyed, so it is
3791         // not profitable to convert to a min/max.
3792         hasOnlySelectUsers(cast<SelectInst>(I).getCondition())) {
3793       OpCode = Opc;
3794       LHSVal = getValue(LHS);
3795       RHSVal = getValue(RHS);
3796       BaseOps.clear();
3797     }
3798 
3799     if (IsUnaryAbs) {
3800       OpCode = Opc;
3801       LHSVal = getValue(LHS);
3802       BaseOps.clear();
3803     }
3804   }
3805 
3806   if (IsUnaryAbs) {
3807     for (unsigned i = 0; i != NumValues; ++i) {
3808       SDLoc dl = getCurSDLoc();
3809       EVT VT = LHSVal.getNode()->getValueType(LHSVal.getResNo() + i);
3810       Values[i] =
3811           DAG.getNode(OpCode, dl, VT, LHSVal.getValue(LHSVal.getResNo() + i));
3812       if (Negate)
3813         Values[i] = DAG.getNegative(Values[i], dl, VT);
3814     }
3815   } else {
3816     for (unsigned i = 0; i != NumValues; ++i) {
3817       SmallVector<SDValue, 3> Ops(BaseOps.begin(), BaseOps.end());
3818       Ops.push_back(SDValue(LHSVal.getNode(), LHSVal.getResNo() + i));
3819       Ops.push_back(SDValue(RHSVal.getNode(), RHSVal.getResNo() + i));
3820       Values[i] = DAG.getNode(
3821           OpCode, getCurSDLoc(),
3822           LHSVal.getNode()->getValueType(LHSVal.getResNo() + i), Ops, Flags);
3823     }
3824   }
3825 
3826   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
3827                            DAG.getVTList(ValueVTs), Values));
3828 }
3829 
3830 void SelectionDAGBuilder::visitTrunc(const User &I) {
3831   // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
3832   SDValue N = getValue(I.getOperand(0));
3833   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3834                                                         I.getType());
3835   SDNodeFlags Flags;
3836   if (auto *Trunc = dyn_cast<TruncInst>(&I)) {
3837     Flags.setNoSignedWrap(Trunc->hasNoSignedWrap());
3838     Flags.setNoUnsignedWrap(Trunc->hasNoUnsignedWrap());
3839   }
3840 
3841   setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), DestVT, N, Flags));
3842 }
3843 
3844 void SelectionDAGBuilder::visitZExt(const User &I) {
3845   // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3846   // ZExt also can't be a cast to bool for same reason. So, nothing much to do
3847   SDValue N = getValue(I.getOperand(0));
3848   auto &TLI = DAG.getTargetLoweringInfo();
3849   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3850 
3851   SDNodeFlags Flags;
3852   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3853     Flags.setNonNeg(PNI->hasNonNeg());
3854 
3855   // Eagerly use nonneg information to canonicalize towards sign_extend if
3856   // that is the target's preference.
3857   // TODO: Let the target do this later.
3858   if (Flags.hasNonNeg() &&
3859       TLI.isSExtCheaperThanZExt(N.getValueType(), DestVT)) {
3860     setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3861     return;
3862   }
3863 
3864   setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurSDLoc(), DestVT, N, Flags));
3865 }
3866 
3867 void SelectionDAGBuilder::visitSExt(const User &I) {
3868   // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
3869   // SExt also can't be a cast to bool for same reason. So, nothing much to do
3870   SDValue N = getValue(I.getOperand(0));
3871   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3872                                                         I.getType());
3873   setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurSDLoc(), DestVT, N));
3874 }
3875 
3876 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
3877   // FPTrunc is never a no-op cast, no need to check
3878   SDValue N = getValue(I.getOperand(0));
3879   SDLoc dl = getCurSDLoc();
3880   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3881   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3882   setValue(&I, DAG.getNode(ISD::FP_ROUND, dl, DestVT, N,
3883                            DAG.getTargetConstant(
3884                                0, dl, TLI.getPointerTy(DAG.getDataLayout()))));
3885 }
3886 
3887 void SelectionDAGBuilder::visitFPExt(const User &I) {
3888   // FPExt is never a no-op cast, no need to check
3889   SDValue N = getValue(I.getOperand(0));
3890   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3891                                                         I.getType());
3892   setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurSDLoc(), DestVT, N));
3893 }
3894 
3895 void SelectionDAGBuilder::visitFPToUI(const User &I) {
3896   // FPToUI is never a no-op cast, no need to check
3897   SDValue N = getValue(I.getOperand(0));
3898   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3899                                                         I.getType());
3900   setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurSDLoc(), DestVT, N));
3901 }
3902 
3903 void SelectionDAGBuilder::visitFPToSI(const User &I) {
3904   // FPToSI is never a no-op cast, no need to check
3905   SDValue N = getValue(I.getOperand(0));
3906   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3907                                                         I.getType());
3908   setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurSDLoc(), DestVT, N));
3909 }
3910 
3911 void SelectionDAGBuilder::visitUIToFP(const User &I) {
3912   // UIToFP is never a no-op cast, no need to check
3913   SDValue N = getValue(I.getOperand(0));
3914   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3915                                                         I.getType());
3916   SDNodeFlags Flags;
3917   if (auto *PNI = dyn_cast<PossiblyNonNegInst>(&I))
3918     Flags.setNonNeg(PNI->hasNonNeg());
3919 
3920   setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurSDLoc(), DestVT, N, Flags));
3921 }
3922 
3923 void SelectionDAGBuilder::visitSIToFP(const User &I) {
3924   // SIToFP is never a no-op cast, no need to check
3925   SDValue N = getValue(I.getOperand(0));
3926   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3927                                                         I.getType());
3928   setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurSDLoc(), DestVT, N));
3929 }
3930 
3931 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
3932   // What to do depends on the size of the integer and the size of the pointer.
3933   // We can either truncate, zero extend, or no-op, accordingly.
3934   SDValue N = getValue(I.getOperand(0));
3935   auto &TLI = DAG.getTargetLoweringInfo();
3936   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3937                                                         I.getType());
3938   EVT PtrMemVT =
3939       TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
3940   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3941   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), DestVT);
3942   setValue(&I, N);
3943 }
3944 
3945 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
3946   // What to do depends on the size of the integer and the size of the pointer.
3947   // We can either truncate, zero extend, or no-op, accordingly.
3948   SDValue N = getValue(I.getOperand(0));
3949   auto &TLI = DAG.getTargetLoweringInfo();
3950   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3951   EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
3952   N = DAG.getZExtOrTrunc(N, getCurSDLoc(), PtrMemVT);
3953   N = DAG.getPtrExtOrTrunc(N, getCurSDLoc(), DestVT);
3954   setValue(&I, N);
3955 }
3956 
3957 void SelectionDAGBuilder::visitBitCast(const User &I) {
3958   SDValue N = getValue(I.getOperand(0));
3959   SDLoc dl = getCurSDLoc();
3960   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
3961                                                         I.getType());
3962 
3963   // BitCast assures us that source and destination are the same size so this is
3964   // either a BITCAST or a no-op.
3965   if (DestVT != N.getValueType())
3966     setValue(&I, DAG.getNode(ISD::BITCAST, dl,
3967                              DestVT, N)); // convert types.
3968   // Check if the original LLVM IR Operand was a ConstantInt, because getValue()
3969   // might fold any kind of constant expression to an integer constant and that
3970   // is not what we are looking for. Only recognize a bitcast of a genuine
3971   // constant integer as an opaque constant.
3972   else if(ConstantInt *C = dyn_cast<ConstantInt>(I.getOperand(0)))
3973     setValue(&I, DAG.getConstant(C->getValue(), dl, DestVT, /*isTarget=*/false,
3974                                  /*isOpaque*/true));
3975   else
3976     setValue(&I, N);            // noop cast.
3977 }
3978 
3979 void SelectionDAGBuilder::visitAddrSpaceCast(const User &I) {
3980   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3981   const Value *SV = I.getOperand(0);
3982   SDValue N = getValue(SV);
3983   EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
3984 
3985   unsigned SrcAS = SV->getType()->getPointerAddressSpace();
3986   unsigned DestAS = I.getType()->getPointerAddressSpace();
3987 
3988   if (!TM.isNoopAddrSpaceCast(SrcAS, DestAS))
3989     N = DAG.getAddrSpaceCast(getCurSDLoc(), DestVT, N, SrcAS, DestAS);
3990 
3991   setValue(&I, N);
3992 }
3993 
3994 void SelectionDAGBuilder::visitInsertElement(const User &I) {
3995   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3996   SDValue InVec = getValue(I.getOperand(0));
3997   SDValue InVal = getValue(I.getOperand(1));
3998   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(2)), getCurSDLoc(),
3999                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
4000   setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurSDLoc(),
4001                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
4002                            InVec, InVal, InIdx));
4003 }
4004 
4005 void SelectionDAGBuilder::visitExtractElement(const User &I) {
4006   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4007   SDValue InVec = getValue(I.getOperand(0));
4008   SDValue InIdx = DAG.getZExtOrTrunc(getValue(I.getOperand(1)), getCurSDLoc(),
4009                                      TLI.getVectorIdxTy(DAG.getDataLayout()));
4010   setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurSDLoc(),
4011                            TLI.getValueType(DAG.getDataLayout(), I.getType()),
4012                            InVec, InIdx));
4013 }
4014 
4015 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
4016   SDValue Src1 = getValue(I.getOperand(0));
4017   SDValue Src2 = getValue(I.getOperand(1));
4018   ArrayRef<int> Mask;
4019   if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I))
4020     Mask = SVI->getShuffleMask();
4021   else
4022     Mask = cast<ConstantExpr>(I).getShuffleMask();
4023   SDLoc DL = getCurSDLoc();
4024   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4025   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
4026   EVT SrcVT = Src1.getValueType();
4027 
4028   if (all_of(Mask, [](int Elem) { return Elem == 0; }) &&
4029       VT.isScalableVector()) {
4030     // Canonical splat form of first element of first input vector.
4031     SDValue FirstElt =
4032         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, SrcVT.getScalarType(), Src1,
4033                     DAG.getVectorIdxConstant(0, DL));
4034     setValue(&I, DAG.getNode(ISD::SPLAT_VECTOR, DL, VT, FirstElt));
4035     return;
4036   }
4037 
4038   // For now, we only handle splats for scalable vectors.
4039   // The DAGCombiner will perform a BUILD_VECTOR -> SPLAT_VECTOR transformation
4040   // for targets that support a SPLAT_VECTOR for non-scalable vector types.
4041   assert(!VT.isScalableVector() && "Unsupported scalable vector shuffle");
4042 
4043   unsigned SrcNumElts = SrcVT.getVectorNumElements();
4044   unsigned MaskNumElts = Mask.size();
4045 
4046   if (SrcNumElts == MaskNumElts) {
4047     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, Mask));
4048     return;
4049   }
4050 
4051   // Normalize the shuffle vector since mask and vector length don't match.
4052   if (SrcNumElts < MaskNumElts) {
4053     // Mask is longer than the source vectors. We can use concatenate vector to
4054     // make the mask and vectors lengths match.
4055 
4056     if (MaskNumElts % SrcNumElts == 0) {
4057       // Mask length is a multiple of the source vector length.
4058       // Check if the shuffle is some kind of concatenation of the input
4059       // vectors.
4060       unsigned NumConcat = MaskNumElts / SrcNumElts;
4061       bool IsConcat = true;
4062       SmallVector<int, 8> ConcatSrcs(NumConcat, -1);
4063       for (unsigned i = 0; i != MaskNumElts; ++i) {
4064         int Idx = Mask[i];
4065         if (Idx < 0)
4066           continue;
4067         // Ensure the indices in each SrcVT sized piece are sequential and that
4068         // the same source is used for the whole piece.
4069         if ((Idx % SrcNumElts != (i % SrcNumElts)) ||
4070             (ConcatSrcs[i / SrcNumElts] >= 0 &&
4071              ConcatSrcs[i / SrcNumElts] != (int)(Idx / SrcNumElts))) {
4072           IsConcat = false;
4073           break;
4074         }
4075         // Remember which source this index came from.
4076         ConcatSrcs[i / SrcNumElts] = Idx / SrcNumElts;
4077       }
4078 
4079       // The shuffle is concatenating multiple vectors together. Just emit
4080       // a CONCAT_VECTORS operation.
4081       if (IsConcat) {
4082         SmallVector<SDValue, 8> ConcatOps;
4083         for (auto Src : ConcatSrcs) {
4084           if (Src < 0)
4085             ConcatOps.push_back(DAG.getUNDEF(SrcVT));
4086           else if (Src == 0)
4087             ConcatOps.push_back(Src1);
4088           else
4089             ConcatOps.push_back(Src2);
4090         }
4091         setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps));
4092         return;
4093       }
4094     }
4095 
4096     unsigned PaddedMaskNumElts = alignTo(MaskNumElts, SrcNumElts);
4097     unsigned NumConcat = PaddedMaskNumElts / SrcNumElts;
4098     EVT PaddedVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
4099                                     PaddedMaskNumElts);
4100 
4101     // Pad both vectors with undefs to make them the same length as the mask.
4102     SDValue UndefVal = DAG.getUNDEF(SrcVT);
4103 
4104     SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
4105     SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
4106     MOps1[0] = Src1;
4107     MOps2[0] = Src2;
4108 
4109     Src1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps1);
4110     Src2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, PaddedVT, MOps2);
4111 
4112     // Readjust mask for new input vector length.
4113     SmallVector<int, 8> MappedOps(PaddedMaskNumElts, -1);
4114     for (unsigned i = 0; i != MaskNumElts; ++i) {
4115       int Idx = Mask[i];
4116       if (Idx >= (int)SrcNumElts)
4117         Idx -= SrcNumElts - PaddedMaskNumElts;
4118       MappedOps[i] = Idx;
4119     }
4120 
4121     SDValue Result = DAG.getVectorShuffle(PaddedVT, DL, Src1, Src2, MappedOps);
4122 
4123     // If the concatenated vector was padded, extract a subvector with the
4124     // correct number of elements.
4125     if (MaskNumElts != PaddedMaskNumElts)
4126       Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Result,
4127                            DAG.getVectorIdxConstant(0, DL));
4128 
4129     setValue(&I, Result);
4130     return;
4131   }
4132 
4133   assert(SrcNumElts > MaskNumElts);
4134 
4135   // Analyze the access pattern of the vector to see if we can extract
4136   // two subvectors and do the shuffle.
4137   int StartIdx[2] = {-1, -1}; // StartIdx to extract from
4138   bool CanExtract = true;
4139   for (int Idx : Mask) {
4140     unsigned Input = 0;
4141     if (Idx < 0)
4142       continue;
4143 
4144     if (Idx >= (int)SrcNumElts) {
4145       Input = 1;
4146       Idx -= SrcNumElts;
4147     }
4148 
4149     // If all the indices come from the same MaskNumElts sized portion of
4150     // the sources we can use extract. Also make sure the extract wouldn't
4151     // extract past the end of the source.
4152     int NewStartIdx = alignDown(Idx, MaskNumElts);
4153     if (NewStartIdx + MaskNumElts > SrcNumElts ||
4154         (StartIdx[Input] >= 0 && StartIdx[Input] != NewStartIdx))
4155       CanExtract = false;
4156     // Make sure we always update StartIdx as we use it to track if all
4157     // elements are undef.
4158     StartIdx[Input] = NewStartIdx;
4159   }
4160 
4161   if (StartIdx[0] < 0 && StartIdx[1] < 0) {
4162     setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
4163     return;
4164   }
4165   if (CanExtract) {
4166     // Extract appropriate subvector and generate a vector shuffle
4167     for (unsigned Input = 0; Input < 2; ++Input) {
4168       SDValue &Src = Input == 0 ? Src1 : Src2;
4169       if (StartIdx[Input] < 0)
4170         Src = DAG.getUNDEF(VT);
4171       else {
4172         Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Src,
4173                           DAG.getVectorIdxConstant(StartIdx[Input], DL));
4174       }
4175     }
4176 
4177     // Calculate new mask.
4178     SmallVector<int, 8> MappedOps(Mask);
4179     for (int &Idx : MappedOps) {
4180       if (Idx >= (int)SrcNumElts)
4181         Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
4182       else if (Idx >= 0)
4183         Idx -= StartIdx[0];
4184     }
4185 
4186     setValue(&I, DAG.getVectorShuffle(VT, DL, Src1, Src2, MappedOps));
4187     return;
4188   }
4189 
4190   // We can't use either concat vectors or extract subvectors so fall back to
4191   // replacing the shuffle with extract and build vector.
4192   // to insert and build vector.
4193   EVT EltVT = VT.getVectorElementType();
4194   SmallVector<SDValue,8> Ops;
4195   for (int Idx : Mask) {
4196     SDValue Res;
4197 
4198     if (Idx < 0) {
4199       Res = DAG.getUNDEF(EltVT);
4200     } else {
4201       SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
4202       if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
4203 
4204       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src,
4205                         DAG.getVectorIdxConstant(Idx, DL));
4206     }
4207 
4208     Ops.push_back(Res);
4209   }
4210 
4211   setValue(&I, DAG.getBuildVector(VT, DL, Ops));
4212 }
4213 
4214 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
4215   ArrayRef<unsigned> Indices = I.getIndices();
4216   const Value *Op0 = I.getOperand(0);
4217   const Value *Op1 = I.getOperand(1);
4218   Type *AggTy = I.getType();
4219   Type *ValTy = Op1->getType();
4220   bool IntoUndef = isa<UndefValue>(Op0);
4221   bool FromUndef = isa<UndefValue>(Op1);
4222 
4223   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4224 
4225   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4226   SmallVector<EVT, 4> AggValueVTs;
4227   ComputeValueVTs(TLI, DAG.getDataLayout(), AggTy, AggValueVTs);
4228   SmallVector<EVT, 4> ValValueVTs;
4229   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4230 
4231   unsigned NumAggValues = AggValueVTs.size();
4232   unsigned NumValValues = ValValueVTs.size();
4233   SmallVector<SDValue, 4> Values(NumAggValues);
4234 
4235   // Ignore an insertvalue that produces an empty object
4236   if (!NumAggValues) {
4237     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4238     return;
4239   }
4240 
4241   SDValue Agg = getValue(Op0);
4242   unsigned i = 0;
4243   // Copy the beginning value(s) from the original aggregate.
4244   for (; i != LinearIndex; ++i)
4245     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4246                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4247   // Copy values from the inserted value(s).
4248   if (NumValValues) {
4249     SDValue Val = getValue(Op1);
4250     for (; i != LinearIndex + NumValValues; ++i)
4251       Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4252                   SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
4253   }
4254   // Copy remaining value(s) from the original aggregate.
4255   for (; i != NumAggValues; ++i)
4256     Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
4257                 SDValue(Agg.getNode(), Agg.getResNo() + i);
4258 
4259   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4260                            DAG.getVTList(AggValueVTs), Values));
4261 }
4262 
4263 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
4264   ArrayRef<unsigned> Indices = I.getIndices();
4265   const Value *Op0 = I.getOperand(0);
4266   Type *AggTy = Op0->getType();
4267   Type *ValTy = I.getType();
4268   bool OutOfUndef = isa<UndefValue>(Op0);
4269 
4270   unsigned LinearIndex = ComputeLinearIndex(AggTy, Indices);
4271 
4272   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4273   SmallVector<EVT, 4> ValValueVTs;
4274   ComputeValueVTs(TLI, DAG.getDataLayout(), ValTy, ValValueVTs);
4275 
4276   unsigned NumValValues = ValValueVTs.size();
4277 
4278   // Ignore a extractvalue that produces an empty object
4279   if (!NumValValues) {
4280     setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
4281     return;
4282   }
4283 
4284   SmallVector<SDValue, 4> Values(NumValValues);
4285 
4286   SDValue Agg = getValue(Op0);
4287   // Copy out the selected value(s).
4288   for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
4289     Values[i - LinearIndex] =
4290       OutOfUndef ?
4291         DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
4292         SDValue(Agg.getNode(), Agg.getResNo() + i);
4293 
4294   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
4295                            DAG.getVTList(ValValueVTs), Values));
4296 }
4297 
4298 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
4299   Value *Op0 = I.getOperand(0);
4300   // Note that the pointer operand may be a vector of pointers. Take the scalar
4301   // element which holds a pointer.
4302   unsigned AS = Op0->getType()->getScalarType()->getPointerAddressSpace();
4303   SDValue N = getValue(Op0);
4304   SDLoc dl = getCurSDLoc();
4305   auto &TLI = DAG.getTargetLoweringInfo();
4306   GEPNoWrapFlags NW = cast<GEPOperator>(I).getNoWrapFlags();
4307 
4308   // Normalize Vector GEP - all scalar operands should be converted to the
4309   // splat vector.
4310   bool IsVectorGEP = I.getType()->isVectorTy();
4311   ElementCount VectorElementCount =
4312       IsVectorGEP ? cast<VectorType>(I.getType())->getElementCount()
4313                   : ElementCount::getFixed(0);
4314 
4315   if (IsVectorGEP && !N.getValueType().isVector()) {
4316     LLVMContext &Context = *DAG.getContext();
4317     EVT VT = EVT::getVectorVT(Context, N.getValueType(), VectorElementCount);
4318     N = DAG.getSplat(VT, dl, N);
4319   }
4320 
4321   for (gep_type_iterator GTI = gep_type_begin(&I), E = gep_type_end(&I);
4322        GTI != E; ++GTI) {
4323     const Value *Idx = GTI.getOperand();
4324     if (StructType *StTy = GTI.getStructTypeOrNull()) {
4325       unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
4326       if (Field) {
4327         // N = N + Offset
4328         uint64_t Offset =
4329             DAG.getDataLayout().getStructLayout(StTy)->getElementOffset(Field);
4330 
4331         // In an inbounds GEP with an offset that is nonnegative even when
4332         // interpreted as signed, assume there is no unsigned overflow.
4333         SDNodeFlags Flags;
4334         if (NW.hasNoUnsignedWrap() ||
4335             (int64_t(Offset) >= 0 && NW.hasNoUnsignedSignedWrap()))
4336           Flags |= SDNodeFlags::NoUnsignedWrap;
4337 
4338         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N,
4339                         DAG.getConstant(Offset, dl, N.getValueType()), Flags);
4340       }
4341     } else {
4342       // IdxSize is the width of the arithmetic according to IR semantics.
4343       // In SelectionDAG, we may prefer to do arithmetic in a wider bitwidth
4344       // (and fix up the result later).
4345       unsigned IdxSize = DAG.getDataLayout().getIndexSizeInBits(AS);
4346       MVT IdxTy = MVT::getIntegerVT(IdxSize);
4347       TypeSize ElementSize =
4348           GTI.getSequentialElementStride(DAG.getDataLayout());
4349       // We intentionally mask away the high bits here; ElementSize may not
4350       // fit in IdxTy.
4351       APInt ElementMul(IdxSize, ElementSize.getKnownMinValue(),
4352                        /*isSigned=*/false, /*implicitTrunc=*/true);
4353       bool ElementScalable = ElementSize.isScalable();
4354 
4355       // If this is a scalar constant or a splat vector of constants,
4356       // handle it quickly.
4357       const auto *C = dyn_cast<Constant>(Idx);
4358       if (C && isa<VectorType>(C->getType()))
4359         C = C->getSplatValue();
4360 
4361       const auto *CI = dyn_cast_or_null<ConstantInt>(C);
4362       if (CI && CI->isZero())
4363         continue;
4364       if (CI && !ElementScalable) {
4365         APInt Offs = ElementMul * CI->getValue().sextOrTrunc(IdxSize);
4366         LLVMContext &Context = *DAG.getContext();
4367         SDValue OffsVal;
4368         if (IsVectorGEP)
4369           OffsVal = DAG.getConstant(
4370               Offs, dl, EVT::getVectorVT(Context, IdxTy, VectorElementCount));
4371         else
4372           OffsVal = DAG.getConstant(Offs, dl, IdxTy);
4373 
4374         // In an inbounds GEP with an offset that is nonnegative even when
4375         // interpreted as signed, assume there is no unsigned overflow.
4376         SDNodeFlags Flags;
4377         if (NW.hasNoUnsignedWrap() ||
4378             (Offs.isNonNegative() && NW.hasNoUnsignedSignedWrap()))
4379           Flags.setNoUnsignedWrap(true);
4380 
4381         OffsVal = DAG.getSExtOrTrunc(OffsVal, dl, N.getValueType());
4382 
4383         N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, OffsVal, Flags);
4384         continue;
4385       }
4386 
4387       // N = N + Idx * ElementMul;
4388       SDValue IdxN = getValue(Idx);
4389 
4390       if (!IdxN.getValueType().isVector() && IsVectorGEP) {
4391         EVT VT = EVT::getVectorVT(*Context, IdxN.getValueType(),
4392                                   VectorElementCount);
4393         IdxN = DAG.getSplat(VT, dl, IdxN);
4394       }
4395 
4396       // If the index is smaller or larger than intptr_t, truncate or extend
4397       // it.
4398       IdxN = DAG.getSExtOrTrunc(IdxN, dl, N.getValueType());
4399 
4400       SDNodeFlags ScaleFlags;
4401       // The multiplication of an index by the type size does not wrap the
4402       // pointer index type in a signed sense (mul nsw).
4403       ScaleFlags.setNoSignedWrap(NW.hasNoUnsignedSignedWrap());
4404 
4405       // The multiplication of an index by the type size does not wrap the
4406       // pointer index type in an unsigned sense (mul nuw).
4407       ScaleFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4408 
4409       if (ElementScalable) {
4410         EVT VScaleTy = N.getValueType().getScalarType();
4411         SDValue VScale = DAG.getNode(
4412             ISD::VSCALE, dl, VScaleTy,
4413             DAG.getConstant(ElementMul.getZExtValue(), dl, VScaleTy));
4414         if (IsVectorGEP)
4415           VScale = DAG.getSplatVector(N.getValueType(), dl, VScale);
4416         IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, VScale,
4417                            ScaleFlags);
4418       } else {
4419         // If this is a multiply by a power of two, turn it into a shl
4420         // immediately.  This is a very common case.
4421         if (ElementMul != 1) {
4422           if (ElementMul.isPowerOf2()) {
4423             unsigned Amt = ElementMul.logBase2();
4424             IdxN = DAG.getNode(ISD::SHL, dl, N.getValueType(), IdxN,
4425                                DAG.getConstant(Amt, dl, IdxN.getValueType()),
4426                                ScaleFlags);
4427           } else {
4428             SDValue Scale = DAG.getConstant(ElementMul.getZExtValue(), dl,
4429                                             IdxN.getValueType());
4430             IdxN = DAG.getNode(ISD::MUL, dl, N.getValueType(), IdxN, Scale,
4431                                ScaleFlags);
4432           }
4433         }
4434       }
4435 
4436       // The successive addition of the current address, truncated to the
4437       // pointer index type and interpreted as an unsigned number, and each
4438       // offset, also interpreted as an unsigned number, does not wrap the
4439       // pointer index type (add nuw).
4440       SDNodeFlags AddFlags;
4441       AddFlags.setNoUnsignedWrap(NW.hasNoUnsignedWrap());
4442 
4443       N = DAG.getNode(ISD::ADD, dl, N.getValueType(), N, IdxN, AddFlags);
4444     }
4445   }
4446 
4447   MVT PtrTy = TLI.getPointerTy(DAG.getDataLayout(), AS);
4448   MVT PtrMemTy = TLI.getPointerMemTy(DAG.getDataLayout(), AS);
4449   if (IsVectorGEP) {
4450     PtrTy = MVT::getVectorVT(PtrTy, VectorElementCount);
4451     PtrMemTy = MVT::getVectorVT(PtrMemTy, VectorElementCount);
4452   }
4453 
4454   if (PtrMemTy != PtrTy && !cast<GEPOperator>(I).isInBounds())
4455     N = DAG.getPtrExtendInReg(N, dl, PtrMemTy);
4456 
4457   setValue(&I, N);
4458 }
4459 
4460 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
4461   // If this is a fixed sized alloca in the entry block of the function,
4462   // allocate it statically on the stack.
4463   if (FuncInfo.StaticAllocaMap.count(&I))
4464     return;   // getValue will auto-populate this.
4465 
4466   SDLoc dl = getCurSDLoc();
4467   Type *Ty = I.getAllocatedType();
4468   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4469   auto &DL = DAG.getDataLayout();
4470   TypeSize TySize = DL.getTypeAllocSize(Ty);
4471   MaybeAlign Alignment = std::max(DL.getPrefTypeAlign(Ty), I.getAlign());
4472 
4473   SDValue AllocSize = getValue(I.getArraySize());
4474 
4475   EVT IntPtr = TLI.getPointerTy(DL, I.getAddressSpace());
4476   if (AllocSize.getValueType() != IntPtr)
4477     AllocSize = DAG.getZExtOrTrunc(AllocSize, dl, IntPtr);
4478 
4479   if (TySize.isScalable())
4480     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4481                             DAG.getVScale(dl, IntPtr,
4482                                           APInt(IntPtr.getScalarSizeInBits(),
4483                                                 TySize.getKnownMinValue())));
4484   else {
4485     SDValue TySizeValue =
4486         DAG.getConstant(TySize.getFixedValue(), dl, MVT::getIntegerVT(64));
4487     AllocSize = DAG.getNode(ISD::MUL, dl, IntPtr, AllocSize,
4488                             DAG.getZExtOrTrunc(TySizeValue, dl, IntPtr));
4489   }
4490 
4491   // Handle alignment.  If the requested alignment is less than or equal to
4492   // the stack alignment, ignore it.  If the size is greater than or equal to
4493   // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
4494   Align StackAlign = DAG.getSubtarget().getFrameLowering()->getStackAlign();
4495   if (*Alignment <= StackAlign)
4496     Alignment = std::nullopt;
4497 
4498   const uint64_t StackAlignMask = StackAlign.value() - 1U;
4499   // Round the size of the allocation up to the stack alignment size
4500   // by add SA-1 to the size. This doesn't overflow because we're computing
4501   // an address inside an alloca.
4502   AllocSize = DAG.getNode(ISD::ADD, dl, AllocSize.getValueType(), AllocSize,
4503                           DAG.getConstant(StackAlignMask, dl, IntPtr),
4504                           SDNodeFlags::NoUnsignedWrap);
4505 
4506   // Mask out the low bits for alignment purposes.
4507   AllocSize = DAG.getNode(ISD::AND, dl, AllocSize.getValueType(), AllocSize,
4508                           DAG.getSignedConstant(~StackAlignMask, dl, IntPtr));
4509 
4510   SDValue Ops[] = {
4511       getRoot(), AllocSize,
4512       DAG.getConstant(Alignment ? Alignment->value() : 0, dl, IntPtr)};
4513   SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
4514   SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, dl, VTs, Ops);
4515   setValue(&I, DSA);
4516   DAG.setRoot(DSA.getValue(1));
4517 
4518   assert(FuncInfo.MF->getFrameInfo().hasVarSizedObjects());
4519 }
4520 
4521 static const MDNode *getRangeMetadata(const Instruction &I) {
4522   // If !noundef is not present, then !range violation results in a poison
4523   // value rather than immediate undefined behavior. In theory, transferring
4524   // these annotations to SDAG is fine, but in practice there are key SDAG
4525   // transforms that are known not to be poison-safe, such as folding logical
4526   // and/or to bitwise and/or. For now, only transfer !range if !noundef is
4527   // also present.
4528   if (!I.hasMetadata(LLVMContext::MD_noundef))
4529     return nullptr;
4530   return I.getMetadata(LLVMContext::MD_range);
4531 }
4532 
4533 static std::optional<ConstantRange> getRange(const Instruction &I) {
4534   if (const auto *CB = dyn_cast<CallBase>(&I)) {
4535     // see comment in getRangeMetadata about this check
4536     if (CB->hasRetAttr(Attribute::NoUndef))
4537       return CB->getRange();
4538   }
4539   if (const MDNode *Range = getRangeMetadata(I))
4540     return getConstantRangeFromMetadata(*Range);
4541   return std::nullopt;
4542 }
4543 
4544 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
4545   if (I.isAtomic())
4546     return visitAtomicLoad(I);
4547 
4548   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4549   const Value *SV = I.getOperand(0);
4550   if (TLI.supportSwiftError()) {
4551     // Swifterror values can come from either a function parameter with
4552     // swifterror attribute or an alloca with swifterror attribute.
4553     if (const Argument *Arg = dyn_cast<Argument>(SV)) {
4554       if (Arg->hasSwiftErrorAttr())
4555         return visitLoadFromSwiftError(I);
4556     }
4557 
4558     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
4559       if (Alloca->isSwiftError())
4560         return visitLoadFromSwiftError(I);
4561     }
4562   }
4563 
4564   SDValue Ptr = getValue(SV);
4565 
4566   Type *Ty = I.getType();
4567   SmallVector<EVT, 4> ValueVTs, MemVTs;
4568   SmallVector<TypeSize, 4> Offsets;
4569   ComputeValueVTs(TLI, DAG.getDataLayout(), Ty, ValueVTs, &MemVTs, &Offsets);
4570   unsigned NumValues = ValueVTs.size();
4571   if (NumValues == 0)
4572     return;
4573 
4574   Align Alignment = I.getAlign();
4575   AAMDNodes AAInfo = I.getAAMetadata();
4576   const MDNode *Ranges = getRangeMetadata(I);
4577   bool isVolatile = I.isVolatile();
4578   MachineMemOperand::Flags MMOFlags =
4579       TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
4580 
4581   SDValue Root;
4582   bool ConstantMemory = false;
4583   if (isVolatile)
4584     // Serialize volatile loads with other side effects.
4585     Root = getRoot();
4586   else if (NumValues > MaxParallelChains)
4587     Root = getMemoryRoot();
4588   else if (BatchAA &&
4589            BatchAA->pointsToConstantMemory(MemoryLocation(
4590                SV,
4591                LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4592                AAInfo))) {
4593     // Do not serialize (non-volatile) loads of constant memory with anything.
4594     Root = DAG.getEntryNode();
4595     ConstantMemory = true;
4596     MMOFlags |= MachineMemOperand::MOInvariant;
4597   } else {
4598     // Do not serialize non-volatile loads against each other.
4599     Root = DAG.getRoot();
4600   }
4601 
4602   SDLoc dl = getCurSDLoc();
4603 
4604   if (isVolatile)
4605     Root = TLI.prepareVolatileOrAtomicLoad(Root, dl, DAG);
4606 
4607   SmallVector<SDValue, 4> Values(NumValues);
4608   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4609 
4610   unsigned ChainI = 0;
4611   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4612     // Serializing loads here may result in excessive register pressure, and
4613     // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
4614     // could recover a bit by hoisting nodes upward in the chain by recognizing
4615     // they are side-effect free or do not alias. The optimizer should really
4616     // avoid this case by converting large object/array copies to llvm.memcpy
4617     // (MaxParallelChains should always remain as failsafe).
4618     if (ChainI == MaxParallelChains) {
4619       assert(PendingLoads.empty() && "PendingLoads must be serialized first");
4620       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4621                                   ArrayRef(Chains.data(), ChainI));
4622       Root = Chain;
4623       ChainI = 0;
4624     }
4625 
4626     // TODO: MachinePointerInfo only supports a fixed length offset.
4627     MachinePointerInfo PtrInfo =
4628         !Offsets[i].isScalable() || Offsets[i].isZero()
4629             ? MachinePointerInfo(SV, Offsets[i].getKnownMinValue())
4630             : MachinePointerInfo();
4631 
4632     SDValue A = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4633     SDValue L = DAG.getLoad(MemVTs[i], dl, Root, A, PtrInfo, Alignment,
4634                             MMOFlags, AAInfo, Ranges);
4635     Chains[ChainI] = L.getValue(1);
4636 
4637     if (MemVTs[i] != ValueVTs[i])
4638       L = DAG.getPtrExtOrTrunc(L, dl, ValueVTs[i]);
4639 
4640     Values[i] = L;
4641   }
4642 
4643   if (!ConstantMemory) {
4644     SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4645                                 ArrayRef(Chains.data(), ChainI));
4646     if (isVolatile)
4647       DAG.setRoot(Chain);
4648     else
4649       PendingLoads.push_back(Chain);
4650   }
4651 
4652   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, dl,
4653                            DAG.getVTList(ValueVTs), Values));
4654 }
4655 
4656 void SelectionDAGBuilder::visitStoreToSwiftError(const StoreInst &I) {
4657   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4658          "call visitStoreToSwiftError when backend supports swifterror");
4659 
4660   SmallVector<EVT, 4> ValueVTs;
4661   SmallVector<uint64_t, 4> Offsets;
4662   const Value *SrcV = I.getOperand(0);
4663   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4664                   SrcV->getType(), ValueVTs, &Offsets, 0);
4665   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4666          "expect a single EVT for swifterror");
4667 
4668   SDValue Src = getValue(SrcV);
4669   // Create a virtual register, then update the virtual register.
4670   Register VReg =
4671       SwiftError.getOrCreateVRegDefAt(&I, FuncInfo.MBB, I.getPointerOperand());
4672   // Chain, DL, Reg, N or Chain, DL, Reg, N, Glue
4673   // Chain can be getRoot or getControlRoot.
4674   SDValue CopyNode = DAG.getCopyToReg(getRoot(), getCurSDLoc(), VReg,
4675                                       SDValue(Src.getNode(), Src.getResNo()));
4676   DAG.setRoot(CopyNode);
4677 }
4678 
4679 void SelectionDAGBuilder::visitLoadFromSwiftError(const LoadInst &I) {
4680   assert(DAG.getTargetLoweringInfo().supportSwiftError() &&
4681          "call visitLoadFromSwiftError when backend supports swifterror");
4682 
4683   assert(!I.isVolatile() &&
4684          !I.hasMetadata(LLVMContext::MD_nontemporal) &&
4685          !I.hasMetadata(LLVMContext::MD_invariant_load) &&
4686          "Support volatile, non temporal, invariant for load_from_swift_error");
4687 
4688   const Value *SV = I.getOperand(0);
4689   Type *Ty = I.getType();
4690   assert(
4691       (!BatchAA ||
4692        !BatchAA->pointsToConstantMemory(MemoryLocation(
4693            SV, LocationSize::precise(DAG.getDataLayout().getTypeStoreSize(Ty)),
4694            I.getAAMetadata()))) &&
4695       "load_from_swift_error should not be constant memory");
4696 
4697   SmallVector<EVT, 4> ValueVTs;
4698   SmallVector<uint64_t, 4> Offsets;
4699   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), Ty,
4700                   ValueVTs, &Offsets, 0);
4701   assert(ValueVTs.size() == 1 && Offsets[0] == 0 &&
4702          "expect a single EVT for swifterror");
4703 
4704   // Chain, DL, Reg, VT, Glue or Chain, DL, Reg, VT
4705   SDValue L = DAG.getCopyFromReg(
4706       getRoot(), getCurSDLoc(),
4707       SwiftError.getOrCreateVRegUseAt(&I, FuncInfo.MBB, SV), ValueVTs[0]);
4708 
4709   setValue(&I, L);
4710 }
4711 
4712 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
4713   if (I.isAtomic())
4714     return visitAtomicStore(I);
4715 
4716   const Value *SrcV = I.getOperand(0);
4717   const Value *PtrV = I.getOperand(1);
4718 
4719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4720   if (TLI.supportSwiftError()) {
4721     // Swifterror values can come from either a function parameter with
4722     // swifterror attribute or an alloca with swifterror attribute.
4723     if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
4724       if (Arg->hasSwiftErrorAttr())
4725         return visitStoreToSwiftError(I);
4726     }
4727 
4728     if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
4729       if (Alloca->isSwiftError())
4730         return visitStoreToSwiftError(I);
4731     }
4732   }
4733 
4734   SmallVector<EVT, 4> ValueVTs, MemVTs;
4735   SmallVector<TypeSize, 4> Offsets;
4736   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(),
4737                   SrcV->getType(), ValueVTs, &MemVTs, &Offsets);
4738   unsigned NumValues = ValueVTs.size();
4739   if (NumValues == 0)
4740     return;
4741 
4742   // Get the lowered operands. Note that we do this after
4743   // checking if NumResults is zero, because with zero results
4744   // the operands won't have values in the map.
4745   SDValue Src = getValue(SrcV);
4746   SDValue Ptr = getValue(PtrV);
4747 
4748   SDValue Root = I.isVolatile() ? getRoot() : getMemoryRoot();
4749   SmallVector<SDValue, 4> Chains(std::min(MaxParallelChains, NumValues));
4750   SDLoc dl = getCurSDLoc();
4751   Align Alignment = I.getAlign();
4752   AAMDNodes AAInfo = I.getAAMetadata();
4753 
4754   auto MMOFlags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
4755 
4756   unsigned ChainI = 0;
4757   for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
4758     // See visitLoad comments.
4759     if (ChainI == MaxParallelChains) {
4760       SDValue Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4761                                   ArrayRef(Chains.data(), ChainI));
4762       Root = Chain;
4763       ChainI = 0;
4764     }
4765 
4766     // TODO: MachinePointerInfo only supports a fixed length offset.
4767     MachinePointerInfo PtrInfo =
4768         !Offsets[i].isScalable() || Offsets[i].isZero()
4769             ? MachinePointerInfo(PtrV, Offsets[i].getKnownMinValue())
4770             : MachinePointerInfo();
4771 
4772     SDValue Add = DAG.getObjectPtrOffset(dl, Ptr, Offsets[i]);
4773     SDValue Val = SDValue(Src.getNode(), Src.getResNo() + i);
4774     if (MemVTs[i] != ValueVTs[i])
4775       Val = DAG.getPtrExtOrTrunc(Val, dl, MemVTs[i]);
4776     SDValue St =
4777         DAG.getStore(Root, dl, Val, Add, PtrInfo, Alignment, MMOFlags, AAInfo);
4778     Chains[ChainI] = St;
4779   }
4780 
4781   SDValue StoreNode = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
4782                                   ArrayRef(Chains.data(), ChainI));
4783   setValue(&I, StoreNode);
4784   DAG.setRoot(StoreNode);
4785 }
4786 
4787 void SelectionDAGBuilder::visitMaskedStore(const CallInst &I,
4788                                            bool IsCompressing) {
4789   SDLoc sdl = getCurSDLoc();
4790 
4791   auto getMaskedStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4792                                Align &Alignment) {
4793     // llvm.masked.store.*(Src0, Ptr, alignment, Mask)
4794     Src0 = I.getArgOperand(0);
4795     Ptr = I.getArgOperand(1);
4796     Alignment = cast<ConstantInt>(I.getArgOperand(2))->getAlignValue();
4797     Mask = I.getArgOperand(3);
4798   };
4799   auto getCompressingStoreOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4800                                     Align &Alignment) {
4801     // llvm.masked.compressstore.*(Src0, Ptr, Mask)
4802     Src0 = I.getArgOperand(0);
4803     Ptr = I.getArgOperand(1);
4804     Mask = I.getArgOperand(2);
4805     Alignment = I.getParamAlign(1).valueOrOne();
4806   };
4807 
4808   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4809   Align Alignment;
4810   if (IsCompressing)
4811     getCompressingStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4812   else
4813     getMaskedStoreOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4814 
4815   SDValue Ptr = getValue(PtrOperand);
4816   SDValue Src0 = getValue(Src0Operand);
4817   SDValue Mask = getValue(MaskOperand);
4818   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4819 
4820   EVT VT = Src0.getValueType();
4821 
4822   auto MMOFlags = MachineMemOperand::MOStore;
4823   if (I.hasMetadata(LLVMContext::MD_nontemporal))
4824     MMOFlags |= MachineMemOperand::MONonTemporal;
4825 
4826   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4827       MachinePointerInfo(PtrOperand), MMOFlags,
4828       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4829 
4830   const auto &TLI = DAG.getTargetLoweringInfo();
4831   const auto &TTI =
4832       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
4833   SDValue StoreNode =
4834       !IsCompressing &&
4835               TTI.hasConditionalLoadStoreForType(I.getArgOperand(0)->getType())
4836           ? TLI.visitMaskedStore(DAG, sdl, getMemoryRoot(), MMO, Ptr, Src0,
4837                                  Mask)
4838           : DAG.getMaskedStore(getMemoryRoot(), sdl, Src0, Ptr, Offset, Mask,
4839                                VT, MMO, ISD::UNINDEXED, /*Truncating=*/false,
4840                                IsCompressing);
4841   DAG.setRoot(StoreNode);
4842   setValue(&I, StoreNode);
4843 }
4844 
4845 // Get a uniform base for the Gather/Scatter intrinsic.
4846 // The first argument of the Gather/Scatter intrinsic is a vector of pointers.
4847 // We try to represent it as a base pointer + vector of indices.
4848 // Usually, the vector of pointers comes from a 'getelementptr' instruction.
4849 // The first operand of the GEP may be a single pointer or a vector of pointers
4850 // Example:
4851 //   %gep.ptr = getelementptr i32, <8 x i32*> %vptr, <8 x i32> %ind
4852 //  or
4853 //   %gep.ptr = getelementptr i32, i32* %ptr,        <8 x i32> %ind
4854 // %res = call <8 x i32> @llvm.masked.gather.v8i32(<8 x i32*> %gep.ptr, ..
4855 //
4856 // When the first GEP operand is a single pointer - it is the uniform base we
4857 // are looking for. If first operand of the GEP is a splat vector - we
4858 // extract the splat value and use it as a uniform base.
4859 // In all other cases the function returns 'false'.
4860 static bool getUniformBase(const Value *Ptr, SDValue &Base, SDValue &Index,
4861                            ISD::MemIndexType &IndexType, SDValue &Scale,
4862                            SelectionDAGBuilder *SDB, const BasicBlock *CurBB,
4863                            uint64_t ElemSize) {
4864   SelectionDAG& DAG = SDB->DAG;
4865   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4866   const DataLayout &DL = DAG.getDataLayout();
4867 
4868   assert(Ptr->getType()->isVectorTy() && "Unexpected pointer type");
4869 
4870   // Handle splat constant pointer.
4871   if (auto *C = dyn_cast<Constant>(Ptr)) {
4872     C = C->getSplatValue();
4873     if (!C)
4874       return false;
4875 
4876     Base = SDB->getValue(C);
4877 
4878     ElementCount NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
4879     EVT VT = EVT::getVectorVT(*DAG.getContext(), TLI.getPointerTy(DL), NumElts);
4880     Index = DAG.getConstant(0, SDB->getCurSDLoc(), VT);
4881     IndexType = ISD::SIGNED_SCALED;
4882     Scale = DAG.getTargetConstant(1, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4883     return true;
4884   }
4885 
4886   const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
4887   if (!GEP || GEP->getParent() != CurBB)
4888     return false;
4889 
4890   if (GEP->getNumOperands() != 2)
4891     return false;
4892 
4893   const Value *BasePtr = GEP->getPointerOperand();
4894   const Value *IndexVal = GEP->getOperand(GEP->getNumOperands() - 1);
4895 
4896   // Make sure the base is scalar and the index is a vector.
4897   if (BasePtr->getType()->isVectorTy() || !IndexVal->getType()->isVectorTy())
4898     return false;
4899 
4900   TypeSize ScaleVal = DL.getTypeAllocSize(GEP->getResultElementType());
4901   if (ScaleVal.isScalable())
4902     return false;
4903 
4904   // Target may not support the required addressing mode.
4905   if (ScaleVal != 1 &&
4906       !TLI.isLegalScaleForGatherScatter(ScaleVal.getFixedValue(), ElemSize))
4907     return false;
4908 
4909   Base = SDB->getValue(BasePtr);
4910   Index = SDB->getValue(IndexVal);
4911   IndexType = ISD::SIGNED_SCALED;
4912 
4913   Scale =
4914       DAG.getTargetConstant(ScaleVal, SDB->getCurSDLoc(), TLI.getPointerTy(DL));
4915   return true;
4916 }
4917 
4918 void SelectionDAGBuilder::visitMaskedScatter(const CallInst &I) {
4919   SDLoc sdl = getCurSDLoc();
4920 
4921   // llvm.masked.scatter.*(Src0, Ptrs, alignment, Mask)
4922   const Value *Ptr = I.getArgOperand(1);
4923   SDValue Src0 = getValue(I.getArgOperand(0));
4924   SDValue Mask = getValue(I.getArgOperand(3));
4925   EVT VT = Src0.getValueType();
4926   Align Alignment = cast<ConstantInt>(I.getArgOperand(2))
4927                         ->getMaybeAlignValue()
4928                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
4929   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4930 
4931   SDValue Base;
4932   SDValue Index;
4933   ISD::MemIndexType IndexType;
4934   SDValue Scale;
4935   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
4936                                     I.getParent(), VT.getScalarStoreSize());
4937 
4938   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
4939   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
4940       MachinePointerInfo(AS), MachineMemOperand::MOStore,
4941       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata());
4942   if (!UniformBase) {
4943     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4944     Index = getValue(Ptr);
4945     IndexType = ISD::SIGNED_SCALED;
4946     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
4947   }
4948 
4949   EVT IdxVT = Index.getValueType();
4950   EVT EltTy = IdxVT.getVectorElementType();
4951   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
4952     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
4953     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
4954   }
4955 
4956   SDValue Ops[] = { getMemoryRoot(), Src0, Mask, Base, Index, Scale };
4957   SDValue Scatter = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), VT, sdl,
4958                                          Ops, MMO, IndexType, false);
4959   DAG.setRoot(Scatter);
4960   setValue(&I, Scatter);
4961 }
4962 
4963 void SelectionDAGBuilder::visitMaskedLoad(const CallInst &I, bool IsExpanding) {
4964   SDLoc sdl = getCurSDLoc();
4965 
4966   auto getMaskedLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4967                               Align &Alignment) {
4968     // @llvm.masked.load.*(Ptr, alignment, Mask, Src0)
4969     Ptr = I.getArgOperand(0);
4970     Alignment = cast<ConstantInt>(I.getArgOperand(1))->getAlignValue();
4971     Mask = I.getArgOperand(2);
4972     Src0 = I.getArgOperand(3);
4973   };
4974   auto getExpandingLoadOps = [&](Value *&Ptr, Value *&Mask, Value *&Src0,
4975                                  Align &Alignment) {
4976     // @llvm.masked.expandload.*(Ptr, Mask, Src0)
4977     Ptr = I.getArgOperand(0);
4978     Alignment = I.getParamAlign(0).valueOrOne();
4979     Mask = I.getArgOperand(1);
4980     Src0 = I.getArgOperand(2);
4981   };
4982 
4983   Value  *PtrOperand, *MaskOperand, *Src0Operand;
4984   Align Alignment;
4985   if (IsExpanding)
4986     getExpandingLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4987   else
4988     getMaskedLoadOps(PtrOperand, MaskOperand, Src0Operand, Alignment);
4989 
4990   SDValue Ptr = getValue(PtrOperand);
4991   SDValue Src0 = getValue(Src0Operand);
4992   SDValue Mask = getValue(MaskOperand);
4993   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
4994 
4995   EVT VT = Src0.getValueType();
4996   AAMDNodes AAInfo = I.getAAMetadata();
4997   const MDNode *Ranges = getRangeMetadata(I);
4998 
4999   // Do not serialize masked loads of constant memory with anything.
5000   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
5001   bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
5002 
5003   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
5004 
5005   auto MMOFlags = MachineMemOperand::MOLoad;
5006   if (I.hasMetadata(LLVMContext::MD_nontemporal))
5007     MMOFlags |= MachineMemOperand::MONonTemporal;
5008 
5009   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5010       MachinePointerInfo(PtrOperand), MMOFlags,
5011       LocationSize::beforeOrAfterPointer(), Alignment, AAInfo, Ranges);
5012 
5013   const auto &TLI = DAG.getTargetLoweringInfo();
5014   const auto &TTI =
5015       TLI.getTargetMachine().getTargetTransformInfo(*I.getFunction());
5016   // The Load/Res may point to different values and both of them are output
5017   // variables.
5018   SDValue Load;
5019   SDValue Res;
5020   if (!IsExpanding &&
5021       TTI.hasConditionalLoadStoreForType(Src0Operand->getType()))
5022     Res = TLI.visitMaskedLoad(DAG, sdl, InChain, MMO, Load, Ptr, Src0, Mask);
5023   else
5024     Res = Load =
5025         DAG.getMaskedLoad(VT, sdl, InChain, Ptr, Offset, Mask, Src0, VT, MMO,
5026                           ISD::UNINDEXED, ISD::NON_EXTLOAD, IsExpanding);
5027   if (AddToChain)
5028     PendingLoads.push_back(Load.getValue(1));
5029   setValue(&I, Res);
5030 }
5031 
5032 void SelectionDAGBuilder::visitMaskedGather(const CallInst &I) {
5033   SDLoc sdl = getCurSDLoc();
5034 
5035   // @llvm.masked.gather.*(Ptrs, alignment, Mask, Src0)
5036   const Value *Ptr = I.getArgOperand(0);
5037   SDValue Src0 = getValue(I.getArgOperand(3));
5038   SDValue Mask = getValue(I.getArgOperand(2));
5039 
5040   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5041   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5042   Align Alignment = cast<ConstantInt>(I.getArgOperand(1))
5043                         ->getMaybeAlignValue()
5044                         .value_or(DAG.getEVTAlign(VT.getScalarType()));
5045 
5046   const MDNode *Ranges = getRangeMetadata(I);
5047 
5048   SDValue Root = DAG.getRoot();
5049   SDValue Base;
5050   SDValue Index;
5051   ISD::MemIndexType IndexType;
5052   SDValue Scale;
5053   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
5054                                     I.getParent(), VT.getScalarStoreSize());
5055   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
5056   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5057       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
5058       LocationSize::beforeOrAfterPointer(), Alignment, I.getAAMetadata(),
5059       Ranges);
5060 
5061   if (!UniformBase) {
5062     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5063     Index = getValue(Ptr);
5064     IndexType = ISD::SIGNED_SCALED;
5065     Scale = DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
5066   }
5067 
5068   EVT IdxVT = Index.getValueType();
5069   EVT EltTy = IdxVT.getVectorElementType();
5070   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
5071     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
5072     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
5073   }
5074 
5075   SDValue Ops[] = { Root, Src0, Mask, Base, Index, Scale };
5076   SDValue Gather = DAG.getMaskedGather(DAG.getVTList(VT, MVT::Other), VT, sdl,
5077                                        Ops, MMO, IndexType, ISD::NON_EXTLOAD);
5078 
5079   PendingLoads.push_back(Gather.getValue(1));
5080   setValue(&I, Gather);
5081 }
5082 
5083 void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
5084   SDLoc dl = getCurSDLoc();
5085   AtomicOrdering SuccessOrdering = I.getSuccessOrdering();
5086   AtomicOrdering FailureOrdering = I.getFailureOrdering();
5087   SyncScope::ID SSID = I.getSyncScopeID();
5088 
5089   SDValue InChain = getRoot();
5090 
5091   MVT MemVT = getValue(I.getCompareOperand()).getSimpleValueType();
5092   SDVTList VTs = DAG.getVTList(MemVT, MVT::i1, MVT::Other);
5093 
5094   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5095   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5096 
5097   MachineFunction &MF = DAG.getMachineFunction();
5098   MachineMemOperand *MMO = MF.getMachineMemOperand(
5099       MachinePointerInfo(I.getPointerOperand()), Flags,
5100       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5101       AAMDNodes(), nullptr, SSID, SuccessOrdering, FailureOrdering);
5102 
5103   SDValue L = DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS,
5104                                    dl, MemVT, VTs, InChain,
5105                                    getValue(I.getPointerOperand()),
5106                                    getValue(I.getCompareOperand()),
5107                                    getValue(I.getNewValOperand()), MMO);
5108 
5109   SDValue OutChain = L.getValue(2);
5110 
5111   setValue(&I, L);
5112   DAG.setRoot(OutChain);
5113 }
5114 
5115 void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
5116   SDLoc dl = getCurSDLoc();
5117   ISD::NodeType NT;
5118   switch (I.getOperation()) {
5119   default: llvm_unreachable("Unknown atomicrmw operation");
5120   case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
5121   case AtomicRMWInst::Add:  NT = ISD::ATOMIC_LOAD_ADD; break;
5122   case AtomicRMWInst::Sub:  NT = ISD::ATOMIC_LOAD_SUB; break;
5123   case AtomicRMWInst::And:  NT = ISD::ATOMIC_LOAD_AND; break;
5124   case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
5125   case AtomicRMWInst::Or:   NT = ISD::ATOMIC_LOAD_OR; break;
5126   case AtomicRMWInst::Xor:  NT = ISD::ATOMIC_LOAD_XOR; break;
5127   case AtomicRMWInst::Max:  NT = ISD::ATOMIC_LOAD_MAX; break;
5128   case AtomicRMWInst::Min:  NT = ISD::ATOMIC_LOAD_MIN; break;
5129   case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
5130   case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
5131   case AtomicRMWInst::FAdd: NT = ISD::ATOMIC_LOAD_FADD; break;
5132   case AtomicRMWInst::FSub: NT = ISD::ATOMIC_LOAD_FSUB; break;
5133   case AtomicRMWInst::FMax: NT = ISD::ATOMIC_LOAD_FMAX; break;
5134   case AtomicRMWInst::FMin: NT = ISD::ATOMIC_LOAD_FMIN; break;
5135   case AtomicRMWInst::UIncWrap:
5136     NT = ISD::ATOMIC_LOAD_UINC_WRAP;
5137     break;
5138   case AtomicRMWInst::UDecWrap:
5139     NT = ISD::ATOMIC_LOAD_UDEC_WRAP;
5140     break;
5141   case AtomicRMWInst::USubCond:
5142     NT = ISD::ATOMIC_LOAD_USUB_COND;
5143     break;
5144   case AtomicRMWInst::USubSat:
5145     NT = ISD::ATOMIC_LOAD_USUB_SAT;
5146     break;
5147   }
5148   AtomicOrdering Ordering = I.getOrdering();
5149   SyncScope::ID SSID = I.getSyncScopeID();
5150 
5151   SDValue InChain = getRoot();
5152 
5153   auto MemVT = getValue(I.getValOperand()).getSimpleValueType();
5154   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5155   auto Flags = TLI.getAtomicMemOperandFlags(I, DAG.getDataLayout());
5156 
5157   MachineFunction &MF = DAG.getMachineFunction();
5158   MachineMemOperand *MMO = MF.getMachineMemOperand(
5159       MachinePointerInfo(I.getPointerOperand()), Flags,
5160       LocationSize::precise(MemVT.getStoreSize()), DAG.getEVTAlign(MemVT),
5161       AAMDNodes(), nullptr, SSID, Ordering);
5162 
5163   SDValue L =
5164     DAG.getAtomic(NT, dl, MemVT, InChain,
5165                   getValue(I.getPointerOperand()), getValue(I.getValOperand()),
5166                   MMO);
5167 
5168   SDValue OutChain = L.getValue(1);
5169 
5170   setValue(&I, L);
5171   DAG.setRoot(OutChain);
5172 }
5173 
5174 void SelectionDAGBuilder::visitFence(const FenceInst &I) {
5175   SDLoc dl = getCurSDLoc();
5176   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5177   SDValue Ops[3];
5178   Ops[0] = getRoot();
5179   Ops[1] = DAG.getTargetConstant((unsigned)I.getOrdering(), dl,
5180                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5181   Ops[2] = DAG.getTargetConstant(I.getSyncScopeID(), dl,
5182                                  TLI.getFenceOperandTy(DAG.getDataLayout()));
5183   SDValue N = DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops);
5184   setValue(&I, N);
5185   DAG.setRoot(N);
5186 }
5187 
5188 void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
5189   SDLoc dl = getCurSDLoc();
5190   AtomicOrdering Order = I.getOrdering();
5191   SyncScope::ID SSID = I.getSyncScopeID();
5192 
5193   SDValue InChain = getRoot();
5194 
5195   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5196   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
5197   EVT MemVT = TLI.getMemValueType(DAG.getDataLayout(), I.getType());
5198 
5199   if (!TLI.supportsUnalignedAtomics() &&
5200       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5201     report_fatal_error("Cannot generate unaligned atomic load");
5202 
5203   auto Flags = TLI.getLoadMemOperandFlags(I, DAG.getDataLayout(), AC, LibInfo);
5204 
5205   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
5206       MachinePointerInfo(I.getPointerOperand()), Flags,
5207       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5208       nullptr, SSID, Order);
5209 
5210   InChain = TLI.prepareVolatileOrAtomicLoad(InChain, dl, DAG);
5211 
5212   SDValue Ptr = getValue(I.getPointerOperand());
5213   SDValue L = DAG.getAtomic(ISD::ATOMIC_LOAD, dl, MemVT, MemVT, InChain,
5214                             Ptr, MMO);
5215 
5216   SDValue OutChain = L.getValue(1);
5217   if (MemVT != VT)
5218     L = DAG.getPtrExtOrTrunc(L, dl, VT);
5219 
5220   setValue(&I, L);
5221   DAG.setRoot(OutChain);
5222 }
5223 
5224 void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
5225   SDLoc dl = getCurSDLoc();
5226 
5227   AtomicOrdering Ordering = I.getOrdering();
5228   SyncScope::ID SSID = I.getSyncScopeID();
5229 
5230   SDValue InChain = getRoot();
5231 
5232   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5233   EVT MemVT =
5234       TLI.getMemValueType(DAG.getDataLayout(), I.getValueOperand()->getType());
5235 
5236   if (!TLI.supportsUnalignedAtomics() &&
5237       I.getAlign().value() < MemVT.getSizeInBits() / 8)
5238     report_fatal_error("Cannot generate unaligned atomic store");
5239 
5240   auto Flags = TLI.getStoreMemOperandFlags(I, DAG.getDataLayout());
5241 
5242   MachineFunction &MF = DAG.getMachineFunction();
5243   MachineMemOperand *MMO = MF.getMachineMemOperand(
5244       MachinePointerInfo(I.getPointerOperand()), Flags,
5245       LocationSize::precise(MemVT.getStoreSize()), I.getAlign(), AAMDNodes(),
5246       nullptr, SSID, Ordering);
5247 
5248   SDValue Val = getValue(I.getValueOperand());
5249   if (Val.getValueType() != MemVT)
5250     Val = DAG.getPtrExtOrTrunc(Val, dl, MemVT);
5251   SDValue Ptr = getValue(I.getPointerOperand());
5252 
5253   SDValue OutChain =
5254       DAG.getAtomic(ISD::ATOMIC_STORE, dl, MemVT, InChain, Val, Ptr, MMO);
5255 
5256   setValue(&I, OutChain);
5257   DAG.setRoot(OutChain);
5258 }
5259 
5260 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
5261 /// node.
5262 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
5263                                                unsigned Intrinsic) {
5264   // Ignore the callsite's attributes. A specific call site may be marked with
5265   // readnone, but the lowering code will expect the chain based on the
5266   // definition.
5267   const Function *F = I.getCalledFunction();
5268   bool HasChain = !F->doesNotAccessMemory();
5269   bool OnlyLoad =
5270       HasChain && F->onlyReadsMemory() && F->willReturn() && F->doesNotThrow();
5271 
5272   // Build the operand list.
5273   SmallVector<SDValue, 8> Ops;
5274   if (HasChain) {  // If this intrinsic has side-effects, chainify it.
5275     if (OnlyLoad) {
5276       // We don't need to serialize loads against other loads.
5277       Ops.push_back(DAG.getRoot());
5278     } else {
5279       Ops.push_back(getRoot());
5280     }
5281   }
5282 
5283   // Info is set by getTgtMemIntrinsic
5284   TargetLowering::IntrinsicInfo Info;
5285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5286   bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I,
5287                                                DAG.getMachineFunction(),
5288                                                Intrinsic);
5289 
5290   // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
5291   if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
5292       Info.opc == ISD::INTRINSIC_W_CHAIN)
5293     Ops.push_back(DAG.getTargetConstant(Intrinsic, getCurSDLoc(),
5294                                         TLI.getPointerTy(DAG.getDataLayout())));
5295 
5296   // Add all operands of the call to the operand list.
5297   for (unsigned i = 0, e = I.arg_size(); i != e; ++i) {
5298     const Value *Arg = I.getArgOperand(i);
5299     if (!I.paramHasAttr(i, Attribute::ImmArg)) {
5300       Ops.push_back(getValue(Arg));
5301       continue;
5302     }
5303 
5304     // Use TargetConstant instead of a regular constant for immarg.
5305     EVT VT = TLI.getValueType(DAG.getDataLayout(), Arg->getType(), true);
5306     if (const ConstantInt *CI = dyn_cast<ConstantInt>(Arg)) {
5307       assert(CI->getBitWidth() <= 64 &&
5308              "large intrinsic immediates not handled");
5309       Ops.push_back(DAG.getTargetConstant(*CI, SDLoc(), VT));
5310     } else {
5311       Ops.push_back(
5312           DAG.getTargetConstantFP(*cast<ConstantFP>(Arg), SDLoc(), VT));
5313     }
5314   }
5315 
5316   SmallVector<EVT, 4> ValueVTs;
5317   ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
5318 
5319   if (HasChain)
5320     ValueVTs.push_back(MVT::Other);
5321 
5322   SDVTList VTs = DAG.getVTList(ValueVTs);
5323 
5324   // Propagate fast-math-flags from IR to node(s).
5325   SDNodeFlags Flags;
5326   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
5327     Flags.copyFMF(*FPMO);
5328   SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
5329 
5330   // Create the node.
5331   SDValue Result;
5332 
5333   if (auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl)) {
5334     auto *Token = Bundle->Inputs[0].get();
5335     SDValue ConvControlToken = getValue(Token);
5336     assert(Ops.back().getValueType() != MVT::Glue &&
5337            "Did not expected another glue node here.");
5338     ConvControlToken =
5339         DAG.getNode(ISD::CONVERGENCECTRL_GLUE, {}, MVT::Glue, ConvControlToken);
5340     Ops.push_back(ConvControlToken);
5341   }
5342 
5343   // In some cases, custom collection of operands from CallInst I may be needed.
5344   TLI.CollectTargetIntrinsicOperands(I, Ops, DAG);
5345   if (IsTgtIntrinsic) {
5346     // This is target intrinsic that touches memory
5347     //
5348     // TODO: We currently just fallback to address space 0 if getTgtMemIntrinsic
5349     //       didn't yield anything useful.
5350     MachinePointerInfo MPI;
5351     if (Info.ptrVal)
5352       MPI = MachinePointerInfo(Info.ptrVal, Info.offset);
5353     else if (Info.fallbackAddressSpace)
5354       MPI = MachinePointerInfo(*Info.fallbackAddressSpace);
5355     Result = DAG.getMemIntrinsicNode(Info.opc, getCurSDLoc(), VTs, Ops,
5356                                      Info.memVT, MPI, Info.align, Info.flags,
5357                                      Info.size, I.getAAMetadata());
5358   } else if (!HasChain) {
5359     Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurSDLoc(), VTs, Ops);
5360   } else if (!I.getType()->isVoidTy()) {
5361     Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurSDLoc(), VTs, Ops);
5362   } else {
5363     Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurSDLoc(), VTs, Ops);
5364   }
5365 
5366   if (HasChain) {
5367     SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
5368     if (OnlyLoad)
5369       PendingLoads.push_back(Chain);
5370     else
5371       DAG.setRoot(Chain);
5372   }
5373 
5374   if (!I.getType()->isVoidTy()) {
5375     if (!isa<VectorType>(I.getType()))
5376       Result = lowerRangeToAssertZExt(DAG, I, Result);
5377 
5378     MaybeAlign Alignment = I.getRetAlign();
5379 
5380     // Insert `assertalign` node if there's an alignment.
5381     if (InsertAssertAlign && Alignment) {
5382       Result =
5383           DAG.getAssertAlign(getCurSDLoc(), Result, Alignment.valueOrOne());
5384     }
5385   }
5386 
5387   setValue(&I, Result);
5388 }
5389 
5390 /// GetSignificand - Get the significand and build it into a floating-point
5391 /// number with exponent of 1:
5392 ///
5393 ///   Op = (Op & 0x007fffff) | 0x3f800000;
5394 ///
5395 /// where Op is the hexadecimal representation of floating point value.
5396 static SDValue GetSignificand(SelectionDAG &DAG, SDValue Op, const SDLoc &dl) {
5397   SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5398                            DAG.getConstant(0x007fffff, dl, MVT::i32));
5399   SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
5400                            DAG.getConstant(0x3f800000, dl, MVT::i32));
5401   return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
5402 }
5403 
5404 /// GetExponent - Get the exponent:
5405 ///
5406 ///   (float)(int)(((Op & 0x7f800000) >> 23) - 127);
5407 ///
5408 /// where Op is the hexadecimal representation of floating point value.
5409 static SDValue GetExponent(SelectionDAG &DAG, SDValue Op,
5410                            const TargetLowering &TLI, const SDLoc &dl) {
5411   SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
5412                            DAG.getConstant(0x7f800000, dl, MVT::i32));
5413   SDValue t1 = DAG.getNode(
5414       ISD::SRL, dl, MVT::i32, t0,
5415       DAG.getConstant(23, dl,
5416                       TLI.getShiftAmountTy(MVT::i32, DAG.getDataLayout())));
5417   SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
5418                            DAG.getConstant(127, dl, MVT::i32));
5419   return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
5420 }
5421 
5422 /// getF32Constant - Get 32-bit floating point constant.
5423 static SDValue getF32Constant(SelectionDAG &DAG, unsigned Flt,
5424                               const SDLoc &dl) {
5425   return DAG.getConstantFP(APFloat(APFloat::IEEEsingle(), APInt(32, Flt)), dl,
5426                            MVT::f32);
5427 }
5428 
5429 static SDValue getLimitedPrecisionExp2(SDValue t0, const SDLoc &dl,
5430                                        SelectionDAG &DAG) {
5431   // TODO: What fast-math-flags should be set on the floating-point nodes?
5432 
5433   //   IntegerPartOfX = ((int32_t)(t0);
5434   SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
5435 
5436   //   FractionalPartOfX = t0 - (float)IntegerPartOfX;
5437   SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
5438   SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
5439 
5440   //   IntegerPartOfX <<= 23;
5441   IntegerPartOfX =
5442       DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
5443                   DAG.getConstant(23, dl,
5444                                   DAG.getTargetLoweringInfo().getShiftAmountTy(
5445                                       MVT::i32, DAG.getDataLayout())));
5446 
5447   SDValue TwoToFractionalPartOfX;
5448   if (LimitFloatPrecision <= 6) {
5449     // For floating-point precision of 6:
5450     //
5451     //   TwoToFractionalPartOfX =
5452     //     0.997535578f +
5453     //       (0.735607626f + 0.252464424f * x) * x;
5454     //
5455     // error 0.0144103317, which is 6 bits
5456     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5457                              getF32Constant(DAG, 0x3e814304, dl));
5458     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5459                              getF32Constant(DAG, 0x3f3c50c8, dl));
5460     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5461     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5462                                          getF32Constant(DAG, 0x3f7f5e7e, dl));
5463   } else if (LimitFloatPrecision <= 12) {
5464     // For floating-point precision of 12:
5465     //
5466     //   TwoToFractionalPartOfX =
5467     //     0.999892986f +
5468     //       (0.696457318f +
5469     //         (0.224338339f + 0.792043434e-1f * x) * x) * x;
5470     //
5471     // error 0.000107046256, which is 13 to 14 bits
5472     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5473                              getF32Constant(DAG, 0x3da235e3, dl));
5474     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5475                              getF32Constant(DAG, 0x3e65b8f3, dl));
5476     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5477     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5478                              getF32Constant(DAG, 0x3f324b07, dl));
5479     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5480     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5481                                          getF32Constant(DAG, 0x3f7ff8fd, dl));
5482   } else { // LimitFloatPrecision <= 18
5483     // For floating-point precision of 18:
5484     //
5485     //   TwoToFractionalPartOfX =
5486     //     0.999999982f +
5487     //       (0.693148872f +
5488     //         (0.240227044f +
5489     //           (0.554906021e-1f +
5490     //             (0.961591928e-2f +
5491     //               (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
5492     // error 2.47208000*10^(-7), which is better than 18 bits
5493     SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5494                              getF32Constant(DAG, 0x3924b03e, dl));
5495     SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5496                              getF32Constant(DAG, 0x3ab24b87, dl));
5497     SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5498     SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5499                              getF32Constant(DAG, 0x3c1d8c17, dl));
5500     SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5501     SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5502                              getF32Constant(DAG, 0x3d634a1d, dl));
5503     SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5504     SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5505                              getF32Constant(DAG, 0x3e75fe14, dl));
5506     SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5507     SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
5508                               getF32Constant(DAG, 0x3f317234, dl));
5509     SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
5510     TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
5511                                          getF32Constant(DAG, 0x3f800000, dl));
5512   }
5513 
5514   // Add the exponent into the result in integer domain.
5515   SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFractionalPartOfX);
5516   return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5517                      DAG.getNode(ISD::ADD, dl, MVT::i32, t13, IntegerPartOfX));
5518 }
5519 
5520 /// expandExp - Lower an exp intrinsic. Handles the special sequences for
5521 /// limited-precision mode.
5522 static SDValue expandExp(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5523                          const TargetLowering &TLI, SDNodeFlags Flags) {
5524   if (Op.getValueType() == MVT::f32 &&
5525       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5526 
5527     // Put the exponent in the right bit position for later addition to the
5528     // final result:
5529     //
5530     // t0 = Op * log2(e)
5531 
5532     // TODO: What fast-math-flags should be set here?
5533     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
5534                              DAG.getConstantFP(numbers::log2ef, dl, MVT::f32));
5535     return getLimitedPrecisionExp2(t0, dl, DAG);
5536   }
5537 
5538   // No special expansion.
5539   return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op, Flags);
5540 }
5541 
5542 /// expandLog - Lower a log intrinsic. Handles the special sequences for
5543 /// limited-precision mode.
5544 static SDValue expandLog(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5545                          const TargetLowering &TLI, SDNodeFlags Flags) {
5546   // TODO: What fast-math-flags should be set on the floating-point nodes?
5547 
5548   if (Op.getValueType() == MVT::f32 &&
5549       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5550     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5551 
5552     // Scale the exponent by log(2).
5553     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5554     SDValue LogOfExponent =
5555         DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5556                     DAG.getConstantFP(numbers::ln2f, dl, MVT::f32));
5557 
5558     // Get the significand and build it into a floating-point number with
5559     // exponent of 1.
5560     SDValue X = GetSignificand(DAG, Op1, dl);
5561 
5562     SDValue LogOfMantissa;
5563     if (LimitFloatPrecision <= 6) {
5564       // For floating-point precision of 6:
5565       //
5566       //   LogofMantissa =
5567       //     -1.1609546f +
5568       //       (1.4034025f - 0.23903021f * x) * x;
5569       //
5570       // error 0.0034276066, which is better than 8 bits
5571       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5572                                getF32Constant(DAG, 0xbe74c456, dl));
5573       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5574                                getF32Constant(DAG, 0x3fb3a2b1, dl));
5575       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5576       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5577                                   getF32Constant(DAG, 0x3f949a29, dl));
5578     } else if (LimitFloatPrecision <= 12) {
5579       // For floating-point precision of 12:
5580       //
5581       //   LogOfMantissa =
5582       //     -1.7417939f +
5583       //       (2.8212026f +
5584       //         (-1.4699568f +
5585       //           (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
5586       //
5587       // error 0.000061011436, which is 14 bits
5588       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5589                                getF32Constant(DAG, 0xbd67b6d6, dl));
5590       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5591                                getF32Constant(DAG, 0x3ee4f4b8, dl));
5592       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5593       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5594                                getF32Constant(DAG, 0x3fbc278b, dl));
5595       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5596       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5597                                getF32Constant(DAG, 0x40348e95, dl));
5598       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5599       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5600                                   getF32Constant(DAG, 0x3fdef31a, dl));
5601     } else { // LimitFloatPrecision <= 18
5602       // For floating-point precision of 18:
5603       //
5604       //   LogOfMantissa =
5605       //     -2.1072184f +
5606       //       (4.2372794f +
5607       //         (-3.7029485f +
5608       //           (2.2781945f +
5609       //             (-0.87823314f +
5610       //               (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
5611       //
5612       // error 0.0000023660568, which is better than 18 bits
5613       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5614                                getF32Constant(DAG, 0xbc91e5ac, dl));
5615       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5616                                getF32Constant(DAG, 0x3e4350aa, dl));
5617       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5618       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5619                                getF32Constant(DAG, 0x3f60d3e3, dl));
5620       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5621       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5622                                getF32Constant(DAG, 0x4011cdf0, dl));
5623       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5624       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5625                                getF32Constant(DAG, 0x406cfd1c, dl));
5626       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5627       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5628                                getF32Constant(DAG, 0x408797cb, dl));
5629       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5630       LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5631                                   getF32Constant(DAG, 0x4006dcab, dl));
5632     }
5633 
5634     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
5635   }
5636 
5637   // No special expansion.
5638   return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op, Flags);
5639 }
5640 
5641 /// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
5642 /// limited-precision mode.
5643 static SDValue expandLog2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5644                           const TargetLowering &TLI, SDNodeFlags Flags) {
5645   // TODO: What fast-math-flags should be set on the floating-point nodes?
5646 
5647   if (Op.getValueType() == MVT::f32 &&
5648       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5649     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5650 
5651     // Get the exponent.
5652     SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
5653 
5654     // Get the significand and build it into a floating-point number with
5655     // exponent of 1.
5656     SDValue X = GetSignificand(DAG, Op1, dl);
5657 
5658     // Different possible minimax approximations of significand in
5659     // floating-point for various degrees of accuracy over [1,2].
5660     SDValue Log2ofMantissa;
5661     if (LimitFloatPrecision <= 6) {
5662       // For floating-point precision of 6:
5663       //
5664       //   Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
5665       //
5666       // error 0.0049451742, which is more than 7 bits
5667       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5668                                getF32Constant(DAG, 0xbeb08fe0, dl));
5669       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5670                                getF32Constant(DAG, 0x40019463, dl));
5671       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5672       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5673                                    getF32Constant(DAG, 0x3fd6633d, dl));
5674     } else if (LimitFloatPrecision <= 12) {
5675       // For floating-point precision of 12:
5676       //
5677       //   Log2ofMantissa =
5678       //     -2.51285454f +
5679       //       (4.07009056f +
5680       //         (-2.12067489f +
5681       //           (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
5682       //
5683       // error 0.0000876136000, which is better than 13 bits
5684       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5685                                getF32Constant(DAG, 0xbda7262e, dl));
5686       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5687                                getF32Constant(DAG, 0x3f25280b, dl));
5688       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5689       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5690                                getF32Constant(DAG, 0x4007b923, dl));
5691       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5692       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5693                                getF32Constant(DAG, 0x40823e2f, dl));
5694       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5695       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5696                                    getF32Constant(DAG, 0x4020d29c, dl));
5697     } else { // LimitFloatPrecision <= 18
5698       // For floating-point precision of 18:
5699       //
5700       //   Log2ofMantissa =
5701       //     -3.0400495f +
5702       //       (6.1129976f +
5703       //         (-5.3420409f +
5704       //           (3.2865683f +
5705       //             (-1.2669343f +
5706       //               (0.27515199f -
5707       //                 0.25691327e-1f * x) * x) * x) * x) * x) * x;
5708       //
5709       // error 0.0000018516, which is better than 18 bits
5710       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5711                                getF32Constant(DAG, 0xbcd2769e, dl));
5712       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5713                                getF32Constant(DAG, 0x3e8ce0b9, dl));
5714       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5715       SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5716                                getF32Constant(DAG, 0x3fa22ae7, dl));
5717       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5718       SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
5719                                getF32Constant(DAG, 0x40525723, dl));
5720       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5721       SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
5722                                getF32Constant(DAG, 0x40aaf200, dl));
5723       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5724       SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
5725                                getF32Constant(DAG, 0x40c39dad, dl));
5726       SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
5727       Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
5728                                    getF32Constant(DAG, 0x4042902c, dl));
5729     }
5730 
5731     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
5732   }
5733 
5734   // No special expansion.
5735   return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op, Flags);
5736 }
5737 
5738 /// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
5739 /// limited-precision mode.
5740 static SDValue expandLog10(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5741                            const TargetLowering &TLI, SDNodeFlags Flags) {
5742   // TODO: What fast-math-flags should be set on the floating-point nodes?
5743 
5744   if (Op.getValueType() == MVT::f32 &&
5745       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5746     SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
5747 
5748     // Scale the exponent by log10(2) [0.30102999f].
5749     SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
5750     SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
5751                                         getF32Constant(DAG, 0x3e9a209a, dl));
5752 
5753     // Get the significand and build it into a floating-point number with
5754     // exponent of 1.
5755     SDValue X = GetSignificand(DAG, Op1, dl);
5756 
5757     SDValue Log10ofMantissa;
5758     if (LimitFloatPrecision <= 6) {
5759       // For floating-point precision of 6:
5760       //
5761       //   Log10ofMantissa =
5762       //     -0.50419619f +
5763       //       (0.60948995f - 0.10380950f * x) * x;
5764       //
5765       // error 0.0014886165, which is 6 bits
5766       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5767                                getF32Constant(DAG, 0xbdd49a13, dl));
5768       SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
5769                                getF32Constant(DAG, 0x3f1c0789, dl));
5770       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5771       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
5772                                     getF32Constant(DAG, 0x3f011300, dl));
5773     } else if (LimitFloatPrecision <= 12) {
5774       // For floating-point precision of 12:
5775       //
5776       //   Log10ofMantissa =
5777       //     -0.64831180f +
5778       //       (0.91751397f +
5779       //         (-0.31664806f + 0.47637168e-1f * x) * x) * x;
5780       //
5781       // error 0.00019228036, which is better than 12 bits
5782       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5783                                getF32Constant(DAG, 0x3d431f31, dl));
5784       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5785                                getF32Constant(DAG, 0x3ea21fb2, dl));
5786       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5787       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5788                                getF32Constant(DAG, 0x3f6ae232, dl));
5789       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5790       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5791                                     getF32Constant(DAG, 0x3f25f7c3, dl));
5792     } else { // LimitFloatPrecision <= 18
5793       // For floating-point precision of 18:
5794       //
5795       //   Log10ofMantissa =
5796       //     -0.84299375f +
5797       //       (1.5327582f +
5798       //         (-1.0688956f +
5799       //           (0.49102474f +
5800       //             (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
5801       //
5802       // error 0.0000037995730, which is better than 18 bits
5803       SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
5804                                getF32Constant(DAG, 0x3c5d51ce, dl));
5805       SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
5806                                getF32Constant(DAG, 0x3e00685a, dl));
5807       SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
5808       SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
5809                                getF32Constant(DAG, 0x3efb6798, dl));
5810       SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
5811       SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
5812                                getF32Constant(DAG, 0x3f88d192, dl));
5813       SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
5814       SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
5815                                getF32Constant(DAG, 0x3fc4316c, dl));
5816       SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
5817       Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
5818                                     getF32Constant(DAG, 0x3f57ce70, dl));
5819     }
5820 
5821     return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
5822   }
5823 
5824   // No special expansion.
5825   return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op, Flags);
5826 }
5827 
5828 /// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
5829 /// limited-precision mode.
5830 static SDValue expandExp2(const SDLoc &dl, SDValue Op, SelectionDAG &DAG,
5831                           const TargetLowering &TLI, SDNodeFlags Flags) {
5832   if (Op.getValueType() == MVT::f32 &&
5833       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18)
5834     return getLimitedPrecisionExp2(Op, dl, DAG);
5835 
5836   // No special expansion.
5837   return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op, Flags);
5838 }
5839 
5840 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
5841 /// limited-precision mode with x == 10.0f.
5842 static SDValue expandPow(const SDLoc &dl, SDValue LHS, SDValue RHS,
5843                          SelectionDAG &DAG, const TargetLowering &TLI,
5844                          SDNodeFlags Flags) {
5845   bool IsExp10 = false;
5846   if (LHS.getValueType() == MVT::f32 && RHS.getValueType() == MVT::f32 &&
5847       LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
5848     if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
5849       APFloat Ten(10.0f);
5850       IsExp10 = LHSC->isExactlyValue(Ten);
5851     }
5852   }
5853 
5854   // TODO: What fast-math-flags should be set on the FMUL node?
5855   if (IsExp10) {
5856     // Put the exponent in the right bit position for later addition to the
5857     // final result:
5858     //
5859     //   #define LOG2OF10 3.3219281f
5860     //   t0 = Op * LOG2OF10;
5861     SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
5862                              getF32Constant(DAG, 0x40549a78, dl));
5863     return getLimitedPrecisionExp2(t0, dl, DAG);
5864   }
5865 
5866   // No special expansion.
5867   return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS, Flags);
5868 }
5869 
5870 /// ExpandPowI - Expand a llvm.powi intrinsic.
5871 static SDValue ExpandPowI(const SDLoc &DL, SDValue LHS, SDValue RHS,
5872                           SelectionDAG &DAG) {
5873   // If RHS is a constant, we can expand this out to a multiplication tree if
5874   // it's beneficial on the target, otherwise we end up lowering to a call to
5875   // __powidf2 (for example).
5876   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
5877     unsigned Val = RHSC->getSExtValue();
5878 
5879     // powi(x, 0) -> 1.0
5880     if (Val == 0)
5881       return DAG.getConstantFP(1.0, DL, LHS.getValueType());
5882 
5883     if (DAG.getTargetLoweringInfo().isBeneficialToExpandPowI(
5884             Val, DAG.shouldOptForSize())) {
5885       // Get the exponent as a positive value.
5886       if ((int)Val < 0)
5887         Val = -Val;
5888       // We use the simple binary decomposition method to generate the multiply
5889       // sequence.  There are more optimal ways to do this (for example,
5890       // powi(x,15) generates one more multiply than it should), but this has
5891       // the benefit of being both really simple and much better than a libcall.
5892       SDValue Res; // Logically starts equal to 1.0
5893       SDValue CurSquare = LHS;
5894       // TODO: Intrinsics should have fast-math-flags that propagate to these
5895       // nodes.
5896       while (Val) {
5897         if (Val & 1) {
5898           if (Res.getNode())
5899             Res =
5900                 DAG.getNode(ISD::FMUL, DL, Res.getValueType(), Res, CurSquare);
5901           else
5902             Res = CurSquare; // 1.0*CurSquare.
5903         }
5904 
5905         CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
5906                                 CurSquare, CurSquare);
5907         Val >>= 1;
5908       }
5909 
5910       // If the original was negative, invert the result, producing 1/(x*x*x).
5911       if (RHSC->getSExtValue() < 0)
5912         Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
5913                           DAG.getConstantFP(1.0, DL, LHS.getValueType()), Res);
5914       return Res;
5915     }
5916   }
5917 
5918   // Otherwise, expand to a libcall.
5919   return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
5920 }
5921 
5922 static SDValue expandDivFix(unsigned Opcode, const SDLoc &DL,
5923                             SDValue LHS, SDValue RHS, SDValue Scale,
5924                             SelectionDAG &DAG, const TargetLowering &TLI) {
5925   EVT VT = LHS.getValueType();
5926   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
5927   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
5928   LLVMContext &Ctx = *DAG.getContext();
5929 
5930   // If the type is legal but the operation isn't, this node might survive all
5931   // the way to operation legalization. If we end up there and we do not have
5932   // the ability to widen the type (if VT*2 is not legal), we cannot expand the
5933   // node.
5934 
5935   // Coax the legalizer into expanding the node during type legalization instead
5936   // by bumping the size by one bit. This will force it to Promote, enabling the
5937   // early expansion and avoiding the need to expand later.
5938 
5939   // We don't have to do this if Scale is 0; that can always be expanded, unless
5940   // it's a saturating signed operation. Those can experience true integer
5941   // division overflow, a case which we must avoid.
5942 
5943   // FIXME: We wouldn't have to do this (or any of the early
5944   // expansion/promotion) if it was possible to expand a libcall of an
5945   // illegal type during operation legalization. But it's not, so things
5946   // get a bit hacky.
5947   unsigned ScaleInt = Scale->getAsZExtVal();
5948   if ((ScaleInt > 0 || (Saturating && Signed)) &&
5949       (TLI.isTypeLegal(VT) ||
5950        (VT.isVector() && TLI.isTypeLegal(VT.getVectorElementType())))) {
5951     TargetLowering::LegalizeAction Action = TLI.getFixedPointOperationAction(
5952         Opcode, VT, ScaleInt);
5953     if (Action != TargetLowering::Legal && Action != TargetLowering::Custom) {
5954       EVT PromVT;
5955       if (VT.isScalarInteger())
5956         PromVT = EVT::getIntegerVT(Ctx, VT.getSizeInBits() + 1);
5957       else if (VT.isVector()) {
5958         PromVT = VT.getVectorElementType();
5959         PromVT = EVT::getIntegerVT(Ctx, PromVT.getSizeInBits() + 1);
5960         PromVT = EVT::getVectorVT(Ctx, PromVT, VT.getVectorElementCount());
5961       } else
5962         llvm_unreachable("Wrong VT for DIVFIX?");
5963       LHS = DAG.getExtOrTrunc(Signed, LHS, DL, PromVT);
5964       RHS = DAG.getExtOrTrunc(Signed, RHS, DL, PromVT);
5965       EVT ShiftTy = TLI.getShiftAmountTy(PromVT, DAG.getDataLayout());
5966       // For saturating operations, we need to shift up the LHS to get the
5967       // proper saturation width, and then shift down again afterwards.
5968       if (Saturating)
5969         LHS = DAG.getNode(ISD::SHL, DL, PromVT, LHS,
5970                           DAG.getConstant(1, DL, ShiftTy));
5971       SDValue Res = DAG.getNode(Opcode, DL, PromVT, LHS, RHS, Scale);
5972       if (Saturating)
5973         Res = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, DL, PromVT, Res,
5974                           DAG.getConstant(1, DL, ShiftTy));
5975       return DAG.getZExtOrTrunc(Res, DL, VT);
5976     }
5977   }
5978 
5979   return DAG.getNode(Opcode, DL, VT, LHS, RHS, Scale);
5980 }
5981 
5982 // getUnderlyingArgRegs - Find underlying registers used for a truncated,
5983 // bitcasted, or split argument. Returns a list of <Register, size in bits>
5984 static void
5985 getUnderlyingArgRegs(SmallVectorImpl<std::pair<Register, TypeSize>> &Regs,
5986                      const SDValue &N) {
5987   switch (N.getOpcode()) {
5988   case ISD::CopyFromReg: {
5989     SDValue Op = N.getOperand(1);
5990     Regs.emplace_back(cast<RegisterSDNode>(Op)->getReg(),
5991                       Op.getValueType().getSizeInBits());
5992     return;
5993   }
5994   case ISD::BITCAST:
5995   case ISD::AssertZext:
5996   case ISD::AssertSext:
5997   case ISD::TRUNCATE:
5998     getUnderlyingArgRegs(Regs, N.getOperand(0));
5999     return;
6000   case ISD::BUILD_PAIR:
6001   case ISD::BUILD_VECTOR:
6002   case ISD::CONCAT_VECTORS:
6003     for (SDValue Op : N->op_values())
6004       getUnderlyingArgRegs(Regs, Op);
6005     return;
6006   default:
6007     return;
6008   }
6009 }
6010 
6011 /// If the DbgValueInst is a dbg_value of a function argument, create the
6012 /// corresponding DBG_VALUE machine instruction for it now.  At the end of
6013 /// instruction selection, they will be inserted to the entry BB.
6014 /// We don't currently support this for variadic dbg_values, as they shouldn't
6015 /// appear for function arguments or in the prologue.
6016 bool SelectionDAGBuilder::EmitFuncArgumentDbgValue(
6017     const Value *V, DILocalVariable *Variable, DIExpression *Expr,
6018     DILocation *DL, FuncArgumentDbgValueKind Kind, const SDValue &N) {
6019   const Argument *Arg = dyn_cast<Argument>(V);
6020   if (!Arg)
6021     return false;
6022 
6023   MachineFunction &MF = DAG.getMachineFunction();
6024   const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
6025 
6026   // Helper to create DBG_INSTR_REFs or DBG_VALUEs, depending on what kind
6027   // we've been asked to pursue.
6028   auto MakeVRegDbgValue = [&](Register Reg, DIExpression *FragExpr,
6029                               bool Indirect) {
6030     if (Reg.isVirtual() && MF.useDebugInstrRef()) {
6031       // For VRegs, in instruction referencing mode, create a DBG_INSTR_REF
6032       // pointing at the VReg, which will be patched up later.
6033       auto &Inst = TII->get(TargetOpcode::DBG_INSTR_REF);
6034       SmallVector<MachineOperand, 1> MOs({MachineOperand::CreateReg(
6035           /* Reg */ Reg, /* isDef */ false, /* isImp */ false,
6036           /* isKill */ false, /* isDead */ false,
6037           /* isUndef */ false, /* isEarlyClobber */ false,
6038           /* SubReg */ 0, /* isDebug */ true)});
6039 
6040       auto *NewDIExpr = FragExpr;
6041       // We don't have an "Indirect" field in DBG_INSTR_REF, fold that into
6042       // the DIExpression.
6043       if (Indirect)
6044         NewDIExpr = DIExpression::prepend(FragExpr, DIExpression::DerefBefore);
6045       SmallVector<uint64_t, 2> Ops({dwarf::DW_OP_LLVM_arg, 0});
6046       NewDIExpr = DIExpression::prependOpcodes(NewDIExpr, Ops);
6047       return BuildMI(MF, DL, Inst, false, MOs, Variable, NewDIExpr);
6048     } else {
6049       // Create a completely standard DBG_VALUE.
6050       auto &Inst = TII->get(TargetOpcode::DBG_VALUE);
6051       return BuildMI(MF, DL, Inst, Indirect, Reg, Variable, FragExpr);
6052     }
6053   };
6054 
6055   if (Kind == FuncArgumentDbgValueKind::Value) {
6056     // ArgDbgValues are hoisted to the beginning of the entry block. So we
6057     // should only emit as ArgDbgValue if the dbg.value intrinsic is found in
6058     // the entry block.
6059     bool IsInEntryBlock = FuncInfo.MBB == &FuncInfo.MF->front();
6060     if (!IsInEntryBlock)
6061       return false;
6062 
6063     // ArgDbgValues are hoisted to the beginning of the entry block.  So we
6064     // should only emit as ArgDbgValue if the dbg.value intrinsic describes a
6065     // variable that also is a param.
6066     //
6067     // Although, if we are at the top of the entry block already, we can still
6068     // emit using ArgDbgValue. This might catch some situations when the
6069     // dbg.value refers to an argument that isn't used in the entry block, so
6070     // any CopyToReg node would be optimized out and the only way to express
6071     // this DBG_VALUE is by using the physical reg (or FI) as done in this
6072     // method.  ArgDbgValues are hoisted to the beginning of the entry block. So
6073     // we should only emit as ArgDbgValue if the Variable is an argument to the
6074     // current function, and the dbg.value intrinsic is found in the entry
6075     // block.
6076     bool VariableIsFunctionInputArg = Variable->isParameter() &&
6077         !DL->getInlinedAt();
6078     bool IsInPrologue = SDNodeOrder == LowestSDNodeOrder;
6079     if (!IsInPrologue && !VariableIsFunctionInputArg)
6080       return false;
6081 
6082     // Here we assume that a function argument on IR level only can be used to
6083     // describe one input parameter on source level. If we for example have
6084     // source code like this
6085     //
6086     //    struct A { long x, y; };
6087     //    void foo(struct A a, long b) {
6088     //      ...
6089     //      b = a.x;
6090     //      ...
6091     //    }
6092     //
6093     // and IR like this
6094     //
6095     //  define void @foo(i32 %a1, i32 %a2, i32 %b)  {
6096     //  entry:
6097     //    call void @llvm.dbg.value(metadata i32 %a1, "a", DW_OP_LLVM_fragment
6098     //    call void @llvm.dbg.value(metadata i32 %a2, "a", DW_OP_LLVM_fragment
6099     //    call void @llvm.dbg.value(metadata i32 %b, "b",
6100     //    ...
6101     //    call void @llvm.dbg.value(metadata i32 %a1, "b"
6102     //    ...
6103     //
6104     // then the last dbg.value is describing a parameter "b" using a value that
6105     // is an argument. But since we already has used %a1 to describe a parameter
6106     // we should not handle that last dbg.value here (that would result in an
6107     // incorrect hoisting of the DBG_VALUE to the function entry).
6108     // Notice that we allow one dbg.value per IR level argument, to accommodate
6109     // for the situation with fragments above.
6110     // If there is no node for the value being handled, we return true to skip
6111     // the normal generation of debug info, as it would kill existing debug
6112     // info for the parameter in case of duplicates.
6113     if (VariableIsFunctionInputArg) {
6114       unsigned ArgNo = Arg->getArgNo();
6115       if (ArgNo >= FuncInfo.DescribedArgs.size())
6116         FuncInfo.DescribedArgs.resize(ArgNo + 1, false);
6117       else if (!IsInPrologue && FuncInfo.DescribedArgs.test(ArgNo))
6118         return !NodeMap[V].getNode();
6119       FuncInfo.DescribedArgs.set(ArgNo);
6120     }
6121   }
6122 
6123   bool IsIndirect = false;
6124   std::optional<MachineOperand> Op;
6125   // Some arguments' frame index is recorded during argument lowering.
6126   int FI = FuncInfo.getArgumentFrameIndex(Arg);
6127   if (FI != std::numeric_limits<int>::max())
6128     Op = MachineOperand::CreateFI(FI);
6129 
6130   SmallVector<std::pair<Register, TypeSize>, 8> ArgRegsAndSizes;
6131   if (!Op && N.getNode()) {
6132     getUnderlyingArgRegs(ArgRegsAndSizes, N);
6133     Register Reg;
6134     if (ArgRegsAndSizes.size() == 1)
6135       Reg = ArgRegsAndSizes.front().first;
6136 
6137     if (Reg && Reg.isVirtual()) {
6138       MachineRegisterInfo &RegInfo = MF.getRegInfo();
6139       Register PR = RegInfo.getLiveInPhysReg(Reg);
6140       if (PR)
6141         Reg = PR;
6142     }
6143     if (Reg) {
6144       Op = MachineOperand::CreateReg(Reg, false);
6145       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6146     }
6147   }
6148 
6149   if (!Op && N.getNode()) {
6150     // Check if frame index is available.
6151     SDValue LCandidate = peekThroughBitcasts(N);
6152     if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(LCandidate.getNode()))
6153       if (FrameIndexSDNode *FINode =
6154           dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6155         Op = MachineOperand::CreateFI(FINode->getIndex());
6156   }
6157 
6158   if (!Op) {
6159     // Create a DBG_VALUE for each decomposed value in ArgRegs to cover Reg
6160     auto splitMultiRegDbgValue = [&](ArrayRef<std::pair<Register, TypeSize>>
6161                                          SplitRegs) {
6162       unsigned Offset = 0;
6163       for (const auto &RegAndSize : SplitRegs) {
6164         // If the expression is already a fragment, the current register
6165         // offset+size might extend beyond the fragment. In this case, only
6166         // the register bits that are inside the fragment are relevant.
6167         int RegFragmentSizeInBits = RegAndSize.second;
6168         if (auto ExprFragmentInfo = Expr->getFragmentInfo()) {
6169           uint64_t ExprFragmentSizeInBits = ExprFragmentInfo->SizeInBits;
6170           // The register is entirely outside the expression fragment,
6171           // so is irrelevant for debug info.
6172           if (Offset >= ExprFragmentSizeInBits)
6173             break;
6174           // The register is partially outside the expression fragment, only
6175           // the low bits within the fragment are relevant for debug info.
6176           if (Offset + RegFragmentSizeInBits > ExprFragmentSizeInBits) {
6177             RegFragmentSizeInBits = ExprFragmentSizeInBits - Offset;
6178           }
6179         }
6180 
6181         auto FragmentExpr = DIExpression::createFragmentExpression(
6182             Expr, Offset, RegFragmentSizeInBits);
6183         Offset += RegAndSize.second;
6184         // If a valid fragment expression cannot be created, the variable's
6185         // correct value cannot be determined and so it is set as Undef.
6186         if (!FragmentExpr) {
6187           SDDbgValue *SDV = DAG.getConstantDbgValue(
6188               Variable, Expr, UndefValue::get(V->getType()), DL, SDNodeOrder);
6189           DAG.AddDbgValue(SDV, false);
6190           continue;
6191         }
6192         MachineInstr *NewMI =
6193             MakeVRegDbgValue(RegAndSize.first, *FragmentExpr,
6194                              Kind != FuncArgumentDbgValueKind::Value);
6195         FuncInfo.ArgDbgValues.push_back(NewMI);
6196       }
6197     };
6198 
6199     // Check if ValueMap has reg number.
6200     DenseMap<const Value *, Register>::const_iterator
6201       VMI = FuncInfo.ValueMap.find(V);
6202     if (VMI != FuncInfo.ValueMap.end()) {
6203       const auto &TLI = DAG.getTargetLoweringInfo();
6204       RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), VMI->second,
6205                        V->getType(), std::nullopt);
6206       if (RFV.occupiesMultipleRegs()) {
6207         splitMultiRegDbgValue(RFV.getRegsAndSizes());
6208         return true;
6209       }
6210 
6211       Op = MachineOperand::CreateReg(VMI->second, false);
6212       IsIndirect = Kind != FuncArgumentDbgValueKind::Value;
6213     } else if (ArgRegsAndSizes.size() > 1) {
6214       // This was split due to the calling convention, and no virtual register
6215       // mapping exists for the value.
6216       splitMultiRegDbgValue(ArgRegsAndSizes);
6217       return true;
6218     }
6219   }
6220 
6221   if (!Op)
6222     return false;
6223 
6224   assert(Variable->isValidLocationForIntrinsic(DL) &&
6225          "Expected inlined-at fields to agree");
6226   MachineInstr *NewMI = nullptr;
6227 
6228   if (Op->isReg())
6229     NewMI = MakeVRegDbgValue(Op->getReg(), Expr, IsIndirect);
6230   else
6231     NewMI = BuildMI(MF, DL, TII->get(TargetOpcode::DBG_VALUE), true, *Op,
6232                     Variable, Expr);
6233 
6234   // Otherwise, use ArgDbgValues.
6235   FuncInfo.ArgDbgValues.push_back(NewMI);
6236   return true;
6237 }
6238 
6239 /// Return the appropriate SDDbgValue based on N.
6240 SDDbgValue *SelectionDAGBuilder::getDbgValue(SDValue N,
6241                                              DILocalVariable *Variable,
6242                                              DIExpression *Expr,
6243                                              const DebugLoc &dl,
6244                                              unsigned DbgSDNodeOrder) {
6245   if (auto *FISDN = dyn_cast<FrameIndexSDNode>(N.getNode())) {
6246     // Construct a FrameIndexDbgValue for FrameIndexSDNodes so we can describe
6247     // stack slot locations.
6248     //
6249     // Consider "int x = 0; int *px = &x;". There are two kinds of interesting
6250     // debug values here after optimization:
6251     //
6252     //   dbg.value(i32* %px, !"int *px", !DIExpression()), and
6253     //   dbg.value(i32* %px, !"int x", !DIExpression(DW_OP_deref))
6254     //
6255     // Both describe the direct values of their associated variables.
6256     return DAG.getFrameIndexDbgValue(Variable, Expr, FISDN->getIndex(),
6257                                      /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6258   }
6259   return DAG.getDbgValue(Variable, Expr, N.getNode(), N.getResNo(),
6260                          /*IsIndirect*/ false, dl, DbgSDNodeOrder);
6261 }
6262 
6263 static unsigned FixedPointIntrinsicToOpcode(unsigned Intrinsic) {
6264   switch (Intrinsic) {
6265   case Intrinsic::smul_fix:
6266     return ISD::SMULFIX;
6267   case Intrinsic::umul_fix:
6268     return ISD::UMULFIX;
6269   case Intrinsic::smul_fix_sat:
6270     return ISD::SMULFIXSAT;
6271   case Intrinsic::umul_fix_sat:
6272     return ISD::UMULFIXSAT;
6273   case Intrinsic::sdiv_fix:
6274     return ISD::SDIVFIX;
6275   case Intrinsic::udiv_fix:
6276     return ISD::UDIVFIX;
6277   case Intrinsic::sdiv_fix_sat:
6278     return ISD::SDIVFIXSAT;
6279   case Intrinsic::udiv_fix_sat:
6280     return ISD::UDIVFIXSAT;
6281   default:
6282     llvm_unreachable("Unhandled fixed point intrinsic");
6283   }
6284 }
6285 
6286 void SelectionDAGBuilder::lowerCallToExternalSymbol(const CallInst &I,
6287                                            const char *FunctionName) {
6288   assert(FunctionName && "FunctionName must not be nullptr");
6289   SDValue Callee = DAG.getExternalSymbol(
6290       FunctionName,
6291       DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout()));
6292   LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
6293 }
6294 
6295 /// Given a @llvm.call.preallocated.setup, return the corresponding
6296 /// preallocated call.
6297 static const CallBase *FindPreallocatedCall(const Value *PreallocatedSetup) {
6298   assert(cast<CallBase>(PreallocatedSetup)
6299                  ->getCalledFunction()
6300                  ->getIntrinsicID() == Intrinsic::call_preallocated_setup &&
6301          "expected call_preallocated_setup Value");
6302   for (const auto *U : PreallocatedSetup->users()) {
6303     auto *UseCall = cast<CallBase>(U);
6304     const Function *Fn = UseCall->getCalledFunction();
6305     if (!Fn || Fn->getIntrinsicID() != Intrinsic::call_preallocated_arg) {
6306       return UseCall;
6307     }
6308   }
6309   llvm_unreachable("expected corresponding call to preallocated setup/arg");
6310 }
6311 
6312 /// If DI is a debug value with an EntryValue expression, lower it using the
6313 /// corresponding physical register of the associated Argument value
6314 /// (guaranteed to exist by the verifier).
6315 bool SelectionDAGBuilder::visitEntryValueDbgValue(
6316     ArrayRef<const Value *> Values, DILocalVariable *Variable,
6317     DIExpression *Expr, DebugLoc DbgLoc) {
6318   if (!Expr->isEntryValue() || !hasSingleElement(Values))
6319     return false;
6320 
6321   // These properties are guaranteed by the verifier.
6322   const Argument *Arg = cast<Argument>(Values[0]);
6323   assert(Arg->hasAttribute(Attribute::AttrKind::SwiftAsync));
6324 
6325   auto ArgIt = FuncInfo.ValueMap.find(Arg);
6326   if (ArgIt == FuncInfo.ValueMap.end()) {
6327     LLVM_DEBUG(
6328         dbgs() << "Dropping dbg.value: expression is entry_value but "
6329                   "couldn't find an associated register for the Argument\n");
6330     return true;
6331   }
6332   Register ArgVReg = ArgIt->getSecond();
6333 
6334   for (auto [PhysReg, VirtReg] : FuncInfo.RegInfo->liveins())
6335     if (ArgVReg == VirtReg || ArgVReg == PhysReg) {
6336       SDDbgValue *SDV = DAG.getVRegDbgValue(
6337           Variable, Expr, PhysReg, false /*IsIndidrect*/, DbgLoc, SDNodeOrder);
6338       DAG.AddDbgValue(SDV, false /*treat as dbg.declare byval parameter*/);
6339       return true;
6340     }
6341   LLVM_DEBUG(dbgs() << "Dropping dbg.value: expression is entry_value but "
6342                        "couldn't find a physical register\n");
6343   return true;
6344 }
6345 
6346 /// Lower the call to the specified intrinsic function.
6347 void SelectionDAGBuilder::visitConvergenceControl(const CallInst &I,
6348                                                   unsigned Intrinsic) {
6349   SDLoc sdl = getCurSDLoc();
6350   switch (Intrinsic) {
6351   case Intrinsic::experimental_convergence_anchor:
6352     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ANCHOR, sdl, MVT::Untyped));
6353     break;
6354   case Intrinsic::experimental_convergence_entry:
6355     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_ENTRY, sdl, MVT::Untyped));
6356     break;
6357   case Intrinsic::experimental_convergence_loop: {
6358     auto Bundle = I.getOperandBundle(LLVMContext::OB_convergencectrl);
6359     auto *Token = Bundle->Inputs[0].get();
6360     setValue(&I, DAG.getNode(ISD::CONVERGENCECTRL_LOOP, sdl, MVT::Untyped,
6361                              getValue(Token)));
6362     break;
6363   }
6364   }
6365 }
6366 
6367 void SelectionDAGBuilder::visitVectorHistogram(const CallInst &I,
6368                                                unsigned IntrinsicID) {
6369   // For now, we're only lowering an 'add' histogram.
6370   // We can add others later, e.g. saturating adds, min/max.
6371   assert(IntrinsicID == Intrinsic::experimental_vector_histogram_add &&
6372          "Tried to lower unsupported histogram type");
6373   SDLoc sdl = getCurSDLoc();
6374   Value *Ptr = I.getOperand(0);
6375   SDValue Inc = getValue(I.getOperand(1));
6376   SDValue Mask = getValue(I.getOperand(2));
6377 
6378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6379   DataLayout TargetDL = DAG.getDataLayout();
6380   EVT VT = Inc.getValueType();
6381   Align Alignment = DAG.getEVTAlign(VT);
6382 
6383   const MDNode *Ranges = getRangeMetadata(I);
6384 
6385   SDValue Root = DAG.getRoot();
6386   SDValue Base;
6387   SDValue Index;
6388   ISD::MemIndexType IndexType;
6389   SDValue Scale;
6390   bool UniformBase = getUniformBase(Ptr, Base, Index, IndexType, Scale, this,
6391                                     I.getParent(), VT.getScalarStoreSize());
6392 
6393   unsigned AS = Ptr->getType()->getScalarType()->getPointerAddressSpace();
6394 
6395   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
6396       MachinePointerInfo(AS),
6397       MachineMemOperand::MOLoad | MachineMemOperand::MOStore,
6398       MemoryLocation::UnknownSize, Alignment, I.getAAMetadata(), Ranges);
6399 
6400   if (!UniformBase) {
6401     Base = DAG.getConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6402     Index = getValue(Ptr);
6403     IndexType = ISD::SIGNED_SCALED;
6404     Scale =
6405         DAG.getTargetConstant(1, sdl, TLI.getPointerTy(DAG.getDataLayout()));
6406   }
6407 
6408   EVT IdxVT = Index.getValueType();
6409   EVT EltTy = IdxVT.getVectorElementType();
6410   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
6411     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
6412     Index = DAG.getNode(ISD::SIGN_EXTEND, sdl, NewIdxVT, Index);
6413   }
6414 
6415   SDValue ID = DAG.getTargetConstant(IntrinsicID, sdl, MVT::i32);
6416 
6417   SDValue Ops[] = {Root, Inc, Mask, Base, Index, Scale, ID};
6418   SDValue Histogram = DAG.getMaskedHistogram(DAG.getVTList(MVT::Other), VT, sdl,
6419                                              Ops, MMO, IndexType);
6420 
6421   setValue(&I, Histogram);
6422   DAG.setRoot(Histogram);
6423 }
6424 
6425 void SelectionDAGBuilder::visitVectorExtractLastActive(const CallInst &I,
6426                                                        unsigned Intrinsic) {
6427   assert(Intrinsic == Intrinsic::experimental_vector_extract_last_active &&
6428          "Tried lowering invalid vector extract last");
6429   SDLoc sdl = getCurSDLoc();
6430   const DataLayout &Layout = DAG.getDataLayout();
6431   SDValue Data = getValue(I.getOperand(0));
6432   SDValue Mask = getValue(I.getOperand(1));
6433 
6434   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6435   EVT ResVT = TLI.getValueType(Layout, I.getType());
6436 
6437   EVT ExtVT = TLI.getVectorIdxTy(Layout);
6438   SDValue Idx = DAG.getNode(ISD::VECTOR_FIND_LAST_ACTIVE, sdl, ExtVT, Mask);
6439   SDValue Result = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl, ResVT, Data, Idx);
6440 
6441   Value *Default = I.getOperand(2);
6442   if (!isa<PoisonValue>(Default) && !isa<UndefValue>(Default)) {
6443     SDValue PassThru = getValue(Default);
6444     EVT BoolVT = Mask.getValueType().getScalarType();
6445     SDValue AnyActive = DAG.getNode(ISD::VECREDUCE_OR, sdl, BoolVT, Mask);
6446     Result = DAG.getSelect(sdl, ResVT, AnyActive, Result, PassThru);
6447   }
6448 
6449   setValue(&I, Result);
6450 }
6451 
6452 /// Lower the call to the specified intrinsic function.
6453 void SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I,
6454                                              unsigned Intrinsic) {
6455   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6456   SDLoc sdl = getCurSDLoc();
6457   DebugLoc dl = getCurDebugLoc();
6458   SDValue Res;
6459 
6460   SDNodeFlags Flags;
6461   if (auto *FPOp = dyn_cast<FPMathOperator>(&I))
6462     Flags.copyFMF(*FPOp);
6463 
6464   switch (Intrinsic) {
6465   default:
6466     // By default, turn this into a target intrinsic node.
6467     visitTargetIntrinsic(I, Intrinsic);
6468     return;
6469   case Intrinsic::vscale: {
6470     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6471     setValue(&I, DAG.getVScale(sdl, VT, APInt(VT.getSizeInBits(), 1)));
6472     return;
6473   }
6474   case Intrinsic::vastart:  visitVAStart(I); return;
6475   case Intrinsic::vaend:    visitVAEnd(I); return;
6476   case Intrinsic::vacopy:   visitVACopy(I); return;
6477   case Intrinsic::returnaddress:
6478     setValue(&I, DAG.getNode(ISD::RETURNADDR, sdl,
6479                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
6480                              getValue(I.getArgOperand(0))));
6481     return;
6482   case Intrinsic::addressofreturnaddress:
6483     setValue(&I,
6484              DAG.getNode(ISD::ADDROFRETURNADDR, sdl,
6485                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6486     return;
6487   case Intrinsic::sponentry:
6488     setValue(&I,
6489              DAG.getNode(ISD::SPONENTRY, sdl,
6490                          TLI.getValueType(DAG.getDataLayout(), I.getType())));
6491     return;
6492   case Intrinsic::frameaddress:
6493     setValue(&I, DAG.getNode(ISD::FRAMEADDR, sdl,
6494                              TLI.getFrameIndexTy(DAG.getDataLayout()),
6495                              getValue(I.getArgOperand(0))));
6496     return;
6497   case Intrinsic::read_volatile_register:
6498   case Intrinsic::read_register: {
6499     Value *Reg = I.getArgOperand(0);
6500     SDValue Chain = getRoot();
6501     SDValue RegName =
6502         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6503     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6504     Res = DAG.getNode(ISD::READ_REGISTER, sdl,
6505       DAG.getVTList(VT, MVT::Other), Chain, RegName);
6506     setValue(&I, Res);
6507     DAG.setRoot(Res.getValue(1));
6508     return;
6509   }
6510   case Intrinsic::write_register: {
6511     Value *Reg = I.getArgOperand(0);
6512     Value *RegValue = I.getArgOperand(1);
6513     SDValue Chain = getRoot();
6514     SDValue RegName =
6515         DAG.getMDNode(cast<MDNode>(cast<MetadataAsValue>(Reg)->getMetadata()));
6516     DAG.setRoot(DAG.getNode(ISD::WRITE_REGISTER, sdl, MVT::Other, Chain,
6517                             RegName, getValue(RegValue)));
6518     return;
6519   }
6520   case Intrinsic::memcpy: {
6521     const auto &MCI = cast<MemCpyInst>(I);
6522     SDValue Op1 = getValue(I.getArgOperand(0));
6523     SDValue Op2 = getValue(I.getArgOperand(1));
6524     SDValue Op3 = getValue(I.getArgOperand(2));
6525     // @llvm.memcpy defines 0 and 1 to both mean no alignment.
6526     Align DstAlign = MCI.getDestAlign().valueOrOne();
6527     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6528     Align Alignment = std::min(DstAlign, SrcAlign);
6529     bool isVol = MCI.isVolatile();
6530     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6531     // node.
6532     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6533     SDValue MC = DAG.getMemcpy(Root, sdl, Op1, Op2, Op3, Alignment, isVol,
6534                                /* AlwaysInline */ false, &I, std::nullopt,
6535                                MachinePointerInfo(I.getArgOperand(0)),
6536                                MachinePointerInfo(I.getArgOperand(1)),
6537                                I.getAAMetadata(), BatchAA);
6538     updateDAGForMaybeTailCall(MC);
6539     return;
6540   }
6541   case Intrinsic::memcpy_inline: {
6542     const auto &MCI = cast<MemCpyInlineInst>(I);
6543     SDValue Dst = getValue(I.getArgOperand(0));
6544     SDValue Src = getValue(I.getArgOperand(1));
6545     SDValue Size = getValue(I.getArgOperand(2));
6546     assert(isa<ConstantSDNode>(Size) && "memcpy_inline needs constant size");
6547     // @llvm.memcpy.inline defines 0 and 1 to both mean no alignment.
6548     Align DstAlign = MCI.getDestAlign().valueOrOne();
6549     Align SrcAlign = MCI.getSourceAlign().valueOrOne();
6550     Align Alignment = std::min(DstAlign, SrcAlign);
6551     bool isVol = MCI.isVolatile();
6552     // FIXME: Support passing different dest/src alignments to the memcpy DAG
6553     // node.
6554     SDValue MC = DAG.getMemcpy(getRoot(), sdl, Dst, Src, Size, Alignment, isVol,
6555                                /* AlwaysInline */ true, &I, std::nullopt,
6556                                MachinePointerInfo(I.getArgOperand(0)),
6557                                MachinePointerInfo(I.getArgOperand(1)),
6558                                I.getAAMetadata(), BatchAA);
6559     updateDAGForMaybeTailCall(MC);
6560     return;
6561   }
6562   case Intrinsic::memset: {
6563     const auto &MSI = cast<MemSetInst>(I);
6564     SDValue Op1 = getValue(I.getArgOperand(0));
6565     SDValue Op2 = getValue(I.getArgOperand(1));
6566     SDValue Op3 = getValue(I.getArgOperand(2));
6567     // @llvm.memset defines 0 and 1 to both mean no alignment.
6568     Align Alignment = MSI.getDestAlign().valueOrOne();
6569     bool isVol = MSI.isVolatile();
6570     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6571     SDValue MS = DAG.getMemset(
6572         Root, sdl, Op1, Op2, Op3, Alignment, isVol, /* AlwaysInline */ false,
6573         &I, MachinePointerInfo(I.getArgOperand(0)), I.getAAMetadata());
6574     updateDAGForMaybeTailCall(MS);
6575     return;
6576   }
6577   case Intrinsic::memset_inline: {
6578     const auto &MSII = cast<MemSetInlineInst>(I);
6579     SDValue Dst = getValue(I.getArgOperand(0));
6580     SDValue Value = getValue(I.getArgOperand(1));
6581     SDValue Size = getValue(I.getArgOperand(2));
6582     assert(isa<ConstantSDNode>(Size) && "memset_inline needs constant size");
6583     // @llvm.memset defines 0 and 1 to both mean no alignment.
6584     Align DstAlign = MSII.getDestAlign().valueOrOne();
6585     bool isVol = MSII.isVolatile();
6586     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6587     SDValue MC = DAG.getMemset(Root, sdl, Dst, Value, Size, DstAlign, isVol,
6588                                /* AlwaysInline */ true, &I,
6589                                MachinePointerInfo(I.getArgOperand(0)),
6590                                I.getAAMetadata());
6591     updateDAGForMaybeTailCall(MC);
6592     return;
6593   }
6594   case Intrinsic::memmove: {
6595     const auto &MMI = cast<MemMoveInst>(I);
6596     SDValue Op1 = getValue(I.getArgOperand(0));
6597     SDValue Op2 = getValue(I.getArgOperand(1));
6598     SDValue Op3 = getValue(I.getArgOperand(2));
6599     // @llvm.memmove defines 0 and 1 to both mean no alignment.
6600     Align DstAlign = MMI.getDestAlign().valueOrOne();
6601     Align SrcAlign = MMI.getSourceAlign().valueOrOne();
6602     Align Alignment = std::min(DstAlign, SrcAlign);
6603     bool isVol = MMI.isVolatile();
6604     // FIXME: Support passing different dest/src alignments to the memmove DAG
6605     // node.
6606     SDValue Root = isVol ? getRoot() : getMemoryRoot();
6607     SDValue MM = DAG.getMemmove(Root, sdl, Op1, Op2, Op3, Alignment, isVol, &I,
6608                                 /* OverrideTailCall */ std::nullopt,
6609                                 MachinePointerInfo(I.getArgOperand(0)),
6610                                 MachinePointerInfo(I.getArgOperand(1)),
6611                                 I.getAAMetadata(), BatchAA);
6612     updateDAGForMaybeTailCall(MM);
6613     return;
6614   }
6615   case Intrinsic::memcpy_element_unordered_atomic: {
6616     const AtomicMemCpyInst &MI = cast<AtomicMemCpyInst>(I);
6617     SDValue Dst = getValue(MI.getRawDest());
6618     SDValue Src = getValue(MI.getRawSource());
6619     SDValue Length = getValue(MI.getLength());
6620 
6621     Type *LengthTy = MI.getLength()->getType();
6622     unsigned ElemSz = MI.getElementSizeInBytes();
6623     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6624     SDValue MC =
6625         DAG.getAtomicMemcpy(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6626                             isTC, MachinePointerInfo(MI.getRawDest()),
6627                             MachinePointerInfo(MI.getRawSource()));
6628     updateDAGForMaybeTailCall(MC);
6629     return;
6630   }
6631   case Intrinsic::memmove_element_unordered_atomic: {
6632     auto &MI = cast<AtomicMemMoveInst>(I);
6633     SDValue Dst = getValue(MI.getRawDest());
6634     SDValue Src = getValue(MI.getRawSource());
6635     SDValue Length = getValue(MI.getLength());
6636 
6637     Type *LengthTy = MI.getLength()->getType();
6638     unsigned ElemSz = MI.getElementSizeInBytes();
6639     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6640     SDValue MC =
6641         DAG.getAtomicMemmove(getRoot(), sdl, Dst, Src, Length, LengthTy, ElemSz,
6642                              isTC, MachinePointerInfo(MI.getRawDest()),
6643                              MachinePointerInfo(MI.getRawSource()));
6644     updateDAGForMaybeTailCall(MC);
6645     return;
6646   }
6647   case Intrinsic::memset_element_unordered_atomic: {
6648     auto &MI = cast<AtomicMemSetInst>(I);
6649     SDValue Dst = getValue(MI.getRawDest());
6650     SDValue Val = getValue(MI.getValue());
6651     SDValue Length = getValue(MI.getLength());
6652 
6653     Type *LengthTy = MI.getLength()->getType();
6654     unsigned ElemSz = MI.getElementSizeInBytes();
6655     bool isTC = I.isTailCall() && isInTailCallPosition(I, DAG.getTarget());
6656     SDValue MC =
6657         DAG.getAtomicMemset(getRoot(), sdl, Dst, Val, Length, LengthTy, ElemSz,
6658                             isTC, MachinePointerInfo(MI.getRawDest()));
6659     updateDAGForMaybeTailCall(MC);
6660     return;
6661   }
6662   case Intrinsic::call_preallocated_setup: {
6663     const CallBase *PreallocatedCall = FindPreallocatedCall(&I);
6664     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6665     SDValue Res = DAG.getNode(ISD::PREALLOCATED_SETUP, sdl, MVT::Other,
6666                               getRoot(), SrcValue);
6667     setValue(&I, Res);
6668     DAG.setRoot(Res);
6669     return;
6670   }
6671   case Intrinsic::call_preallocated_arg: {
6672     const CallBase *PreallocatedCall = FindPreallocatedCall(I.getOperand(0));
6673     SDValue SrcValue = DAG.getSrcValue(PreallocatedCall);
6674     SDValue Ops[3];
6675     Ops[0] = getRoot();
6676     Ops[1] = SrcValue;
6677     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
6678                                    MVT::i32); // arg index
6679     SDValue Res = DAG.getNode(
6680         ISD::PREALLOCATED_ARG, sdl,
6681         DAG.getVTList(TLI.getPointerTy(DAG.getDataLayout()), MVT::Other), Ops);
6682     setValue(&I, Res);
6683     DAG.setRoot(Res.getValue(1));
6684     return;
6685   }
6686   case Intrinsic::dbg_declare: {
6687     const auto &DI = cast<DbgDeclareInst>(I);
6688     // Debug intrinsics are handled separately in assignment tracking mode.
6689     // Some intrinsics are handled right after Argument lowering.
6690     if (AssignmentTrackingEnabled ||
6691         FuncInfo.PreprocessedDbgDeclares.count(&DI))
6692       return;
6693     LLVM_DEBUG(dbgs() << "SelectionDAG visiting dbg_declare: " << DI << "\n");
6694     DILocalVariable *Variable = DI.getVariable();
6695     DIExpression *Expression = DI.getExpression();
6696     dropDanglingDebugInfo(Variable, Expression);
6697     // Assume dbg.declare can not currently use DIArgList, i.e.
6698     // it is non-variadic.
6699     assert(!DI.hasArgList() && "Only dbg.value should currently use DIArgList");
6700     handleDebugDeclare(DI.getVariableLocationOp(0), Variable, Expression,
6701                        DI.getDebugLoc());
6702     return;
6703   }
6704   case Intrinsic::dbg_label: {
6705     const DbgLabelInst &DI = cast<DbgLabelInst>(I);
6706     DILabel *Label = DI.getLabel();
6707     assert(Label && "Missing label");
6708 
6709     SDDbgLabel *SDV;
6710     SDV = DAG.getDbgLabel(Label, dl, SDNodeOrder);
6711     DAG.AddDbgLabel(SDV);
6712     return;
6713   }
6714   case Intrinsic::dbg_assign: {
6715     // Debug intrinsics are handled separately in assignment tracking mode.
6716     if (AssignmentTrackingEnabled)
6717       return;
6718     // If assignment tracking hasn't been enabled then fall through and treat
6719     // the dbg.assign as a dbg.value.
6720     [[fallthrough]];
6721   }
6722   case Intrinsic::dbg_value: {
6723     // Debug intrinsics are handled separately in assignment tracking mode.
6724     if (AssignmentTrackingEnabled)
6725       return;
6726     const DbgValueInst &DI = cast<DbgValueInst>(I);
6727     assert(DI.getVariable() && "Missing variable");
6728 
6729     DILocalVariable *Variable = DI.getVariable();
6730     DIExpression *Expression = DI.getExpression();
6731     dropDanglingDebugInfo(Variable, Expression);
6732 
6733     if (DI.isKillLocation()) {
6734       handleKillDebugValue(Variable, Expression, DI.getDebugLoc(), SDNodeOrder);
6735       return;
6736     }
6737 
6738     SmallVector<Value *, 4> Values(DI.getValues());
6739     if (Values.empty())
6740       return;
6741 
6742     bool IsVariadic = DI.hasArgList();
6743     if (!handleDebugValue(Values, Variable, Expression, DI.getDebugLoc(),
6744                           SDNodeOrder, IsVariadic))
6745       addDanglingDebugInfo(Values, Variable, Expression, IsVariadic,
6746                            DI.getDebugLoc(), SDNodeOrder);
6747     return;
6748   }
6749 
6750   case Intrinsic::eh_typeid_for: {
6751     // Find the type id for the given typeinfo.
6752     GlobalValue *GV = ExtractTypeInfo(I.getArgOperand(0));
6753     unsigned TypeID = DAG.getMachineFunction().getTypeIDFor(GV);
6754     Res = DAG.getConstant(TypeID, sdl, MVT::i32);
6755     setValue(&I, Res);
6756     return;
6757   }
6758 
6759   case Intrinsic::eh_return_i32:
6760   case Intrinsic::eh_return_i64:
6761     DAG.getMachineFunction().setCallsEHReturn(true);
6762     DAG.setRoot(DAG.getNode(ISD::EH_RETURN, sdl,
6763                             MVT::Other,
6764                             getControlRoot(),
6765                             getValue(I.getArgOperand(0)),
6766                             getValue(I.getArgOperand(1))));
6767     return;
6768   case Intrinsic::eh_unwind_init:
6769     DAG.getMachineFunction().setCallsUnwindInit(true);
6770     return;
6771   case Intrinsic::eh_dwarf_cfa:
6772     setValue(&I, DAG.getNode(ISD::EH_DWARF_CFA, sdl,
6773                              TLI.getPointerTy(DAG.getDataLayout()),
6774                              getValue(I.getArgOperand(0))));
6775     return;
6776   case Intrinsic::eh_sjlj_callsite: {
6777     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(0));
6778     assert(FuncInfo.getCurrentCallSite() == 0 && "Overlapping call sites!");
6779 
6780     FuncInfo.setCurrentCallSite(CI->getZExtValue());
6781     return;
6782   }
6783   case Intrinsic::eh_sjlj_functioncontext: {
6784     // Get and store the index of the function context.
6785     MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6786     AllocaInst *FnCtx =
6787       cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
6788     int FI = FuncInfo.StaticAllocaMap[FnCtx];
6789     MFI.setFunctionContextIndex(FI);
6790     return;
6791   }
6792   case Intrinsic::eh_sjlj_setjmp: {
6793     SDValue Ops[2];
6794     Ops[0] = getRoot();
6795     Ops[1] = getValue(I.getArgOperand(0));
6796     SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, sdl,
6797                              DAG.getVTList(MVT::i32, MVT::Other), Ops);
6798     setValue(&I, Op.getValue(0));
6799     DAG.setRoot(Op.getValue(1));
6800     return;
6801   }
6802   case Intrinsic::eh_sjlj_longjmp:
6803     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, sdl, MVT::Other,
6804                             getRoot(), getValue(I.getArgOperand(0))));
6805     return;
6806   case Intrinsic::eh_sjlj_setup_dispatch:
6807     DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_SETUP_DISPATCH, sdl, MVT::Other,
6808                             getRoot()));
6809     return;
6810   case Intrinsic::masked_gather:
6811     visitMaskedGather(I);
6812     return;
6813   case Intrinsic::masked_load:
6814     visitMaskedLoad(I);
6815     return;
6816   case Intrinsic::masked_scatter:
6817     visitMaskedScatter(I);
6818     return;
6819   case Intrinsic::masked_store:
6820     visitMaskedStore(I);
6821     return;
6822   case Intrinsic::masked_expandload:
6823     visitMaskedLoad(I, true /* IsExpanding */);
6824     return;
6825   case Intrinsic::masked_compressstore:
6826     visitMaskedStore(I, true /* IsCompressing */);
6827     return;
6828   case Intrinsic::powi:
6829     setValue(&I, ExpandPowI(sdl, getValue(I.getArgOperand(0)),
6830                             getValue(I.getArgOperand(1)), DAG));
6831     return;
6832   case Intrinsic::log:
6833     setValue(&I, expandLog(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6834     return;
6835   case Intrinsic::log2:
6836     setValue(&I,
6837              expandLog2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6838     return;
6839   case Intrinsic::log10:
6840     setValue(&I,
6841              expandLog10(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6842     return;
6843   case Intrinsic::exp:
6844     setValue(&I, expandExp(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6845     return;
6846   case Intrinsic::exp2:
6847     setValue(&I,
6848              expandExp2(sdl, getValue(I.getArgOperand(0)), DAG, TLI, Flags));
6849     return;
6850   case Intrinsic::pow:
6851     setValue(&I, expandPow(sdl, getValue(I.getArgOperand(0)),
6852                            getValue(I.getArgOperand(1)), DAG, TLI, Flags));
6853     return;
6854   case Intrinsic::sqrt:
6855   case Intrinsic::fabs:
6856   case Intrinsic::sin:
6857   case Intrinsic::cos:
6858   case Intrinsic::tan:
6859   case Intrinsic::asin:
6860   case Intrinsic::acos:
6861   case Intrinsic::atan:
6862   case Intrinsic::sinh:
6863   case Intrinsic::cosh:
6864   case Intrinsic::tanh:
6865   case Intrinsic::exp10:
6866   case Intrinsic::floor:
6867   case Intrinsic::ceil:
6868   case Intrinsic::trunc:
6869   case Intrinsic::rint:
6870   case Intrinsic::nearbyint:
6871   case Intrinsic::round:
6872   case Intrinsic::roundeven:
6873   case Intrinsic::canonicalize: {
6874     unsigned Opcode;
6875     // clang-format off
6876     switch (Intrinsic) {
6877     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6878     case Intrinsic::sqrt:         Opcode = ISD::FSQRT;         break;
6879     case Intrinsic::fabs:         Opcode = ISD::FABS;          break;
6880     case Intrinsic::sin:          Opcode = ISD::FSIN;          break;
6881     case Intrinsic::cos:          Opcode = ISD::FCOS;          break;
6882     case Intrinsic::tan:          Opcode = ISD::FTAN;          break;
6883     case Intrinsic::asin:         Opcode = ISD::FASIN;         break;
6884     case Intrinsic::acos:         Opcode = ISD::FACOS;         break;
6885     case Intrinsic::atan:         Opcode = ISD::FATAN;         break;
6886     case Intrinsic::sinh:         Opcode = ISD::FSINH;         break;
6887     case Intrinsic::cosh:         Opcode = ISD::FCOSH;         break;
6888     case Intrinsic::tanh:         Opcode = ISD::FTANH;         break;
6889     case Intrinsic::exp10:        Opcode = ISD::FEXP10;        break;
6890     case Intrinsic::floor:        Opcode = ISD::FFLOOR;        break;
6891     case Intrinsic::ceil:         Opcode = ISD::FCEIL;         break;
6892     case Intrinsic::trunc:        Opcode = ISD::FTRUNC;        break;
6893     case Intrinsic::rint:         Opcode = ISD::FRINT;         break;
6894     case Intrinsic::nearbyint:    Opcode = ISD::FNEARBYINT;    break;
6895     case Intrinsic::round:        Opcode = ISD::FROUND;        break;
6896     case Intrinsic::roundeven:    Opcode = ISD::FROUNDEVEN;    break;
6897     case Intrinsic::canonicalize: Opcode = ISD::FCANONICALIZE; break;
6898     }
6899     // clang-format on
6900 
6901     setValue(&I, DAG.getNode(Opcode, sdl,
6902                              getValue(I.getArgOperand(0)).getValueType(),
6903                              getValue(I.getArgOperand(0)), Flags));
6904     return;
6905   }
6906   case Intrinsic::atan2:
6907     setValue(&I, DAG.getNode(ISD::FATAN2, sdl,
6908                              getValue(I.getArgOperand(0)).getValueType(),
6909                              getValue(I.getArgOperand(0)),
6910                              getValue(I.getArgOperand(1)), Flags));
6911     return;
6912   case Intrinsic::lround:
6913   case Intrinsic::llround:
6914   case Intrinsic::lrint:
6915   case Intrinsic::llrint: {
6916     unsigned Opcode;
6917     // clang-format off
6918     switch (Intrinsic) {
6919     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
6920     case Intrinsic::lround:  Opcode = ISD::LROUND;  break;
6921     case Intrinsic::llround: Opcode = ISD::LLROUND; break;
6922     case Intrinsic::lrint:   Opcode = ISD::LRINT;   break;
6923     case Intrinsic::llrint:  Opcode = ISD::LLRINT;  break;
6924     }
6925     // clang-format on
6926 
6927     EVT RetVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
6928     setValue(&I, DAG.getNode(Opcode, sdl, RetVT,
6929                              getValue(I.getArgOperand(0))));
6930     return;
6931   }
6932   case Intrinsic::minnum:
6933     setValue(&I, DAG.getNode(ISD::FMINNUM, sdl,
6934                              getValue(I.getArgOperand(0)).getValueType(),
6935                              getValue(I.getArgOperand(0)),
6936                              getValue(I.getArgOperand(1)), Flags));
6937     return;
6938   case Intrinsic::maxnum:
6939     setValue(&I, DAG.getNode(ISD::FMAXNUM, sdl,
6940                              getValue(I.getArgOperand(0)).getValueType(),
6941                              getValue(I.getArgOperand(0)),
6942                              getValue(I.getArgOperand(1)), Flags));
6943     return;
6944   case Intrinsic::minimum:
6945     setValue(&I, DAG.getNode(ISD::FMINIMUM, sdl,
6946                              getValue(I.getArgOperand(0)).getValueType(),
6947                              getValue(I.getArgOperand(0)),
6948                              getValue(I.getArgOperand(1)), Flags));
6949     return;
6950   case Intrinsic::maximum:
6951     setValue(&I, DAG.getNode(ISD::FMAXIMUM, sdl,
6952                              getValue(I.getArgOperand(0)).getValueType(),
6953                              getValue(I.getArgOperand(0)),
6954                              getValue(I.getArgOperand(1)), Flags));
6955     return;
6956   case Intrinsic::minimumnum:
6957     setValue(&I, DAG.getNode(ISD::FMINIMUMNUM, sdl,
6958                              getValue(I.getArgOperand(0)).getValueType(),
6959                              getValue(I.getArgOperand(0)),
6960                              getValue(I.getArgOperand(1)), Flags));
6961     return;
6962   case Intrinsic::maximumnum:
6963     setValue(&I, DAG.getNode(ISD::FMAXIMUMNUM, sdl,
6964                              getValue(I.getArgOperand(0)).getValueType(),
6965                              getValue(I.getArgOperand(0)),
6966                              getValue(I.getArgOperand(1)), Flags));
6967     return;
6968   case Intrinsic::copysign:
6969     setValue(&I, DAG.getNode(ISD::FCOPYSIGN, sdl,
6970                              getValue(I.getArgOperand(0)).getValueType(),
6971                              getValue(I.getArgOperand(0)),
6972                              getValue(I.getArgOperand(1)), Flags));
6973     return;
6974   case Intrinsic::ldexp:
6975     setValue(&I, DAG.getNode(ISD::FLDEXP, sdl,
6976                              getValue(I.getArgOperand(0)).getValueType(),
6977                              getValue(I.getArgOperand(0)),
6978                              getValue(I.getArgOperand(1)), Flags));
6979     return;
6980   case Intrinsic::sincos:
6981   case Intrinsic::frexp: {
6982     unsigned Opcode;
6983     switch (Intrinsic) {
6984     default:
6985       llvm_unreachable("unexpected intrinsic");
6986     case Intrinsic::sincos:
6987       Opcode = ISD::FSINCOS;
6988       break;
6989     case Intrinsic::frexp:
6990       Opcode = ISD::FFREXP;
6991       break;
6992     }
6993     SmallVector<EVT, 2> ValueVTs;
6994     ComputeValueVTs(TLI, DAG.getDataLayout(), I.getType(), ValueVTs);
6995     SDVTList VTs = DAG.getVTList(ValueVTs);
6996     setValue(
6997         &I, DAG.getNode(Opcode, sdl, VTs, getValue(I.getArgOperand(0)), Flags));
6998     return;
6999   }
7000   case Intrinsic::arithmetic_fence: {
7001     setValue(&I, DAG.getNode(ISD::ARITH_FENCE, sdl,
7002                              getValue(I.getArgOperand(0)).getValueType(),
7003                              getValue(I.getArgOperand(0)), Flags));
7004     return;
7005   }
7006   case Intrinsic::fma:
7007     setValue(&I, DAG.getNode(
7008                      ISD::FMA, sdl, getValue(I.getArgOperand(0)).getValueType(),
7009                      getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)),
7010                      getValue(I.getArgOperand(2)), Flags));
7011     return;
7012 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC)                         \
7013   case Intrinsic::INTRINSIC:
7014 #include "llvm/IR/ConstrainedOps.def"
7015     visitConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(I));
7016     return;
7017 #define BEGIN_REGISTER_VP_INTRINSIC(VPID, ...) case Intrinsic::VPID:
7018 #include "llvm/IR/VPIntrinsics.def"
7019     visitVectorPredicationIntrinsic(cast<VPIntrinsic>(I));
7020     return;
7021   case Intrinsic::fptrunc_round: {
7022     // Get the last argument, the metadata and convert it to an integer in the
7023     // call
7024     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(1))->getMetadata();
7025     std::optional<RoundingMode> RoundMode =
7026         convertStrToRoundingMode(cast<MDString>(MD)->getString());
7027 
7028     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7029 
7030     // Propagate fast-math-flags from IR to node(s).
7031     SDNodeFlags Flags;
7032     Flags.copyFMF(*cast<FPMathOperator>(&I));
7033     SelectionDAG::FlagInserter FlagsInserter(DAG, Flags);
7034 
7035     SDValue Result;
7036     Result = DAG.getNode(
7037         ISD::FPTRUNC_ROUND, sdl, VT, getValue(I.getArgOperand(0)),
7038         DAG.getTargetConstant((int)*RoundMode, sdl, MVT::i32));
7039     setValue(&I, Result);
7040 
7041     return;
7042   }
7043   case Intrinsic::fmuladd: {
7044     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7045     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
7046         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
7047       setValue(&I, DAG.getNode(ISD::FMA, sdl,
7048                                getValue(I.getArgOperand(0)).getValueType(),
7049                                getValue(I.getArgOperand(0)),
7050                                getValue(I.getArgOperand(1)),
7051                                getValue(I.getArgOperand(2)), Flags));
7052     } else {
7053       // TODO: Intrinsic calls should have fast-math-flags.
7054       SDValue Mul = DAG.getNode(
7055           ISD::FMUL, sdl, getValue(I.getArgOperand(0)).getValueType(),
7056           getValue(I.getArgOperand(0)), getValue(I.getArgOperand(1)), Flags);
7057       SDValue Add = DAG.getNode(ISD::FADD, sdl,
7058                                 getValue(I.getArgOperand(0)).getValueType(),
7059                                 Mul, getValue(I.getArgOperand(2)), Flags);
7060       setValue(&I, Add);
7061     }
7062     return;
7063   }
7064   case Intrinsic::convert_to_fp16:
7065     setValue(&I, DAG.getNode(ISD::BITCAST, sdl, MVT::i16,
7066                              DAG.getNode(ISD::FP_ROUND, sdl, MVT::f16,
7067                                          getValue(I.getArgOperand(0)),
7068                                          DAG.getTargetConstant(0, sdl,
7069                                                                MVT::i32))));
7070     return;
7071   case Intrinsic::convert_from_fp16:
7072     setValue(&I, DAG.getNode(ISD::FP_EXTEND, sdl,
7073                              TLI.getValueType(DAG.getDataLayout(), I.getType()),
7074                              DAG.getNode(ISD::BITCAST, sdl, MVT::f16,
7075                                          getValue(I.getArgOperand(0)))));
7076     return;
7077   case Intrinsic::fptosi_sat: {
7078     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7079     setValue(&I, DAG.getNode(ISD::FP_TO_SINT_SAT, sdl, VT,
7080                              getValue(I.getArgOperand(0)),
7081                              DAG.getValueType(VT.getScalarType())));
7082     return;
7083   }
7084   case Intrinsic::fptoui_sat: {
7085     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7086     setValue(&I, DAG.getNode(ISD::FP_TO_UINT_SAT, sdl, VT,
7087                              getValue(I.getArgOperand(0)),
7088                              DAG.getValueType(VT.getScalarType())));
7089     return;
7090   }
7091   case Intrinsic::set_rounding:
7092     Res = DAG.getNode(ISD::SET_ROUNDING, sdl, MVT::Other,
7093                       {getRoot(), getValue(I.getArgOperand(0))});
7094     setValue(&I, Res);
7095     DAG.setRoot(Res.getValue(0));
7096     return;
7097   case Intrinsic::is_fpclass: {
7098     const DataLayout DLayout = DAG.getDataLayout();
7099     EVT DestVT = TLI.getValueType(DLayout, I.getType());
7100     EVT ArgVT = TLI.getValueType(DLayout, I.getArgOperand(0)->getType());
7101     FPClassTest Test = static_cast<FPClassTest>(
7102         cast<ConstantInt>(I.getArgOperand(1))->getZExtValue());
7103     MachineFunction &MF = DAG.getMachineFunction();
7104     const Function &F = MF.getFunction();
7105     SDValue Op = getValue(I.getArgOperand(0));
7106     SDNodeFlags Flags;
7107     Flags.setNoFPExcept(
7108         !F.getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
7109     // If ISD::IS_FPCLASS should be expanded, do it right now, because the
7110     // expansion can use illegal types. Making expansion early allows
7111     // legalizing these types prior to selection.
7112     if (!TLI.isOperationLegal(ISD::IS_FPCLASS, ArgVT) &&
7113         !TLI.isOperationCustom(ISD::IS_FPCLASS, ArgVT)) {
7114       SDValue Result = TLI.expandIS_FPCLASS(DestVT, Op, Test, Flags, sdl, DAG);
7115       setValue(&I, Result);
7116       return;
7117     }
7118 
7119     SDValue Check = DAG.getTargetConstant(Test, sdl, MVT::i32);
7120     SDValue V = DAG.getNode(ISD::IS_FPCLASS, sdl, DestVT, {Op, Check}, Flags);
7121     setValue(&I, V);
7122     return;
7123   }
7124   case Intrinsic::get_fpenv: {
7125     const DataLayout DLayout = DAG.getDataLayout();
7126     EVT EnvVT = TLI.getValueType(DLayout, I.getType());
7127     Align TempAlign = DAG.getEVTAlign(EnvVT);
7128     SDValue Chain = getRoot();
7129     // Use GET_FPENV if it is legal or custom. Otherwise use memory-based node
7130     // and temporary storage in stack.
7131     if (TLI.isOperationLegalOrCustom(ISD::GET_FPENV, EnvVT)) {
7132       Res = DAG.getNode(
7133           ISD::GET_FPENV, sdl,
7134           DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7135                         MVT::Other),
7136           Chain);
7137     } else {
7138       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7139       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7140       auto MPI =
7141           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7142       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7143           MPI, MachineMemOperand::MOStore, LocationSize::beforeOrAfterPointer(),
7144           TempAlign);
7145       Chain = DAG.getGetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7146       Res = DAG.getLoad(EnvVT, sdl, Chain, Temp, MPI);
7147     }
7148     setValue(&I, Res);
7149     DAG.setRoot(Res.getValue(1));
7150     return;
7151   }
7152   case Intrinsic::set_fpenv: {
7153     const DataLayout DLayout = DAG.getDataLayout();
7154     SDValue Env = getValue(I.getArgOperand(0));
7155     EVT EnvVT = Env.getValueType();
7156     Align TempAlign = DAG.getEVTAlign(EnvVT);
7157     SDValue Chain = getRoot();
7158     // If SET_FPENV is custom or legal, use it. Otherwise use loading
7159     // environment from memory.
7160     if (TLI.isOperationLegalOrCustom(ISD::SET_FPENV, EnvVT)) {
7161       Chain = DAG.getNode(ISD::SET_FPENV, sdl, MVT::Other, Chain, Env);
7162     } else {
7163       // Allocate space in stack, copy environment bits into it and use this
7164       // memory in SET_FPENV_MEM.
7165       SDValue Temp = DAG.CreateStackTemporary(EnvVT, TempAlign.value());
7166       int SPFI = cast<FrameIndexSDNode>(Temp.getNode())->getIndex();
7167       auto MPI =
7168           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), SPFI);
7169       Chain = DAG.getStore(Chain, sdl, Env, Temp, MPI, TempAlign,
7170                            MachineMemOperand::MOStore);
7171       MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
7172           MPI, MachineMemOperand::MOLoad, LocationSize::beforeOrAfterPointer(),
7173           TempAlign);
7174       Chain = DAG.getSetFPEnv(Chain, sdl, Temp, EnvVT, MMO);
7175     }
7176     DAG.setRoot(Chain);
7177     return;
7178   }
7179   case Intrinsic::reset_fpenv:
7180     DAG.setRoot(DAG.getNode(ISD::RESET_FPENV, sdl, MVT::Other, getRoot()));
7181     return;
7182   case Intrinsic::get_fpmode:
7183     Res = DAG.getNode(
7184         ISD::GET_FPMODE, sdl,
7185         DAG.getVTList(TLI.getValueType(DAG.getDataLayout(), I.getType()),
7186                       MVT::Other),
7187         DAG.getRoot());
7188     setValue(&I, Res);
7189     DAG.setRoot(Res.getValue(1));
7190     return;
7191   case Intrinsic::set_fpmode:
7192     Res = DAG.getNode(ISD::SET_FPMODE, sdl, MVT::Other, {DAG.getRoot()},
7193                       getValue(I.getArgOperand(0)));
7194     DAG.setRoot(Res);
7195     return;
7196   case Intrinsic::reset_fpmode: {
7197     Res = DAG.getNode(ISD::RESET_FPMODE, sdl, MVT::Other, getRoot());
7198     DAG.setRoot(Res);
7199     return;
7200   }
7201   case Intrinsic::pcmarker: {
7202     SDValue Tmp = getValue(I.getArgOperand(0));
7203     DAG.setRoot(DAG.getNode(ISD::PCMARKER, sdl, MVT::Other, getRoot(), Tmp));
7204     return;
7205   }
7206   case Intrinsic::readcyclecounter: {
7207     SDValue Op = getRoot();
7208     Res = DAG.getNode(ISD::READCYCLECOUNTER, sdl,
7209                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7210     setValue(&I, Res);
7211     DAG.setRoot(Res.getValue(1));
7212     return;
7213   }
7214   case Intrinsic::readsteadycounter: {
7215     SDValue Op = getRoot();
7216     Res = DAG.getNode(ISD::READSTEADYCOUNTER, sdl,
7217                       DAG.getVTList(MVT::i64, MVT::Other), Op);
7218     setValue(&I, Res);
7219     DAG.setRoot(Res.getValue(1));
7220     return;
7221   }
7222   case Intrinsic::bitreverse:
7223     setValue(&I, DAG.getNode(ISD::BITREVERSE, sdl,
7224                              getValue(I.getArgOperand(0)).getValueType(),
7225                              getValue(I.getArgOperand(0))));
7226     return;
7227   case Intrinsic::bswap:
7228     setValue(&I, DAG.getNode(ISD::BSWAP, sdl,
7229                              getValue(I.getArgOperand(0)).getValueType(),
7230                              getValue(I.getArgOperand(0))));
7231     return;
7232   case Intrinsic::cttz: {
7233     SDValue Arg = getValue(I.getArgOperand(0));
7234     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7235     EVT Ty = Arg.getValueType();
7236     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
7237                              sdl, Ty, Arg));
7238     return;
7239   }
7240   case Intrinsic::ctlz: {
7241     SDValue Arg = getValue(I.getArgOperand(0));
7242     ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
7243     EVT Ty = Arg.getValueType();
7244     setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
7245                              sdl, Ty, Arg));
7246     return;
7247   }
7248   case Intrinsic::ctpop: {
7249     SDValue Arg = getValue(I.getArgOperand(0));
7250     EVT Ty = Arg.getValueType();
7251     setValue(&I, DAG.getNode(ISD::CTPOP, sdl, Ty, Arg));
7252     return;
7253   }
7254   case Intrinsic::fshl:
7255   case Intrinsic::fshr: {
7256     bool IsFSHL = Intrinsic == Intrinsic::fshl;
7257     SDValue X = getValue(I.getArgOperand(0));
7258     SDValue Y = getValue(I.getArgOperand(1));
7259     SDValue Z = getValue(I.getArgOperand(2));
7260     EVT VT = X.getValueType();
7261 
7262     if (X == Y) {
7263       auto RotateOpcode = IsFSHL ? ISD::ROTL : ISD::ROTR;
7264       setValue(&I, DAG.getNode(RotateOpcode, sdl, VT, X, Z));
7265     } else {
7266       auto FunnelOpcode = IsFSHL ? ISD::FSHL : ISD::FSHR;
7267       setValue(&I, DAG.getNode(FunnelOpcode, sdl, VT, X, Y, Z));
7268     }
7269     return;
7270   }
7271   case Intrinsic::sadd_sat: {
7272     SDValue Op1 = getValue(I.getArgOperand(0));
7273     SDValue Op2 = getValue(I.getArgOperand(1));
7274     setValue(&I, DAG.getNode(ISD::SADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7275     return;
7276   }
7277   case Intrinsic::uadd_sat: {
7278     SDValue Op1 = getValue(I.getArgOperand(0));
7279     SDValue Op2 = getValue(I.getArgOperand(1));
7280     setValue(&I, DAG.getNode(ISD::UADDSAT, sdl, Op1.getValueType(), Op1, Op2));
7281     return;
7282   }
7283   case Intrinsic::ssub_sat: {
7284     SDValue Op1 = getValue(I.getArgOperand(0));
7285     SDValue Op2 = getValue(I.getArgOperand(1));
7286     setValue(&I, DAG.getNode(ISD::SSUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7287     return;
7288   }
7289   case Intrinsic::usub_sat: {
7290     SDValue Op1 = getValue(I.getArgOperand(0));
7291     SDValue Op2 = getValue(I.getArgOperand(1));
7292     setValue(&I, DAG.getNode(ISD::USUBSAT, sdl, Op1.getValueType(), Op1, Op2));
7293     return;
7294   }
7295   case Intrinsic::sshl_sat: {
7296     SDValue Op1 = getValue(I.getArgOperand(0));
7297     SDValue Op2 = getValue(I.getArgOperand(1));
7298     setValue(&I, DAG.getNode(ISD::SSHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7299     return;
7300   }
7301   case Intrinsic::ushl_sat: {
7302     SDValue Op1 = getValue(I.getArgOperand(0));
7303     SDValue Op2 = getValue(I.getArgOperand(1));
7304     setValue(&I, DAG.getNode(ISD::USHLSAT, sdl, Op1.getValueType(), Op1, Op2));
7305     return;
7306   }
7307   case Intrinsic::smul_fix:
7308   case Intrinsic::umul_fix:
7309   case Intrinsic::smul_fix_sat:
7310   case Intrinsic::umul_fix_sat: {
7311     SDValue Op1 = getValue(I.getArgOperand(0));
7312     SDValue Op2 = getValue(I.getArgOperand(1));
7313     SDValue Op3 = getValue(I.getArgOperand(2));
7314     setValue(&I, DAG.getNode(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7315                              Op1.getValueType(), Op1, Op2, Op3));
7316     return;
7317   }
7318   case Intrinsic::sdiv_fix:
7319   case Intrinsic::udiv_fix:
7320   case Intrinsic::sdiv_fix_sat:
7321   case Intrinsic::udiv_fix_sat: {
7322     SDValue Op1 = getValue(I.getArgOperand(0));
7323     SDValue Op2 = getValue(I.getArgOperand(1));
7324     SDValue Op3 = getValue(I.getArgOperand(2));
7325     setValue(&I, expandDivFix(FixedPointIntrinsicToOpcode(Intrinsic), sdl,
7326                               Op1, Op2, Op3, DAG, TLI));
7327     return;
7328   }
7329   case Intrinsic::smax: {
7330     SDValue Op1 = getValue(I.getArgOperand(0));
7331     SDValue Op2 = getValue(I.getArgOperand(1));
7332     setValue(&I, DAG.getNode(ISD::SMAX, sdl, Op1.getValueType(), Op1, Op2));
7333     return;
7334   }
7335   case Intrinsic::smin: {
7336     SDValue Op1 = getValue(I.getArgOperand(0));
7337     SDValue Op2 = getValue(I.getArgOperand(1));
7338     setValue(&I, DAG.getNode(ISD::SMIN, sdl, Op1.getValueType(), Op1, Op2));
7339     return;
7340   }
7341   case Intrinsic::umax: {
7342     SDValue Op1 = getValue(I.getArgOperand(0));
7343     SDValue Op2 = getValue(I.getArgOperand(1));
7344     setValue(&I, DAG.getNode(ISD::UMAX, sdl, Op1.getValueType(), Op1, Op2));
7345     return;
7346   }
7347   case Intrinsic::umin: {
7348     SDValue Op1 = getValue(I.getArgOperand(0));
7349     SDValue Op2 = getValue(I.getArgOperand(1));
7350     setValue(&I, DAG.getNode(ISD::UMIN, sdl, Op1.getValueType(), Op1, Op2));
7351     return;
7352   }
7353   case Intrinsic::abs: {
7354     // TODO: Preserve "int min is poison" arg in SDAG?
7355     SDValue Op1 = getValue(I.getArgOperand(0));
7356     setValue(&I, DAG.getNode(ISD::ABS, sdl, Op1.getValueType(), Op1));
7357     return;
7358   }
7359   case Intrinsic::scmp: {
7360     SDValue Op1 = getValue(I.getArgOperand(0));
7361     SDValue Op2 = getValue(I.getArgOperand(1));
7362     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7363     setValue(&I, DAG.getNode(ISD::SCMP, sdl, DestVT, Op1, Op2));
7364     break;
7365   }
7366   case Intrinsic::ucmp: {
7367     SDValue Op1 = getValue(I.getArgOperand(0));
7368     SDValue Op2 = getValue(I.getArgOperand(1));
7369     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7370     setValue(&I, DAG.getNode(ISD::UCMP, sdl, DestVT, Op1, Op2));
7371     break;
7372   }
7373   case Intrinsic::stacksave: {
7374     SDValue Op = getRoot();
7375     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
7376     Res = DAG.getNode(ISD::STACKSAVE, sdl, DAG.getVTList(VT, MVT::Other), Op);
7377     setValue(&I, Res);
7378     DAG.setRoot(Res.getValue(1));
7379     return;
7380   }
7381   case Intrinsic::stackrestore:
7382     Res = getValue(I.getArgOperand(0));
7383     DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, sdl, MVT::Other, getRoot(), Res));
7384     return;
7385   case Intrinsic::get_dynamic_area_offset: {
7386     SDValue Op = getRoot();
7387     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7388     EVT ResTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7389     // Result type for @llvm.get.dynamic.area.offset should match PtrTy for
7390     // target.
7391     if (PtrTy.getFixedSizeInBits() < ResTy.getFixedSizeInBits())
7392       report_fatal_error("Wrong result type for @llvm.get.dynamic.area.offset"
7393                          " intrinsic!");
7394     Res = DAG.getNode(ISD::GET_DYNAMIC_AREA_OFFSET, sdl, DAG.getVTList(ResTy),
7395                       Op);
7396     DAG.setRoot(Op);
7397     setValue(&I, Res);
7398     return;
7399   }
7400   case Intrinsic::stackguard: {
7401     MachineFunction &MF = DAG.getMachineFunction();
7402     const Module &M = *MF.getFunction().getParent();
7403     EVT PtrTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
7404     SDValue Chain = getRoot();
7405     if (TLI.useLoadStackGuardNode(M)) {
7406       Res = getLoadStackGuard(DAG, sdl, Chain);
7407       Res = DAG.getPtrExtOrTrunc(Res, sdl, PtrTy);
7408     } else {
7409       const Value *Global = TLI.getSDagStackGuard(M);
7410       Align Align = DAG.getDataLayout().getPrefTypeAlign(Global->getType());
7411       Res = DAG.getLoad(PtrTy, sdl, Chain, getValue(Global),
7412                         MachinePointerInfo(Global, 0), Align,
7413                         MachineMemOperand::MOVolatile);
7414     }
7415     if (TLI.useStackGuardXorFP())
7416       Res = TLI.emitStackGuardXorFP(DAG, Res, sdl);
7417     DAG.setRoot(Chain);
7418     setValue(&I, Res);
7419     return;
7420   }
7421   case Intrinsic::stackprotector: {
7422     // Emit code into the DAG to store the stack guard onto the stack.
7423     MachineFunction &MF = DAG.getMachineFunction();
7424     MachineFrameInfo &MFI = MF.getFrameInfo();
7425     const Module &M = *MF.getFunction().getParent();
7426     SDValue Src, Chain = getRoot();
7427 
7428     if (TLI.useLoadStackGuardNode(M))
7429       Src = getLoadStackGuard(DAG, sdl, Chain);
7430     else
7431       Src = getValue(I.getArgOperand(0));   // The guard's value.
7432 
7433     AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
7434 
7435     int FI = FuncInfo.StaticAllocaMap[Slot];
7436     MFI.setStackProtectorIndex(FI);
7437     EVT PtrTy = TLI.getFrameIndexTy(DAG.getDataLayout());
7438 
7439     SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
7440 
7441     // Store the stack protector onto the stack.
7442     Res = DAG.getStore(
7443         Chain, sdl, Src, FIN,
7444         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
7445         MaybeAlign(), MachineMemOperand::MOVolatile);
7446     setValue(&I, Res);
7447     DAG.setRoot(Res);
7448     return;
7449   }
7450   case Intrinsic::objectsize:
7451     llvm_unreachable("llvm.objectsize.* should have been lowered already");
7452 
7453   case Intrinsic::is_constant:
7454     llvm_unreachable("llvm.is.constant.* should have been lowered already");
7455 
7456   case Intrinsic::annotation:
7457   case Intrinsic::ptr_annotation:
7458   case Intrinsic::launder_invariant_group:
7459   case Intrinsic::strip_invariant_group:
7460     // Drop the intrinsic, but forward the value
7461     setValue(&I, getValue(I.getOperand(0)));
7462     return;
7463 
7464   case Intrinsic::assume:
7465   case Intrinsic::experimental_noalias_scope_decl:
7466   case Intrinsic::var_annotation:
7467   case Intrinsic::sideeffect:
7468     // Discard annotate attributes, noalias scope declarations, assumptions, and
7469     // artificial side-effects.
7470     return;
7471 
7472   case Intrinsic::codeview_annotation: {
7473     // Emit a label associated with this metadata.
7474     MachineFunction &MF = DAG.getMachineFunction();
7475     MCSymbol *Label = MF.getContext().createTempSymbol("annotation", true);
7476     Metadata *MD = cast<MetadataAsValue>(I.getArgOperand(0))->getMetadata();
7477     MF.addCodeViewAnnotation(Label, cast<MDNode>(MD));
7478     Res = DAG.getLabelNode(ISD::ANNOTATION_LABEL, sdl, getRoot(), Label);
7479     DAG.setRoot(Res);
7480     return;
7481   }
7482 
7483   case Intrinsic::init_trampoline: {
7484     const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
7485 
7486     SDValue Ops[6];
7487     Ops[0] = getRoot();
7488     Ops[1] = getValue(I.getArgOperand(0));
7489     Ops[2] = getValue(I.getArgOperand(1));
7490     Ops[3] = getValue(I.getArgOperand(2));
7491     Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
7492     Ops[5] = DAG.getSrcValue(F);
7493 
7494     Res = DAG.getNode(ISD::INIT_TRAMPOLINE, sdl, MVT::Other, Ops);
7495 
7496     DAG.setRoot(Res);
7497     return;
7498   }
7499   case Intrinsic::adjust_trampoline:
7500     setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, sdl,
7501                              TLI.getPointerTy(DAG.getDataLayout()),
7502                              getValue(I.getArgOperand(0))));
7503     return;
7504   case Intrinsic::gcroot: {
7505     assert(DAG.getMachineFunction().getFunction().hasGC() &&
7506            "only valid in functions with gc specified, enforced by Verifier");
7507     assert(GFI && "implied by previous");
7508     const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
7509     const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
7510 
7511     FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
7512     GFI->addStackRoot(FI->getIndex(), TypeMap);
7513     return;
7514   }
7515   case Intrinsic::gcread:
7516   case Intrinsic::gcwrite:
7517     llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
7518   case Intrinsic::get_rounding:
7519     Res = DAG.getNode(ISD::GET_ROUNDING, sdl, {MVT::i32, MVT::Other}, getRoot());
7520     setValue(&I, Res);
7521     DAG.setRoot(Res.getValue(1));
7522     return;
7523 
7524   case Intrinsic::expect:
7525   case Intrinsic::expect_with_probability:
7526     // Just replace __builtin_expect(exp, c) and
7527     // __builtin_expect_with_probability(exp, c, p) with EXP.
7528     setValue(&I, getValue(I.getArgOperand(0)));
7529     return;
7530 
7531   case Intrinsic::ubsantrap:
7532   case Intrinsic::debugtrap:
7533   case Intrinsic::trap: {
7534     StringRef TrapFuncName =
7535         I.getAttributes().getFnAttr("trap-func-name").getValueAsString();
7536     if (TrapFuncName.empty()) {
7537       switch (Intrinsic) {
7538       case Intrinsic::trap:
7539         DAG.setRoot(DAG.getNode(ISD::TRAP, sdl, MVT::Other, getRoot()));
7540         break;
7541       case Intrinsic::debugtrap:
7542         DAG.setRoot(DAG.getNode(ISD::DEBUGTRAP, sdl, MVT::Other, getRoot()));
7543         break;
7544       case Intrinsic::ubsantrap:
7545         DAG.setRoot(DAG.getNode(
7546             ISD::UBSANTRAP, sdl, MVT::Other, getRoot(),
7547             DAG.getTargetConstant(
7548                 cast<ConstantInt>(I.getArgOperand(0))->getZExtValue(), sdl,
7549                 MVT::i32)));
7550         break;
7551       default: llvm_unreachable("unknown trap intrinsic");
7552       }
7553       DAG.addNoMergeSiteInfo(DAG.getRoot().getNode(),
7554                              I.hasFnAttr(Attribute::NoMerge));
7555       return;
7556     }
7557     TargetLowering::ArgListTy Args;
7558     if (Intrinsic == Intrinsic::ubsantrap) {
7559       Args.push_back(TargetLoweringBase::ArgListEntry());
7560       Args[0].Val = I.getArgOperand(0);
7561       Args[0].Node = getValue(Args[0].Val);
7562       Args[0].Ty = Args[0].Val->getType();
7563     }
7564 
7565     TargetLowering::CallLoweringInfo CLI(DAG);
7566     CLI.setDebugLoc(sdl).setChain(getRoot()).setLibCallee(
7567         CallingConv::C, I.getType(),
7568         DAG.getExternalSymbol(TrapFuncName.data(),
7569                               TLI.getPointerTy(DAG.getDataLayout())),
7570         std::move(Args));
7571     CLI.NoMerge = I.hasFnAttr(Attribute::NoMerge);
7572     std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
7573     DAG.setRoot(Result.second);
7574     return;
7575   }
7576 
7577   case Intrinsic::allow_runtime_check:
7578   case Intrinsic::allow_ubsan_check:
7579     setValue(&I, getValue(ConstantInt::getTrue(I.getType())));
7580     return;
7581 
7582   case Intrinsic::uadd_with_overflow:
7583   case Intrinsic::sadd_with_overflow:
7584   case Intrinsic::usub_with_overflow:
7585   case Intrinsic::ssub_with_overflow:
7586   case Intrinsic::umul_with_overflow:
7587   case Intrinsic::smul_with_overflow: {
7588     ISD::NodeType Op;
7589     switch (Intrinsic) {
7590     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
7591     case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
7592     case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
7593     case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
7594     case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
7595     case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
7596     case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
7597     }
7598     SDValue Op1 = getValue(I.getArgOperand(0));
7599     SDValue Op2 = getValue(I.getArgOperand(1));
7600 
7601     EVT ResultVT = Op1.getValueType();
7602     EVT OverflowVT = MVT::i1;
7603     if (ResultVT.isVector())
7604       OverflowVT = EVT::getVectorVT(
7605           *Context, OverflowVT, ResultVT.getVectorElementCount());
7606 
7607     SDVTList VTs = DAG.getVTList(ResultVT, OverflowVT);
7608     setValue(&I, DAG.getNode(Op, sdl, VTs, Op1, Op2));
7609     return;
7610   }
7611   case Intrinsic::prefetch: {
7612     SDValue Ops[5];
7613     unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7614     auto Flags = rw == 0 ? MachineMemOperand::MOLoad :MachineMemOperand::MOStore;
7615     Ops[0] = DAG.getRoot();
7616     Ops[1] = getValue(I.getArgOperand(0));
7617     Ops[2] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(1)), sdl,
7618                                    MVT::i32);
7619     Ops[3] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(2)), sdl,
7620                                    MVT::i32);
7621     Ops[4] = DAG.getTargetConstant(*cast<ConstantInt>(I.getArgOperand(3)), sdl,
7622                                    MVT::i32);
7623     SDValue Result = DAG.getMemIntrinsicNode(
7624         ISD::PREFETCH, sdl, DAG.getVTList(MVT::Other), Ops,
7625         EVT::getIntegerVT(*Context, 8), MachinePointerInfo(I.getArgOperand(0)),
7626         /* align */ std::nullopt, Flags);
7627 
7628     // Chain the prefetch in parallel with any pending loads, to stay out of
7629     // the way of later optimizations.
7630     PendingLoads.push_back(Result);
7631     Result = getRoot();
7632     DAG.setRoot(Result);
7633     return;
7634   }
7635   case Intrinsic::lifetime_start:
7636   case Intrinsic::lifetime_end: {
7637     bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
7638     // Stack coloring is not enabled in O0, discard region information.
7639     if (TM.getOptLevel() == CodeGenOptLevel::None)
7640       return;
7641 
7642     const int64_t ObjectSize =
7643         cast<ConstantInt>(I.getArgOperand(0))->getSExtValue();
7644     Value *const ObjectPtr = I.getArgOperand(1);
7645     SmallVector<const Value *, 4> Allocas;
7646     getUnderlyingObjects(ObjectPtr, Allocas);
7647 
7648     for (const Value *Alloca : Allocas) {
7649       const AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(Alloca);
7650 
7651       // Could not find an Alloca.
7652       if (!LifetimeObject)
7653         continue;
7654 
7655       // First check that the Alloca is static, otherwise it won't have a
7656       // valid frame index.
7657       auto SI = FuncInfo.StaticAllocaMap.find(LifetimeObject);
7658       if (SI == FuncInfo.StaticAllocaMap.end())
7659         return;
7660 
7661       const int FrameIndex = SI->second;
7662       int64_t Offset;
7663       if (GetPointerBaseWithConstantOffset(
7664               ObjectPtr, Offset, DAG.getDataLayout()) != LifetimeObject)
7665         Offset = -1; // Cannot determine offset from alloca to lifetime object.
7666       Res = DAG.getLifetimeNode(IsStart, sdl, getRoot(), FrameIndex, ObjectSize,
7667                                 Offset);
7668       DAG.setRoot(Res);
7669     }
7670     return;
7671   }
7672   case Intrinsic::pseudoprobe: {
7673     auto Guid = cast<ConstantInt>(I.getArgOperand(0))->getZExtValue();
7674     auto Index = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
7675     auto Attr = cast<ConstantInt>(I.getArgOperand(2))->getZExtValue();
7676     Res = DAG.getPseudoProbeNode(sdl, getRoot(), Guid, Index, Attr);
7677     DAG.setRoot(Res);
7678     return;
7679   }
7680   case Intrinsic::invariant_start:
7681     // Discard region information.
7682     setValue(&I,
7683              DAG.getUNDEF(TLI.getValueType(DAG.getDataLayout(), I.getType())));
7684     return;
7685   case Intrinsic::invariant_end:
7686     // Discard region information.
7687     return;
7688   case Intrinsic::clear_cache: {
7689     SDValue InputChain = DAG.getRoot();
7690     SDValue StartVal = getValue(I.getArgOperand(0));
7691     SDValue EndVal = getValue(I.getArgOperand(1));
7692     Res = DAG.getNode(ISD::CLEAR_CACHE, sdl, DAG.getVTList(MVT::Other),
7693                       {InputChain, StartVal, EndVal});
7694     setValue(&I, Res);
7695     DAG.setRoot(Res);
7696     return;
7697   }
7698   case Intrinsic::donothing:
7699   case Intrinsic::seh_try_begin:
7700   case Intrinsic::seh_scope_begin:
7701   case Intrinsic::seh_try_end:
7702   case Intrinsic::seh_scope_end:
7703     // ignore
7704     return;
7705   case Intrinsic::experimental_stackmap:
7706     visitStackmap(I);
7707     return;
7708   case Intrinsic::experimental_patchpoint_void:
7709   case Intrinsic::experimental_patchpoint:
7710     visitPatchpoint(I);
7711     return;
7712   case Intrinsic::experimental_gc_statepoint:
7713     LowerStatepoint(cast<GCStatepointInst>(I));
7714     return;
7715   case Intrinsic::experimental_gc_result:
7716     visitGCResult(cast<GCResultInst>(I));
7717     return;
7718   case Intrinsic::experimental_gc_relocate:
7719     visitGCRelocate(cast<GCRelocateInst>(I));
7720     return;
7721   case Intrinsic::instrprof_cover:
7722     llvm_unreachable("instrprof failed to lower a cover");
7723   case Intrinsic::instrprof_increment:
7724     llvm_unreachable("instrprof failed to lower an increment");
7725   case Intrinsic::instrprof_timestamp:
7726     llvm_unreachable("instrprof failed to lower a timestamp");
7727   case Intrinsic::instrprof_value_profile:
7728     llvm_unreachable("instrprof failed to lower a value profiling call");
7729   case Intrinsic::instrprof_mcdc_parameters:
7730     llvm_unreachable("instrprof failed to lower mcdc parameters");
7731   case Intrinsic::instrprof_mcdc_tvbitmap_update:
7732     llvm_unreachable("instrprof failed to lower an mcdc tvbitmap update");
7733   case Intrinsic::localescape: {
7734     MachineFunction &MF = DAG.getMachineFunction();
7735     const TargetInstrInfo *TII = DAG.getSubtarget().getInstrInfo();
7736 
7737     // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission
7738     // is the same on all targets.
7739     for (unsigned Idx = 0, E = I.arg_size(); Idx < E; ++Idx) {
7740       Value *Arg = I.getArgOperand(Idx)->stripPointerCasts();
7741       if (isa<ConstantPointerNull>(Arg))
7742         continue; // Skip null pointers. They represent a hole in index space.
7743       AllocaInst *Slot = cast<AllocaInst>(Arg);
7744       assert(FuncInfo.StaticAllocaMap.count(Slot) &&
7745              "can only escape static allocas");
7746       int FI = FuncInfo.StaticAllocaMap[Slot];
7747       MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7748           GlobalValue::dropLLVMManglingEscape(MF.getName()), Idx);
7749       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, dl,
7750               TII->get(TargetOpcode::LOCAL_ESCAPE))
7751           .addSym(FrameAllocSym)
7752           .addFrameIndex(FI);
7753     }
7754 
7755     return;
7756   }
7757 
7758   case Intrinsic::localrecover: {
7759     // i8* @llvm.localrecover(i8* %fn, i8* %fp, i32 %idx)
7760     MachineFunction &MF = DAG.getMachineFunction();
7761 
7762     // Get the symbol that defines the frame offset.
7763     auto *Fn = cast<Function>(I.getArgOperand(0)->stripPointerCasts());
7764     auto *Idx = cast<ConstantInt>(I.getArgOperand(2));
7765     unsigned IdxVal =
7766         unsigned(Idx->getLimitedValue(std::numeric_limits<int>::max()));
7767     MCSymbol *FrameAllocSym = MF.getContext().getOrCreateFrameAllocSymbol(
7768         GlobalValue::dropLLVMManglingEscape(Fn->getName()), IdxVal);
7769 
7770     Value *FP = I.getArgOperand(1);
7771     SDValue FPVal = getValue(FP);
7772     EVT PtrVT = FPVal.getValueType();
7773 
7774     // Create a MCSymbol for the label to avoid any target lowering
7775     // that would make this PC relative.
7776     SDValue OffsetSym = DAG.getMCSymbol(FrameAllocSym, PtrVT);
7777     SDValue OffsetVal =
7778         DAG.getNode(ISD::LOCAL_RECOVER, sdl, PtrVT, OffsetSym);
7779 
7780     // Add the offset to the FP.
7781     SDValue Add = DAG.getMemBasePlusOffset(FPVal, OffsetVal, sdl);
7782     setValue(&I, Add);
7783 
7784     return;
7785   }
7786 
7787   case Intrinsic::fake_use: {
7788     Value *V = I.getArgOperand(0);
7789     SDValue Ops[2];
7790     // For Values not declared or previously used in this basic block, the
7791     // NodeMap will not have an entry, and `getValue` will assert if V has no
7792     // valid register value.
7793     auto FakeUseValue = [&]() -> SDValue {
7794       SDValue &N = NodeMap[V];
7795       if (N.getNode())
7796         return N;
7797 
7798       // If there's a virtual register allocated and initialized for this
7799       // value, use it.
7800       if (SDValue copyFromReg = getCopyFromRegs(V, V->getType()))
7801         return copyFromReg;
7802       // FIXME: Do we want to preserve constants? It seems pointless.
7803       if (isa<Constant>(V))
7804         return getValue(V);
7805       return SDValue();
7806     }();
7807     if (!FakeUseValue || FakeUseValue.isUndef())
7808       return;
7809     Ops[0] = getRoot();
7810     Ops[1] = FakeUseValue;
7811     // Also, do not translate a fake use with an undef operand, or any other
7812     // empty SDValues.
7813     if (!Ops[1] || Ops[1].isUndef())
7814       return;
7815     DAG.setRoot(DAG.getNode(ISD::FAKE_USE, sdl, MVT::Other, Ops));
7816     return;
7817   }
7818 
7819   case Intrinsic::eh_exceptionpointer:
7820   case Intrinsic::eh_exceptioncode: {
7821     // Get the exception pointer vreg, copy from it, and resize it to fit.
7822     const auto *CPI = cast<CatchPadInst>(I.getArgOperand(0));
7823     MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
7824     const TargetRegisterClass *PtrRC = TLI.getRegClassFor(PtrVT);
7825     Register VReg = FuncInfo.getCatchPadExceptionPointerVReg(CPI, PtrRC);
7826     SDValue N = DAG.getCopyFromReg(DAG.getEntryNode(), sdl, VReg, PtrVT);
7827     if (Intrinsic == Intrinsic::eh_exceptioncode)
7828       N = DAG.getZExtOrTrunc(N, sdl, MVT::i32);
7829     setValue(&I, N);
7830     return;
7831   }
7832   case Intrinsic::xray_customevent: {
7833     // Here we want to make sure that the intrinsic behaves as if it has a
7834     // specific calling convention.
7835     const auto &Triple = DAG.getTarget().getTargetTriple();
7836     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7837       return;
7838 
7839     SmallVector<SDValue, 8> Ops;
7840 
7841     // We want to say that we always want the arguments in registers.
7842     SDValue LogEntryVal = getValue(I.getArgOperand(0));
7843     SDValue StrSizeVal = getValue(I.getArgOperand(1));
7844     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7845     SDValue Chain = getRoot();
7846     Ops.push_back(LogEntryVal);
7847     Ops.push_back(StrSizeVal);
7848     Ops.push_back(Chain);
7849 
7850     // We need to enforce the calling convention for the callsite, so that
7851     // argument ordering is enforced correctly, and that register allocation can
7852     // see that some registers may be assumed clobbered and have to preserve
7853     // them across calls to the intrinsic.
7854     MachineSDNode *MN = DAG.getMachineNode(TargetOpcode::PATCHABLE_EVENT_CALL,
7855                                            sdl, NodeTys, Ops);
7856     SDValue patchableNode = SDValue(MN, 0);
7857     DAG.setRoot(patchableNode);
7858     setValue(&I, patchableNode);
7859     return;
7860   }
7861   case Intrinsic::xray_typedevent: {
7862     // Here we want to make sure that the intrinsic behaves as if it has a
7863     // specific calling convention.
7864     const auto &Triple = DAG.getTarget().getTargetTriple();
7865     if (!Triple.isAArch64(64) && Triple.getArch() != Triple::x86_64)
7866       return;
7867 
7868     SmallVector<SDValue, 8> Ops;
7869 
7870     // We want to say that we always want the arguments in registers.
7871     // It's unclear to me how manipulating the selection DAG here forces callers
7872     // to provide arguments in registers instead of on the stack.
7873     SDValue LogTypeId = getValue(I.getArgOperand(0));
7874     SDValue LogEntryVal = getValue(I.getArgOperand(1));
7875     SDValue StrSizeVal = getValue(I.getArgOperand(2));
7876     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
7877     SDValue Chain = getRoot();
7878     Ops.push_back(LogTypeId);
7879     Ops.push_back(LogEntryVal);
7880     Ops.push_back(StrSizeVal);
7881     Ops.push_back(Chain);
7882 
7883     // We need to enforce the calling convention for the callsite, so that
7884     // argument ordering is enforced correctly, and that register allocation can
7885     // see that some registers may be assumed clobbered and have to preserve
7886     // them across calls to the intrinsic.
7887     MachineSDNode *MN = DAG.getMachineNode(
7888         TargetOpcode::PATCHABLE_TYPED_EVENT_CALL, sdl, NodeTys, Ops);
7889     SDValue patchableNode = SDValue(MN, 0);
7890     DAG.setRoot(patchableNode);
7891     setValue(&I, patchableNode);
7892     return;
7893   }
7894   case Intrinsic::experimental_deoptimize:
7895     LowerDeoptimizeCall(&I);
7896     return;
7897   case Intrinsic::stepvector:
7898     visitStepVector(I);
7899     return;
7900   case Intrinsic::vector_reduce_fadd:
7901   case Intrinsic::vector_reduce_fmul:
7902   case Intrinsic::vector_reduce_add:
7903   case Intrinsic::vector_reduce_mul:
7904   case Intrinsic::vector_reduce_and:
7905   case Intrinsic::vector_reduce_or:
7906   case Intrinsic::vector_reduce_xor:
7907   case Intrinsic::vector_reduce_smax:
7908   case Intrinsic::vector_reduce_smin:
7909   case Intrinsic::vector_reduce_umax:
7910   case Intrinsic::vector_reduce_umin:
7911   case Intrinsic::vector_reduce_fmax:
7912   case Intrinsic::vector_reduce_fmin:
7913   case Intrinsic::vector_reduce_fmaximum:
7914   case Intrinsic::vector_reduce_fminimum:
7915     visitVectorReduce(I, Intrinsic);
7916     return;
7917 
7918   case Intrinsic::icall_branch_funnel: {
7919     SmallVector<SDValue, 16> Ops;
7920     Ops.push_back(getValue(I.getArgOperand(0)));
7921 
7922     int64_t Offset;
7923     auto *Base = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7924         I.getArgOperand(1), Offset, DAG.getDataLayout()));
7925     if (!Base)
7926       report_fatal_error(
7927           "llvm.icall.branch.funnel operand must be a GlobalValue");
7928     Ops.push_back(DAG.getTargetGlobalAddress(Base, sdl, MVT::i64, 0));
7929 
7930     struct BranchFunnelTarget {
7931       int64_t Offset;
7932       SDValue Target;
7933     };
7934     SmallVector<BranchFunnelTarget, 8> Targets;
7935 
7936     for (unsigned Op = 1, N = I.arg_size(); Op != N; Op += 2) {
7937       auto *ElemBase = dyn_cast<GlobalObject>(GetPointerBaseWithConstantOffset(
7938           I.getArgOperand(Op), Offset, DAG.getDataLayout()));
7939       if (ElemBase != Base)
7940         report_fatal_error("all llvm.icall.branch.funnel operands must refer "
7941                            "to the same GlobalValue");
7942 
7943       SDValue Val = getValue(I.getArgOperand(Op + 1));
7944       auto *GA = dyn_cast<GlobalAddressSDNode>(Val);
7945       if (!GA)
7946         report_fatal_error(
7947             "llvm.icall.branch.funnel operand must be a GlobalValue");
7948       Targets.push_back({Offset, DAG.getTargetGlobalAddress(
7949                                      GA->getGlobal(), sdl, Val.getValueType(),
7950                                      GA->getOffset())});
7951     }
7952     llvm::sort(Targets,
7953                [](const BranchFunnelTarget &T1, const BranchFunnelTarget &T2) {
7954                  return T1.Offset < T2.Offset;
7955                });
7956 
7957     for (auto &T : Targets) {
7958       Ops.push_back(DAG.getTargetConstant(T.Offset, sdl, MVT::i32));
7959       Ops.push_back(T.Target);
7960     }
7961 
7962     Ops.push_back(DAG.getRoot()); // Chain
7963     SDValue N(DAG.getMachineNode(TargetOpcode::ICALL_BRANCH_FUNNEL, sdl,
7964                                  MVT::Other, Ops),
7965               0);
7966     DAG.setRoot(N);
7967     setValue(&I, N);
7968     HasTailCall = true;
7969     return;
7970   }
7971 
7972   case Intrinsic::wasm_landingpad_index:
7973     // Information this intrinsic contained has been transferred to
7974     // MachineFunction in SelectionDAGISel::PrepareEHLandingPad. We can safely
7975     // delete it now.
7976     return;
7977 
7978   case Intrinsic::aarch64_settag:
7979   case Intrinsic::aarch64_settag_zero: {
7980     const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
7981     bool ZeroMemory = Intrinsic == Intrinsic::aarch64_settag_zero;
7982     SDValue Val = TSI.EmitTargetCodeForSetTag(
7983         DAG, sdl, getRoot(), getValue(I.getArgOperand(0)),
7984         getValue(I.getArgOperand(1)), MachinePointerInfo(I.getArgOperand(0)),
7985         ZeroMemory);
7986     DAG.setRoot(Val);
7987     setValue(&I, Val);
7988     return;
7989   }
7990   case Intrinsic::amdgcn_cs_chain: {
7991     assert(I.arg_size() == 5 && "Additional args not supported yet");
7992     assert(cast<ConstantInt>(I.getOperand(4))->isZero() &&
7993            "Non-zero flags not supported yet");
7994 
7995     // At this point we don't care if it's amdgpu_cs_chain or
7996     // amdgpu_cs_chain_preserve.
7997     CallingConv::ID CC = CallingConv::AMDGPU_CS_Chain;
7998 
7999     Type *RetTy = I.getType();
8000     assert(RetTy->isVoidTy() && "Should not return");
8001 
8002     SDValue Callee = getValue(I.getOperand(0));
8003 
8004     // We only have 2 actual args: one for the SGPRs and one for the VGPRs.
8005     // We'll also tack the value of the EXEC mask at the end.
8006     TargetLowering::ArgListTy Args;
8007     Args.reserve(3);
8008 
8009     for (unsigned Idx : {2, 3, 1}) {
8010       TargetLowering::ArgListEntry Arg;
8011       Arg.Node = getValue(I.getOperand(Idx));
8012       Arg.Ty = I.getOperand(Idx)->getType();
8013       Arg.setAttributes(&I, Idx);
8014       Args.push_back(Arg);
8015     }
8016 
8017     assert(Args[0].IsInReg && "SGPR args should be marked inreg");
8018     assert(!Args[1].IsInReg && "VGPR args should not be marked inreg");
8019     Args[2].IsInReg = true; // EXEC should be inreg
8020 
8021     TargetLowering::CallLoweringInfo CLI(DAG);
8022     CLI.setDebugLoc(getCurSDLoc())
8023         .setChain(getRoot())
8024         .setCallee(CC, RetTy, Callee, std::move(Args))
8025         .setNoReturn(true)
8026         .setTailCall(true)
8027         .setConvergent(I.isConvergent());
8028     CLI.CB = &I;
8029     std::pair<SDValue, SDValue> Result =
8030         lowerInvokable(CLI, /*EHPadBB*/ nullptr);
8031     (void)Result;
8032     assert(!Result.first.getNode() && !Result.second.getNode() &&
8033            "Should've lowered as tail call");
8034 
8035     HasTailCall = true;
8036     return;
8037   }
8038   case Intrinsic::ptrmask: {
8039     SDValue Ptr = getValue(I.getOperand(0));
8040     SDValue Mask = getValue(I.getOperand(1));
8041 
8042     // On arm64_32, pointers are 32 bits when stored in memory, but
8043     // zero-extended to 64 bits when in registers.  Thus the mask is 32 bits to
8044     // match the index type, but the pointer is 64 bits, so the the mask must be
8045     // zero-extended up to 64 bits to match the pointer.
8046     EVT PtrVT =
8047         TLI.getValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8048     EVT MemVT =
8049         TLI.getMemValueType(DAG.getDataLayout(), I.getOperand(0)->getType());
8050     assert(PtrVT == Ptr.getValueType());
8051     assert(MemVT == Mask.getValueType());
8052     if (MemVT != PtrVT)
8053       Mask = DAG.getPtrExtOrTrunc(Mask, sdl, PtrVT);
8054 
8055     setValue(&I, DAG.getNode(ISD::AND, sdl, PtrVT, Ptr, Mask));
8056     return;
8057   }
8058   case Intrinsic::threadlocal_address: {
8059     setValue(&I, getValue(I.getOperand(0)));
8060     return;
8061   }
8062   case Intrinsic::get_active_lane_mask: {
8063     EVT CCVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8064     SDValue Index = getValue(I.getOperand(0));
8065     EVT ElementVT = Index.getValueType();
8066 
8067     if (!TLI.shouldExpandGetActiveLaneMask(CCVT, ElementVT)) {
8068       visitTargetIntrinsic(I, Intrinsic);
8069       return;
8070     }
8071 
8072     SDValue TripCount = getValue(I.getOperand(1));
8073     EVT VecTy = EVT::getVectorVT(*DAG.getContext(), ElementVT,
8074                                  CCVT.getVectorElementCount());
8075 
8076     SDValue VectorIndex = DAG.getSplat(VecTy, sdl, Index);
8077     SDValue VectorTripCount = DAG.getSplat(VecTy, sdl, TripCount);
8078     SDValue VectorStep = DAG.getStepVector(sdl, VecTy);
8079     SDValue VectorInduction = DAG.getNode(
8080         ISD::UADDSAT, sdl, VecTy, VectorIndex, VectorStep);
8081     SDValue SetCC = DAG.getSetCC(sdl, CCVT, VectorInduction,
8082                                  VectorTripCount, ISD::CondCode::SETULT);
8083     setValue(&I, SetCC);
8084     return;
8085   }
8086   case Intrinsic::experimental_get_vector_length: {
8087     assert(cast<ConstantInt>(I.getOperand(1))->getSExtValue() > 0 &&
8088            "Expected positive VF");
8089     unsigned VF = cast<ConstantInt>(I.getOperand(1))->getZExtValue();
8090     bool IsScalable = cast<ConstantInt>(I.getOperand(2))->isOne();
8091 
8092     SDValue Count = getValue(I.getOperand(0));
8093     EVT CountVT = Count.getValueType();
8094 
8095     if (!TLI.shouldExpandGetVectorLength(CountVT, VF, IsScalable)) {
8096       visitTargetIntrinsic(I, Intrinsic);
8097       return;
8098     }
8099 
8100     // Expand to a umin between the trip count and the maximum elements the type
8101     // can hold.
8102     EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8103 
8104     // Extend the trip count to at least the result VT.
8105     if (CountVT.bitsLT(VT)) {
8106       Count = DAG.getNode(ISD::ZERO_EXTEND, sdl, VT, Count);
8107       CountVT = VT;
8108     }
8109 
8110     SDValue MaxEVL = DAG.getElementCount(sdl, CountVT,
8111                                          ElementCount::get(VF, IsScalable));
8112 
8113     SDValue UMin = DAG.getNode(ISD::UMIN, sdl, CountVT, Count, MaxEVL);
8114     // Clip to the result type if needed.
8115     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, sdl, VT, UMin);
8116 
8117     setValue(&I, Trunc);
8118     return;
8119   }
8120   case Intrinsic::experimental_vector_partial_reduce_add: {
8121 
8122     if (!TLI.shouldExpandPartialReductionIntrinsic(cast<IntrinsicInst>(&I))) {
8123       visitTargetIntrinsic(I, Intrinsic);
8124       return;
8125     }
8126 
8127     setValue(&I, DAG.getPartialReduceAdd(sdl, EVT::getEVT(I.getType()),
8128                                          getValue(I.getOperand(0)),
8129                                          getValue(I.getOperand(1))));
8130     return;
8131   }
8132   case Intrinsic::experimental_cttz_elts: {
8133     auto DL = getCurSDLoc();
8134     SDValue Op = getValue(I.getOperand(0));
8135     EVT OpVT = Op.getValueType();
8136 
8137     if (!TLI.shouldExpandCttzElements(OpVT)) {
8138       visitTargetIntrinsic(I, Intrinsic);
8139       return;
8140     }
8141 
8142     if (OpVT.getScalarType() != MVT::i1) {
8143       // Compare the input vector elements to zero & use to count trailing zeros
8144       SDValue AllZero = DAG.getConstant(0, DL, OpVT);
8145       OpVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
8146                               OpVT.getVectorElementCount());
8147       Op = DAG.getSetCC(DL, OpVT, Op, AllZero, ISD::SETNE);
8148     }
8149 
8150     // If the zero-is-poison flag is set, we can assume the upper limit
8151     // of the result is VF-1.
8152     bool ZeroIsPoison =
8153         !cast<ConstantSDNode>(getValue(I.getOperand(1)))->isZero();
8154     ConstantRange VScaleRange(1, true); // Dummy value.
8155     if (isa<ScalableVectorType>(I.getOperand(0)->getType()))
8156       VScaleRange = getVScaleRange(I.getCaller(), 64);
8157     unsigned EltWidth = TLI.getBitWidthForCttzElements(
8158         I.getType(), OpVT.getVectorElementCount(), ZeroIsPoison, &VScaleRange);
8159 
8160     MVT NewEltTy = MVT::getIntegerVT(EltWidth);
8161 
8162     // Create the new vector type & get the vector length
8163     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), NewEltTy,
8164                                  OpVT.getVectorElementCount());
8165 
8166     SDValue VL =
8167         DAG.getElementCount(DL, NewEltTy, OpVT.getVectorElementCount());
8168 
8169     SDValue StepVec = DAG.getStepVector(DL, NewVT);
8170     SDValue SplatVL = DAG.getSplat(NewVT, DL, VL);
8171     SDValue StepVL = DAG.getNode(ISD::SUB, DL, NewVT, SplatVL, StepVec);
8172     SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, Op);
8173     SDValue And = DAG.getNode(ISD::AND, DL, NewVT, StepVL, Ext);
8174     SDValue Max = DAG.getNode(ISD::VECREDUCE_UMAX, DL, NewEltTy, And);
8175     SDValue Sub = DAG.getNode(ISD::SUB, DL, NewEltTy, VL, Max);
8176 
8177     EVT RetTy = TLI.getValueType(DAG.getDataLayout(), I.getType());
8178     SDValue Ret = DAG.getZExtOrTrunc(Sub, DL, RetTy);
8179 
8180     setValue(&I, Ret);
8181     return;
8182   }
8183   case Intrinsic::vector_insert: {
8184     SDValue Vec = getValue(I.getOperand(0));
8185     SDValue SubVec = getValue(I.getOperand(1));
8186     SDValue Index = getValue(I.getOperand(2));
8187 
8188     // The intrinsic's index type is i64, but the SDNode requires an index type
8189     // suitable for the target. Convert the index as required.
8190     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8191     if (Index.getValueType() != VectorIdxTy)
8192       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8193 
8194     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8195     setValue(&I, DAG.getNode(ISD::INSERT_SUBVECTOR, sdl, ResultVT, Vec, SubVec,
8196                              Index));
8197     return;
8198   }
8199   case Intrinsic::vector_extract: {
8200     SDValue Vec = getValue(I.getOperand(0));
8201     SDValue Index = getValue(I.getOperand(1));
8202     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
8203 
8204     // The intrinsic's index type is i64, but the SDNode requires an index type
8205     // suitable for the target. Convert the index as required.
8206     MVT VectorIdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
8207     if (Index.getValueType() != VectorIdxTy)
8208       Index = DAG.getVectorIdxConstant(Index->getAsZExtVal(), sdl);
8209 
8210     setValue(&I,
8211              DAG.getNode(ISD::EXTRACT_SUBVECTOR, sdl, ResultVT, Vec, Index));
8212     return;
8213   }
8214   case Intrinsic::experimental_vector_match: {
8215     SDValue Op1 = getValue(I.getOperand(0));
8216     SDValue Op2 = getValue(I.getOperand(1));
8217     SDValue Mask = getValue(I.getOperand(2));
8218     EVT Op1VT = Op1.getValueType();
8219     EVT Op2VT = Op2.getValueType();
8220     EVT ResVT = Mask.getValueType();
8221     unsigned SearchSize = Op2VT.getVectorNumElements();
8222 
8223     // If the target has native support for this vector match operation, lower
8224     // the intrinsic untouched; otherwise, expand it below.
8225     if (!TLI.shouldExpandVectorMatch(Op1VT, SearchSize)) {
8226       visitTargetIntrinsic(I, Intrinsic);
8227       return;
8228     }
8229 
8230     SDValue Ret = DAG.getConstant(0, sdl, ResVT);
8231 
8232     for (unsigned i = 0; i < SearchSize; ++i) {
8233       SDValue Op2Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, sdl,
8234                                     Op2VT.getVectorElementType(), Op2,
8235                                     DAG.getVectorIdxConstant(i, sdl));
8236       SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, sdl, Op1VT, Op2Elem);
8237       SDValue Cmp = DAG.getSetCC(sdl, ResVT, Op1, Splat, ISD::SETEQ);
8238       Ret = DAG.getNode(ISD::OR, sdl, ResVT, Ret, Cmp);
8239     }
8240 
8241     setValue(&I, DAG.getNode(ISD::AND, sdl, ResVT, Ret, Mask));
8242     return;
8243   }
8244   case Intrinsic::vector_reverse:
8245     visitVectorReverse(I);
8246     return;
8247   case Intrinsic::vector_splice:
8248     visitVectorSplice(I);
8249     return;
8250   case Intrinsic::callbr_landingpad:
8251     visitCallBrLandingPad(I);
8252     return;
8253   case Intrinsic::vector_interleave2:
8254     visitVectorInterleave(I);
8255     return;
8256   case Intrinsic::vector_deinterleave2:
8257     visitVectorDeinterleave(I);
8258     return;
8259   case Intrinsic::experimental_vector_compress:
8260     setValue(&I, DAG.getNode(ISD::VECTOR_COMPRESS, sdl,
8261                              getValue(I.getArgOperand(0)).getValueType(),
8262                              getValue(I.getArgOperand(0)),
8263                              getValue(I.getArgOperand(1)),
8264                              getValue(I.getArgOperand(2)), Flags));
8265     return;
8266   case Intrinsic::experimental_convergence_anchor:
8267   case Intrinsic::experimental_convergence_entry:
8268   case Intrinsic::experimental_convergence_loop:
8269     visitConvergenceControl(I, Intrinsic);
8270     return;
8271   case Intrinsic::experimental_vector_histogram_add: {
8272     visitVectorHistogram(I, Intrinsic);
8273     return;
8274   }
8275   case Intrinsic::experimental_vector_extract_last_active: {
8276     visitVectorExtractLastActive(I, Intrinsic);
8277     return;
8278   }
8279   }
8280 }
8281 
8282 void SelectionDAGBuilder::visitConstrainedFPIntrinsic(
8283     const ConstrainedFPIntrinsic &FPI) {
8284   SDLoc sdl = getCurSDLoc();
8285 
8286   // We do not need to serialize constrained FP intrinsics against
8287   // each other or against (nonvolatile) loads, so they can be
8288   // chained like loads.
8289   SDValue Chain = DAG.getRoot();
8290   SmallVector<SDValue, 4> Opers;
8291   Opers.push_back(Chain);
8292   for (unsigned I = 0, E = FPI.getNonMetadataArgCount(); I != E; ++I)
8293     Opers.push_back(getValue(FPI.getArgOperand(I)));
8294 
8295   auto pushOutChain = [this](SDValue Result, fp::ExceptionBehavior EB) {
8296     assert(Result.getNode()->getNumValues() == 2);
8297 
8298     // Push node to the appropriate list so that future instructions can be
8299     // chained up correctly.
8300     SDValue OutChain = Result.getValue(1);
8301     switch (EB) {
8302     case fp::ExceptionBehavior::ebIgnore:
8303       // The only reason why ebIgnore nodes still need to be chained is that
8304       // they might depend on the current rounding mode, and therefore must
8305       // not be moved across instruction that may change that mode.
8306       [[fallthrough]];
8307     case fp::ExceptionBehavior::ebMayTrap:
8308       // These must not be moved across calls or instructions that may change
8309       // floating-point exception masks.
8310       PendingConstrainedFP.push_back(OutChain);
8311       break;
8312     case fp::ExceptionBehavior::ebStrict:
8313       // These must not be moved across calls or instructions that may change
8314       // floating-point exception masks or read floating-point exception flags.
8315       // In addition, they cannot be optimized out even if unused.
8316       PendingConstrainedFPStrict.push_back(OutChain);
8317       break;
8318     }
8319   };
8320 
8321   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8322   EVT VT = TLI.getValueType(DAG.getDataLayout(), FPI.getType());
8323   SDVTList VTs = DAG.getVTList(VT, MVT::Other);
8324   fp::ExceptionBehavior EB = *FPI.getExceptionBehavior();
8325 
8326   SDNodeFlags Flags;
8327   if (EB == fp::ExceptionBehavior::ebIgnore)
8328     Flags.setNoFPExcept(true);
8329 
8330   if (auto *FPOp = dyn_cast<FPMathOperator>(&FPI))
8331     Flags.copyFMF(*FPOp);
8332 
8333   unsigned Opcode;
8334   switch (FPI.getIntrinsicID()) {
8335   default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
8336 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8337   case Intrinsic::INTRINSIC:                                                   \
8338     Opcode = ISD::STRICT_##DAGN;                                               \
8339     break;
8340 #include "llvm/IR/ConstrainedOps.def"
8341   case Intrinsic::experimental_constrained_fmuladd: {
8342     Opcode = ISD::STRICT_FMA;
8343     // Break fmuladd into fmul and fadd.
8344     if (TM.Options.AllowFPOpFusion == FPOpFusion::Strict ||
8345         !TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
8346       Opers.pop_back();
8347       SDValue Mul = DAG.getNode(ISD::STRICT_FMUL, sdl, VTs, Opers, Flags);
8348       pushOutChain(Mul, EB);
8349       Opcode = ISD::STRICT_FADD;
8350       Opers.clear();
8351       Opers.push_back(Mul.getValue(1));
8352       Opers.push_back(Mul.getValue(0));
8353       Opers.push_back(getValue(FPI.getArgOperand(2)));
8354     }
8355     break;
8356   }
8357   }
8358 
8359   // A few strict DAG nodes carry additional operands that are not
8360   // set up by the default code above.
8361   switch (Opcode) {
8362   default: break;
8363   case ISD::STRICT_FP_ROUND:
8364     Opers.push_back(
8365         DAG.getTargetConstant(0, sdl, TLI.getPointerTy(DAG.getDataLayout())));
8366     break;
8367   case ISD::STRICT_FSETCC:
8368   case ISD::STRICT_FSETCCS: {
8369     auto *FPCmp = dyn_cast<ConstrainedFPCmpIntrinsic>(&FPI);
8370     ISD::CondCode Condition = getFCmpCondCode(FPCmp->getPredicate());
8371     if (TM.Options.NoNaNsFPMath)
8372       Condition = getFCmpCodeWithoutNaN(Condition);
8373     Opers.push_back(DAG.getCondCode(Condition));
8374     break;
8375   }
8376   }
8377 
8378   SDValue Result = DAG.getNode(Opcode, sdl, VTs, Opers, Flags);
8379   pushOutChain(Result, EB);
8380 
8381   SDValue FPResult = Result.getValue(0);
8382   setValue(&FPI, FPResult);
8383 }
8384 
8385 static unsigned getISDForVPIntrinsic(const VPIntrinsic &VPIntrin) {
8386   std::optional<unsigned> ResOPC;
8387   switch (VPIntrin.getIntrinsicID()) {
8388   case Intrinsic::vp_ctlz: {
8389     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8390     ResOPC = IsZeroUndef ? ISD::VP_CTLZ_ZERO_UNDEF : ISD::VP_CTLZ;
8391     break;
8392   }
8393   case Intrinsic::vp_cttz: {
8394     bool IsZeroUndef = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8395     ResOPC = IsZeroUndef ? ISD::VP_CTTZ_ZERO_UNDEF : ISD::VP_CTTZ;
8396     break;
8397   }
8398   case Intrinsic::vp_cttz_elts: {
8399     bool IsZeroPoison = cast<ConstantInt>(VPIntrin.getArgOperand(1))->isOne();
8400     ResOPC = IsZeroPoison ? ISD::VP_CTTZ_ELTS_ZERO_UNDEF : ISD::VP_CTTZ_ELTS;
8401     break;
8402   }
8403 #define HELPER_MAP_VPID_TO_VPSD(VPID, VPSD)                                    \
8404   case Intrinsic::VPID:                                                        \
8405     ResOPC = ISD::VPSD;                                                        \
8406     break;
8407 #include "llvm/IR/VPIntrinsics.def"
8408   }
8409 
8410   if (!ResOPC)
8411     llvm_unreachable(
8412         "Inconsistency: no SDNode available for this VPIntrinsic!");
8413 
8414   if (*ResOPC == ISD::VP_REDUCE_SEQ_FADD ||
8415       *ResOPC == ISD::VP_REDUCE_SEQ_FMUL) {
8416     if (VPIntrin.getFastMathFlags().allowReassoc())
8417       return *ResOPC == ISD::VP_REDUCE_SEQ_FADD ? ISD::VP_REDUCE_FADD
8418                                                 : ISD::VP_REDUCE_FMUL;
8419   }
8420 
8421   return *ResOPC;
8422 }
8423 
8424 void SelectionDAGBuilder::visitVPLoad(
8425     const VPIntrinsic &VPIntrin, EVT VT,
8426     const SmallVectorImpl<SDValue> &OpValues) {
8427   SDLoc DL = getCurSDLoc();
8428   Value *PtrOperand = VPIntrin.getArgOperand(0);
8429   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8430   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8431   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8432   SDValue LD;
8433   // Do not serialize variable-length loads of constant memory with
8434   // anything.
8435   if (!Alignment)
8436     Alignment = DAG.getEVTAlign(VT);
8437   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8438   bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
8439   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8440   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8441       MachinePointerInfo(PtrOperand), MachineMemOperand::MOLoad,
8442       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8443   LD = DAG.getLoadVP(VT, DL, InChain, OpValues[0], OpValues[1], OpValues[2],
8444                      MMO, false /*IsExpanding */);
8445   if (AddToChain)
8446     PendingLoads.push_back(LD.getValue(1));
8447   setValue(&VPIntrin, LD);
8448 }
8449 
8450 void SelectionDAGBuilder::visitVPGather(
8451     const VPIntrinsic &VPIntrin, EVT VT,
8452     const SmallVectorImpl<SDValue> &OpValues) {
8453   SDLoc DL = getCurSDLoc();
8454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8455   Value *PtrOperand = VPIntrin.getArgOperand(0);
8456   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8457   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8458   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8459   SDValue LD;
8460   if (!Alignment)
8461     Alignment = DAG.getEVTAlign(VT.getScalarType());
8462   unsigned AS =
8463     PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8464   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8465       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8466       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8467   SDValue Base, Index, Scale;
8468   ISD::MemIndexType IndexType;
8469   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8470                                     this, VPIntrin.getParent(),
8471                                     VT.getScalarStoreSize());
8472   if (!UniformBase) {
8473     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8474     Index = getValue(PtrOperand);
8475     IndexType = ISD::SIGNED_SCALED;
8476     Scale = DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8477   }
8478   EVT IdxVT = Index.getValueType();
8479   EVT EltTy = IdxVT.getVectorElementType();
8480   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8481     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8482     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8483   }
8484   LD = DAG.getGatherVP(
8485       DAG.getVTList(VT, MVT::Other), VT, DL,
8486       {DAG.getRoot(), Base, Index, Scale, OpValues[1], OpValues[2]}, MMO,
8487       IndexType);
8488   PendingLoads.push_back(LD.getValue(1));
8489   setValue(&VPIntrin, LD);
8490 }
8491 
8492 void SelectionDAGBuilder::visitVPStore(
8493     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8494   SDLoc DL = getCurSDLoc();
8495   Value *PtrOperand = VPIntrin.getArgOperand(1);
8496   EVT VT = OpValues[0].getValueType();
8497   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8498   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8499   SDValue ST;
8500   if (!Alignment)
8501     Alignment = DAG.getEVTAlign(VT);
8502   SDValue Ptr = OpValues[1];
8503   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
8504   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8505       MachinePointerInfo(PtrOperand), MachineMemOperand::MOStore,
8506       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8507   ST = DAG.getStoreVP(getMemoryRoot(), DL, OpValues[0], Ptr, Offset,
8508                       OpValues[2], OpValues[3], VT, MMO, ISD::UNINDEXED,
8509                       /* IsTruncating */ false, /*IsCompressing*/ false);
8510   DAG.setRoot(ST);
8511   setValue(&VPIntrin, ST);
8512 }
8513 
8514 void SelectionDAGBuilder::visitVPScatter(
8515     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8516   SDLoc DL = getCurSDLoc();
8517   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8518   Value *PtrOperand = VPIntrin.getArgOperand(1);
8519   EVT VT = OpValues[0].getValueType();
8520   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8521   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8522   SDValue ST;
8523   if (!Alignment)
8524     Alignment = DAG.getEVTAlign(VT.getScalarType());
8525   unsigned AS =
8526       PtrOperand->getType()->getScalarType()->getPointerAddressSpace();
8527   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8528       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8529       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8530   SDValue Base, Index, Scale;
8531   ISD::MemIndexType IndexType;
8532   bool UniformBase = getUniformBase(PtrOperand, Base, Index, IndexType, Scale,
8533                                     this, VPIntrin.getParent(),
8534                                     VT.getScalarStoreSize());
8535   if (!UniformBase) {
8536     Base = DAG.getConstant(0, DL, TLI.getPointerTy(DAG.getDataLayout()));
8537     Index = getValue(PtrOperand);
8538     IndexType = ISD::SIGNED_SCALED;
8539     Scale =
8540       DAG.getTargetConstant(1, DL, TLI.getPointerTy(DAG.getDataLayout()));
8541   }
8542   EVT IdxVT = Index.getValueType();
8543   EVT EltTy = IdxVT.getVectorElementType();
8544   if (TLI.shouldExtendGSIndex(IdxVT, EltTy)) {
8545     EVT NewIdxVT = IdxVT.changeVectorElementType(EltTy);
8546     Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
8547   }
8548   ST = DAG.getScatterVP(DAG.getVTList(MVT::Other), VT, DL,
8549                         {getMemoryRoot(), OpValues[0], Base, Index, Scale,
8550                          OpValues[2], OpValues[3]},
8551                         MMO, IndexType);
8552   DAG.setRoot(ST);
8553   setValue(&VPIntrin, ST);
8554 }
8555 
8556 void SelectionDAGBuilder::visitVPStridedLoad(
8557     const VPIntrinsic &VPIntrin, EVT VT,
8558     const SmallVectorImpl<SDValue> &OpValues) {
8559   SDLoc DL = getCurSDLoc();
8560   Value *PtrOperand = VPIntrin.getArgOperand(0);
8561   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8562   if (!Alignment)
8563     Alignment = DAG.getEVTAlign(VT.getScalarType());
8564   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8565   const MDNode *Ranges = getRangeMetadata(VPIntrin);
8566   MemoryLocation ML = MemoryLocation::getAfter(PtrOperand, AAInfo);
8567   bool AddToChain = !BatchAA || !BatchAA->pointsToConstantMemory(ML);
8568   SDValue InChain = AddToChain ? DAG.getRoot() : DAG.getEntryNode();
8569   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8570   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8571       MachinePointerInfo(AS), MachineMemOperand::MOLoad,
8572       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo, Ranges);
8573 
8574   SDValue LD = DAG.getStridedLoadVP(VT, DL, InChain, OpValues[0], OpValues[1],
8575                                     OpValues[2], OpValues[3], MMO,
8576                                     false /*IsExpanding*/);
8577 
8578   if (AddToChain)
8579     PendingLoads.push_back(LD.getValue(1));
8580   setValue(&VPIntrin, LD);
8581 }
8582 
8583 void SelectionDAGBuilder::visitVPStridedStore(
8584     const VPIntrinsic &VPIntrin, const SmallVectorImpl<SDValue> &OpValues) {
8585   SDLoc DL = getCurSDLoc();
8586   Value *PtrOperand = VPIntrin.getArgOperand(1);
8587   EVT VT = OpValues[0].getValueType();
8588   MaybeAlign Alignment = VPIntrin.getPointerAlignment();
8589   if (!Alignment)
8590     Alignment = DAG.getEVTAlign(VT.getScalarType());
8591   AAMDNodes AAInfo = VPIntrin.getAAMetadata();
8592   unsigned AS = PtrOperand->getType()->getPointerAddressSpace();
8593   MachineMemOperand *MMO = DAG.getMachineFunction().getMachineMemOperand(
8594       MachinePointerInfo(AS), MachineMemOperand::MOStore,
8595       LocationSize::beforeOrAfterPointer(), *Alignment, AAInfo);
8596 
8597   SDValue ST = DAG.getStridedStoreVP(
8598       getMemoryRoot(), DL, OpValues[0], OpValues[1],
8599       DAG.getUNDEF(OpValues[1].getValueType()), OpValues[2], OpValues[3],
8600       OpValues[4], VT, MMO, ISD::UNINDEXED, /*IsTruncating*/ false,
8601       /*IsCompressing*/ false);
8602 
8603   DAG.setRoot(ST);
8604   setValue(&VPIntrin, ST);
8605 }
8606 
8607 void SelectionDAGBuilder::visitVPCmp(const VPCmpIntrinsic &VPIntrin) {
8608   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8609   SDLoc DL = getCurSDLoc();
8610 
8611   ISD::CondCode Condition;
8612   CmpInst::Predicate CondCode = VPIntrin.getPredicate();
8613   bool IsFP = VPIntrin.getOperand(0)->getType()->isFPOrFPVectorTy();
8614   if (IsFP) {
8615     // FIXME: Regular fcmps are FPMathOperators which may have fast-math (nnan)
8616     // flags, but calls that don't return floating-point types can't be
8617     // FPMathOperators, like vp.fcmp. This affects constrained fcmp too.
8618     Condition = getFCmpCondCode(CondCode);
8619     if (TM.Options.NoNaNsFPMath)
8620       Condition = getFCmpCodeWithoutNaN(Condition);
8621   } else {
8622     Condition = getICmpCondCode(CondCode);
8623   }
8624 
8625   SDValue Op1 = getValue(VPIntrin.getOperand(0));
8626   SDValue Op2 = getValue(VPIntrin.getOperand(1));
8627   // #2 is the condition code
8628   SDValue MaskOp = getValue(VPIntrin.getOperand(3));
8629   SDValue EVL = getValue(VPIntrin.getOperand(4));
8630   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8631   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8632          "Unexpected target EVL type");
8633   EVL = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, EVL);
8634 
8635   EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8636                                                         VPIntrin.getType());
8637   setValue(&VPIntrin,
8638            DAG.getSetCCVP(DL, DestVT, Op1, Op2, Condition, MaskOp, EVL));
8639 }
8640 
8641 void SelectionDAGBuilder::visitVectorPredicationIntrinsic(
8642     const VPIntrinsic &VPIntrin) {
8643   SDLoc DL = getCurSDLoc();
8644   unsigned Opcode = getISDForVPIntrinsic(VPIntrin);
8645 
8646   auto IID = VPIntrin.getIntrinsicID();
8647 
8648   if (const auto *CmpI = dyn_cast<VPCmpIntrinsic>(&VPIntrin))
8649     return visitVPCmp(*CmpI);
8650 
8651   SmallVector<EVT, 4> ValueVTs;
8652   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8653   ComputeValueVTs(TLI, DAG.getDataLayout(), VPIntrin.getType(), ValueVTs);
8654   SDVTList VTs = DAG.getVTList(ValueVTs);
8655 
8656   auto EVLParamPos = VPIntrinsic::getVectorLengthParamPos(IID);
8657 
8658   MVT EVLParamVT = TLI.getVPExplicitVectorLengthTy();
8659   assert(EVLParamVT.isScalarInteger() && EVLParamVT.bitsGE(MVT::i32) &&
8660          "Unexpected target EVL type");
8661 
8662   // Request operands.
8663   SmallVector<SDValue, 7> OpValues;
8664   for (unsigned I = 0; I < VPIntrin.arg_size(); ++I) {
8665     auto Op = getValue(VPIntrin.getArgOperand(I));
8666     if (I == EVLParamPos)
8667       Op = DAG.getNode(ISD::ZERO_EXTEND, DL, EVLParamVT, Op);
8668     OpValues.push_back(Op);
8669   }
8670 
8671   switch (Opcode) {
8672   default: {
8673     SDNodeFlags SDFlags;
8674     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8675       SDFlags.copyFMF(*FPMO);
8676     SDValue Result = DAG.getNode(Opcode, DL, VTs, OpValues, SDFlags);
8677     setValue(&VPIntrin, Result);
8678     break;
8679   }
8680   case ISD::VP_LOAD:
8681     visitVPLoad(VPIntrin, ValueVTs[0], OpValues);
8682     break;
8683   case ISD::VP_GATHER:
8684     visitVPGather(VPIntrin, ValueVTs[0], OpValues);
8685     break;
8686   case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
8687     visitVPStridedLoad(VPIntrin, ValueVTs[0], OpValues);
8688     break;
8689   case ISD::VP_STORE:
8690     visitVPStore(VPIntrin, OpValues);
8691     break;
8692   case ISD::VP_SCATTER:
8693     visitVPScatter(VPIntrin, OpValues);
8694     break;
8695   case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
8696     visitVPStridedStore(VPIntrin, OpValues);
8697     break;
8698   case ISD::VP_FMULADD: {
8699     assert(OpValues.size() == 5 && "Unexpected number of operands");
8700     SDNodeFlags SDFlags;
8701     if (auto *FPMO = dyn_cast<FPMathOperator>(&VPIntrin))
8702       SDFlags.copyFMF(*FPMO);
8703     if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
8704         TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), ValueVTs[0])) {
8705       setValue(&VPIntrin, DAG.getNode(ISD::VP_FMA, DL, VTs, OpValues, SDFlags));
8706     } else {
8707       SDValue Mul = DAG.getNode(
8708           ISD::VP_FMUL, DL, VTs,
8709           {OpValues[0], OpValues[1], OpValues[3], OpValues[4]}, SDFlags);
8710       SDValue Add =
8711           DAG.getNode(ISD::VP_FADD, DL, VTs,
8712                       {Mul, OpValues[2], OpValues[3], OpValues[4]}, SDFlags);
8713       setValue(&VPIntrin, Add);
8714     }
8715     break;
8716   }
8717   case ISD::VP_IS_FPCLASS: {
8718     const DataLayout DLayout = DAG.getDataLayout();
8719     EVT DestVT = TLI.getValueType(DLayout, VPIntrin.getType());
8720     auto Constant = OpValues[1]->getAsZExtVal();
8721     SDValue Check = DAG.getTargetConstant(Constant, DL, MVT::i32);
8722     SDValue V = DAG.getNode(ISD::VP_IS_FPCLASS, DL, DestVT,
8723                             {OpValues[0], Check, OpValues[2], OpValues[3]});
8724     setValue(&VPIntrin, V);
8725     return;
8726   }
8727   case ISD::VP_INTTOPTR: {
8728     SDValue N = OpValues[0];
8729     EVT DestVT = TLI.getValueType(DAG.getDataLayout(), VPIntrin.getType());
8730     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(), VPIntrin.getType());
8731     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8732                                OpValues[2]);
8733     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8734                              OpValues[2]);
8735     setValue(&VPIntrin, N);
8736     break;
8737   }
8738   case ISD::VP_PTRTOINT: {
8739     SDValue N = OpValues[0];
8740     EVT DestVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
8741                                                           VPIntrin.getType());
8742     EVT PtrMemVT = TLI.getMemValueType(DAG.getDataLayout(),
8743                                        VPIntrin.getOperand(0)->getType());
8744     N = DAG.getVPPtrExtOrTrunc(getCurSDLoc(), PtrMemVT, N, OpValues[1],
8745                                OpValues[2]);
8746     N = DAG.getVPZExtOrTrunc(getCurSDLoc(), DestVT, N, OpValues[1],
8747                              OpValues[2]);
8748     setValue(&VPIntrin, N);
8749     break;
8750   }
8751   case ISD::VP_ABS:
8752   case ISD::VP_CTLZ:
8753   case ISD::VP_CTLZ_ZERO_UNDEF:
8754   case ISD::VP_CTTZ:
8755   case ISD::VP_CTTZ_ZERO_UNDEF:
8756   case ISD::VP_CTTZ_ELTS_ZERO_UNDEF:
8757   case ISD::VP_CTTZ_ELTS: {
8758     SDValue Result =
8759         DAG.getNode(Opcode, DL, VTs, {OpValues[0], OpValues[2], OpValues[3]});
8760     setValue(&VPIntrin, Result);
8761     break;
8762   }
8763   }
8764 }
8765 
8766 SDValue SelectionDAGBuilder::lowerStartEH(SDValue Chain,
8767                                           const BasicBlock *EHPadBB,
8768                                           MCSymbol *&BeginLabel) {
8769   MachineFunction &MF = DAG.getMachineFunction();
8770 
8771   // Insert a label before the invoke call to mark the try range.  This can be
8772   // used to detect deletion of the invoke via the MachineModuleInfo.
8773   BeginLabel = MF.getContext().createTempSymbol();
8774 
8775   // For SjLj, keep track of which landing pads go with which invokes
8776   // so as to maintain the ordering of pads in the LSDA.
8777   unsigned CallSiteIndex = FuncInfo.getCurrentCallSite();
8778   if (CallSiteIndex) {
8779     MF.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
8780     LPadToCallSiteMap[FuncInfo.getMBB(EHPadBB)].push_back(CallSiteIndex);
8781 
8782     // Now that the call site is handled, stop tracking it.
8783     FuncInfo.setCurrentCallSite(0);
8784   }
8785 
8786   return DAG.getEHLabel(getCurSDLoc(), Chain, BeginLabel);
8787 }
8788 
8789 SDValue SelectionDAGBuilder::lowerEndEH(SDValue Chain, const InvokeInst *II,
8790                                         const BasicBlock *EHPadBB,
8791                                         MCSymbol *BeginLabel) {
8792   assert(BeginLabel && "BeginLabel should've been set");
8793 
8794   MachineFunction &MF = DAG.getMachineFunction();
8795 
8796   // Insert a label at the end of the invoke call to mark the try range.  This
8797   // can be used to detect deletion of the invoke via the MachineModuleInfo.
8798   MCSymbol *EndLabel = MF.getContext().createTempSymbol();
8799   Chain = DAG.getEHLabel(getCurSDLoc(), Chain, EndLabel);
8800 
8801   // Inform MachineModuleInfo of range.
8802   auto Pers = classifyEHPersonality(FuncInfo.Fn->getPersonalityFn());
8803   // There is a platform (e.g. wasm) that uses funclet style IR but does not
8804   // actually use outlined funclets and their LSDA info style.
8805   if (MF.hasEHFunclets() && isFuncletEHPersonality(Pers)) {
8806     assert(II && "II should've been set");
8807     WinEHFuncInfo *EHInfo = MF.getWinEHFuncInfo();
8808     EHInfo->addIPToStateRange(II, BeginLabel, EndLabel);
8809   } else if (!isScopedEHPersonality(Pers)) {
8810     assert(EHPadBB);
8811     MF.addInvoke(FuncInfo.getMBB(EHPadBB), BeginLabel, EndLabel);
8812   }
8813 
8814   return Chain;
8815 }
8816 
8817 std::pair<SDValue, SDValue>
8818 SelectionDAGBuilder::lowerInvokable(TargetLowering::CallLoweringInfo &CLI,
8819                                     const BasicBlock *EHPadBB) {
8820   MCSymbol *BeginLabel = nullptr;
8821 
8822   if (EHPadBB) {
8823     // Both PendingLoads and PendingExports must be flushed here;
8824     // this call might not return.
8825     (void)getRoot();
8826     DAG.setRoot(lowerStartEH(getControlRoot(), EHPadBB, BeginLabel));
8827     CLI.setChain(getRoot());
8828   }
8829 
8830   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8831   std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
8832 
8833   assert((CLI.IsTailCall || Result.second.getNode()) &&
8834          "Non-null chain expected with non-tail call!");
8835   assert((Result.second.getNode() || !Result.first.getNode()) &&
8836          "Null value expected with tail call!");
8837 
8838   if (!Result.second.getNode()) {
8839     // As a special case, a null chain means that a tail call has been emitted
8840     // and the DAG root is already updated.
8841     HasTailCall = true;
8842 
8843     // Since there's no actual continuation from this block, nothing can be
8844     // relying on us setting vregs for them.
8845     PendingExports.clear();
8846   } else {
8847     DAG.setRoot(Result.second);
8848   }
8849 
8850   if (EHPadBB) {
8851     DAG.setRoot(lowerEndEH(getRoot(), cast_or_null<InvokeInst>(CLI.CB), EHPadBB,
8852                            BeginLabel));
8853     Result.second = getRoot();
8854   }
8855 
8856   return Result;
8857 }
8858 
8859 void SelectionDAGBuilder::LowerCallTo(const CallBase &CB, SDValue Callee,
8860                                       bool isTailCall, bool isMustTailCall,
8861                                       const BasicBlock *EHPadBB,
8862                                       const TargetLowering::PtrAuthInfo *PAI) {
8863   auto &DL = DAG.getDataLayout();
8864   FunctionType *FTy = CB.getFunctionType();
8865   Type *RetTy = CB.getType();
8866 
8867   TargetLowering::ArgListTy Args;
8868   Args.reserve(CB.arg_size());
8869 
8870   const Value *SwiftErrorVal = nullptr;
8871   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8872 
8873   if (isTailCall) {
8874     // Avoid emitting tail calls in functions with the disable-tail-calls
8875     // attribute.
8876     auto *Caller = CB.getParent()->getParent();
8877     if (Caller->getFnAttribute("disable-tail-calls").getValueAsString() ==
8878         "true" && !isMustTailCall)
8879       isTailCall = false;
8880 
8881     // We can't tail call inside a function with a swifterror argument. Lowering
8882     // does not support this yet. It would have to move into the swifterror
8883     // register before the call.
8884     if (TLI.supportSwiftError() &&
8885         Caller->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
8886       isTailCall = false;
8887   }
8888 
8889   for (auto I = CB.arg_begin(), E = CB.arg_end(); I != E; ++I) {
8890     TargetLowering::ArgListEntry Entry;
8891     const Value *V = *I;
8892 
8893     // Skip empty types
8894     if (V->getType()->isEmptyTy())
8895       continue;
8896 
8897     SDValue ArgNode = getValue(V);
8898     Entry.Node = ArgNode; Entry.Ty = V->getType();
8899 
8900     Entry.setAttributes(&CB, I - CB.arg_begin());
8901 
8902     // Use swifterror virtual register as input to the call.
8903     if (Entry.IsSwiftError && TLI.supportSwiftError()) {
8904       SwiftErrorVal = V;
8905       // We find the virtual register for the actual swifterror argument.
8906       // Instead of using the Value, we use the virtual register instead.
8907       Entry.Node =
8908           DAG.getRegister(SwiftError.getOrCreateVRegUseAt(&CB, FuncInfo.MBB, V),
8909                           EVT(TLI.getPointerTy(DL)));
8910     }
8911 
8912     Args.push_back(Entry);
8913 
8914     // If we have an explicit sret argument that is an Instruction, (i.e., it
8915     // might point to function-local memory), we can't meaningfully tail-call.
8916     if (Entry.IsSRet && isa<Instruction>(V))
8917       isTailCall = false;
8918   }
8919 
8920   // If call site has a cfguardtarget operand bundle, create and add an
8921   // additional ArgListEntry.
8922   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_cfguardtarget)) {
8923     TargetLowering::ArgListEntry Entry;
8924     Value *V = Bundle->Inputs[0];
8925     SDValue ArgNode = getValue(V);
8926     Entry.Node = ArgNode;
8927     Entry.Ty = V->getType();
8928     Entry.IsCFGuardTarget = true;
8929     Args.push_back(Entry);
8930   }
8931 
8932   // Check if target-independent constraints permit a tail call here.
8933   // Target-dependent constraints are checked within TLI->LowerCallTo.
8934   if (isTailCall && !isInTailCallPosition(CB, DAG.getTarget()))
8935     isTailCall = false;
8936 
8937   // Disable tail calls if there is an swifterror argument. Targets have not
8938   // been updated to support tail calls.
8939   if (TLI.supportSwiftError() && SwiftErrorVal)
8940     isTailCall = false;
8941 
8942   ConstantInt *CFIType = nullptr;
8943   if (CB.isIndirectCall()) {
8944     if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_kcfi)) {
8945       if (!TLI.supportKCFIBundles())
8946         report_fatal_error(
8947             "Target doesn't support calls with kcfi operand bundles.");
8948       CFIType = cast<ConstantInt>(Bundle->Inputs[0]);
8949       assert(CFIType->getType()->isIntegerTy(32) && "Invalid CFI type");
8950     }
8951   }
8952 
8953   SDValue ConvControlToken;
8954   if (auto Bundle = CB.getOperandBundle(LLVMContext::OB_convergencectrl)) {
8955     auto *Token = Bundle->Inputs[0].get();
8956     ConvControlToken = getValue(Token);
8957   }
8958 
8959   TargetLowering::CallLoweringInfo CLI(DAG);
8960   CLI.setDebugLoc(getCurSDLoc())
8961       .setChain(getRoot())
8962       .setCallee(RetTy, FTy, Callee, std::move(Args), CB)
8963       .setTailCall(isTailCall)
8964       .setConvergent(CB.isConvergent())
8965       .setIsPreallocated(
8966           CB.countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0)
8967       .setCFIType(CFIType)
8968       .setConvergenceControlToken(ConvControlToken);
8969 
8970   // Set the pointer authentication info if we have it.
8971   if (PAI) {
8972     if (!TLI.supportPtrAuthBundles())
8973       report_fatal_error(
8974           "This target doesn't support calls with ptrauth operand bundles.");
8975     CLI.setPtrAuth(*PAI);
8976   }
8977 
8978   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
8979 
8980   if (Result.first.getNode()) {
8981     Result.first = lowerRangeToAssertZExt(DAG, CB, Result.first);
8982     setValue(&CB, Result.first);
8983   }
8984 
8985   // The last element of CLI.InVals has the SDValue for swifterror return.
8986   // Here we copy it to a virtual register and update SwiftErrorMap for
8987   // book-keeping.
8988   if (SwiftErrorVal && TLI.supportSwiftError()) {
8989     // Get the last element of InVals.
8990     SDValue Src = CLI.InVals.back();
8991     Register VReg =
8992         SwiftError.getOrCreateVRegDefAt(&CB, FuncInfo.MBB, SwiftErrorVal);
8993     SDValue CopyNode = CLI.DAG.getCopyToReg(Result.second, CLI.DL, VReg, Src);
8994     DAG.setRoot(CopyNode);
8995   }
8996 }
8997 
8998 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
8999                              SelectionDAGBuilder &Builder) {
9000   // Check to see if this load can be trivially constant folded, e.g. if the
9001   // input is from a string literal.
9002   if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
9003     // Cast pointer to the type we really want to load.
9004     Type *LoadTy =
9005         Type::getIntNTy(PtrVal->getContext(), LoadVT.getScalarSizeInBits());
9006     if (LoadVT.isVector())
9007       LoadTy = FixedVectorType::get(LoadTy, LoadVT.getVectorNumElements());
9008     if (const Constant *LoadCst =
9009             ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
9010                                          LoadTy, Builder.DAG.getDataLayout()))
9011       return Builder.getValue(LoadCst);
9012   }
9013 
9014   // Otherwise, we have to emit the load.  If the pointer is to unfoldable but
9015   // still constant memory, the input chain can be the entry node.
9016   SDValue Root;
9017   bool ConstantMemory = false;
9018 
9019   // Do not serialize (non-volatile) loads of constant memory with anything.
9020   if (Builder.BatchAA && Builder.BatchAA->pointsToConstantMemory(PtrVal)) {
9021     Root = Builder.DAG.getEntryNode();
9022     ConstantMemory = true;
9023   } else {
9024     // Do not serialize non-volatile loads against each other.
9025     Root = Builder.DAG.getRoot();
9026   }
9027 
9028   SDValue Ptr = Builder.getValue(PtrVal);
9029   SDValue LoadVal =
9030       Builder.DAG.getLoad(LoadVT, Builder.getCurSDLoc(), Root, Ptr,
9031                           MachinePointerInfo(PtrVal), Align(1));
9032 
9033   if (!ConstantMemory)
9034     Builder.PendingLoads.push_back(LoadVal.getValue(1));
9035   return LoadVal;
9036 }
9037 
9038 /// Record the value for an instruction that produces an integer result,
9039 /// converting the type where necessary.
9040 void SelectionDAGBuilder::processIntegerCallValue(const Instruction &I,
9041                                                   SDValue Value,
9042                                                   bool IsSigned) {
9043   EVT VT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9044                                                     I.getType(), true);
9045   Value = DAG.getExtOrTrunc(IsSigned, Value, getCurSDLoc(), VT);
9046   setValue(&I, Value);
9047 }
9048 
9049 /// See if we can lower a memcmp/bcmp call into an optimized form. If so, return
9050 /// true and lower it. Otherwise return false, and it will be lowered like a
9051 /// normal call.
9052 /// The caller already checked that \p I calls the appropriate LibFunc with a
9053 /// correct prototype.
9054 bool SelectionDAGBuilder::visitMemCmpBCmpCall(const CallInst &I) {
9055   const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
9056   const Value *Size = I.getArgOperand(2);
9057   const ConstantSDNode *CSize = dyn_cast<ConstantSDNode>(getValue(Size));
9058   if (CSize && CSize->getZExtValue() == 0) {
9059     EVT CallVT = DAG.getTargetLoweringInfo().getValueType(DAG.getDataLayout(),
9060                                                           I.getType(), true);
9061     setValue(&I, DAG.getConstant(0, getCurSDLoc(), CallVT));
9062     return true;
9063   }
9064 
9065   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9066   std::pair<SDValue, SDValue> Res = TSI.EmitTargetCodeForMemcmp(
9067       DAG, getCurSDLoc(), DAG.getRoot(), getValue(LHS), getValue(RHS),
9068       getValue(Size), MachinePointerInfo(LHS), MachinePointerInfo(RHS));
9069   if (Res.first.getNode()) {
9070     processIntegerCallValue(I, Res.first, true);
9071     PendingLoads.push_back(Res.second);
9072     return true;
9073   }
9074 
9075   // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS)  != 0
9076   // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS)  != 0
9077   if (!CSize || !isOnlyUsedInZeroEqualityComparison(&I))
9078     return false;
9079 
9080   // If the target has a fast compare for the given size, it will return a
9081   // preferred load type for that size. Require that the load VT is legal and
9082   // that the target supports unaligned loads of that type. Otherwise, return
9083   // INVALID.
9084   auto hasFastLoadsAndCompare = [&](unsigned NumBits) {
9085     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9086     MVT LVT = TLI.hasFastEqualityCompare(NumBits);
9087     if (LVT != MVT::INVALID_SIMPLE_VALUE_TYPE) {
9088       // TODO: Handle 5 byte compare as 4-byte + 1 byte.
9089       // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
9090       // TODO: Check alignment of src and dest ptrs.
9091       unsigned DstAS = LHS->getType()->getPointerAddressSpace();
9092       unsigned SrcAS = RHS->getType()->getPointerAddressSpace();
9093       if (!TLI.isTypeLegal(LVT) ||
9094           !TLI.allowsMisalignedMemoryAccesses(LVT, SrcAS) ||
9095           !TLI.allowsMisalignedMemoryAccesses(LVT, DstAS))
9096         LVT = MVT::INVALID_SIMPLE_VALUE_TYPE;
9097     }
9098 
9099     return LVT;
9100   };
9101 
9102   // This turns into unaligned loads. We only do this if the target natively
9103   // supports the MVT we'll be loading or if it is small enough (<= 4) that
9104   // we'll only produce a small number of byte loads.
9105   MVT LoadVT;
9106   unsigned NumBitsToCompare = CSize->getZExtValue() * 8;
9107   switch (NumBitsToCompare) {
9108   default:
9109     return false;
9110   case 16:
9111     LoadVT = MVT::i16;
9112     break;
9113   case 32:
9114     LoadVT = MVT::i32;
9115     break;
9116   case 64:
9117   case 128:
9118   case 256:
9119     LoadVT = hasFastLoadsAndCompare(NumBitsToCompare);
9120     break;
9121   }
9122 
9123   if (LoadVT == MVT::INVALID_SIMPLE_VALUE_TYPE)
9124     return false;
9125 
9126   SDValue LoadL = getMemCmpLoad(LHS, LoadVT, *this);
9127   SDValue LoadR = getMemCmpLoad(RHS, LoadVT, *this);
9128 
9129   // Bitcast to a wide integer type if the loads are vectors.
9130   if (LoadVT.isVector()) {
9131     EVT CmpVT = EVT::getIntegerVT(LHS->getContext(), LoadVT.getSizeInBits());
9132     LoadL = DAG.getBitcast(CmpVT, LoadL);
9133     LoadR = DAG.getBitcast(CmpVT, LoadR);
9134   }
9135 
9136   SDValue Cmp = DAG.getSetCC(getCurSDLoc(), MVT::i1, LoadL, LoadR, ISD::SETNE);
9137   processIntegerCallValue(I, Cmp, false);
9138   return true;
9139 }
9140 
9141 /// See if we can lower a memchr call into an optimized form. If so, return
9142 /// true and lower it. Otherwise return false, and it will be lowered like a
9143 /// normal call.
9144 /// The caller already checked that \p I calls the appropriate LibFunc with a
9145 /// correct prototype.
9146 bool SelectionDAGBuilder::visitMemChrCall(const CallInst &I) {
9147   const Value *Src = I.getArgOperand(0);
9148   const Value *Char = I.getArgOperand(1);
9149   const Value *Length = I.getArgOperand(2);
9150 
9151   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9152   std::pair<SDValue, SDValue> Res =
9153     TSI.EmitTargetCodeForMemchr(DAG, getCurSDLoc(), DAG.getRoot(),
9154                                 getValue(Src), getValue(Char), getValue(Length),
9155                                 MachinePointerInfo(Src));
9156   if (Res.first.getNode()) {
9157     setValue(&I, Res.first);
9158     PendingLoads.push_back(Res.second);
9159     return true;
9160   }
9161 
9162   return false;
9163 }
9164 
9165 /// See if we can lower a mempcpy call into an optimized form. If so, return
9166 /// true and lower it. Otherwise return false, and it will be lowered like a
9167 /// normal call.
9168 /// The caller already checked that \p I calls the appropriate LibFunc with a
9169 /// correct prototype.
9170 bool SelectionDAGBuilder::visitMemPCpyCall(const CallInst &I) {
9171   SDValue Dst = getValue(I.getArgOperand(0));
9172   SDValue Src = getValue(I.getArgOperand(1));
9173   SDValue Size = getValue(I.getArgOperand(2));
9174 
9175   Align DstAlign = DAG.InferPtrAlign(Dst).valueOrOne();
9176   Align SrcAlign = DAG.InferPtrAlign(Src).valueOrOne();
9177   // DAG::getMemcpy needs Alignment to be defined.
9178   Align Alignment = std::min(DstAlign, SrcAlign);
9179 
9180   SDLoc sdl = getCurSDLoc();
9181 
9182   // In the mempcpy context we need to pass in a false value for isTailCall
9183   // because the return pointer needs to be adjusted by the size of
9184   // the copied memory.
9185   SDValue Root = getMemoryRoot();
9186   SDValue MC = DAG.getMemcpy(
9187       Root, sdl, Dst, Src, Size, Alignment, false, false, /*CI=*/nullptr,
9188       std::nullopt, MachinePointerInfo(I.getArgOperand(0)),
9189       MachinePointerInfo(I.getArgOperand(1)), I.getAAMetadata());
9190   assert(MC.getNode() != nullptr &&
9191          "** memcpy should not be lowered as TailCall in mempcpy context **");
9192   DAG.setRoot(MC);
9193 
9194   // Check if Size needs to be truncated or extended.
9195   Size = DAG.getSExtOrTrunc(Size, sdl, Dst.getValueType());
9196 
9197   // Adjust return pointer to point just past the last dst byte.
9198   SDValue DstPlusSize = DAG.getNode(ISD::ADD, sdl, Dst.getValueType(),
9199                                     Dst, Size);
9200   setValue(&I, DstPlusSize);
9201   return true;
9202 }
9203 
9204 /// See if we can lower a strcpy call into an optimized form.  If so, return
9205 /// true and lower it, otherwise return false and it will be lowered like a
9206 /// normal call.
9207 /// The caller already checked that \p I calls the appropriate LibFunc with a
9208 /// correct prototype.
9209 bool SelectionDAGBuilder::visitStrCpyCall(const CallInst &I, bool isStpcpy) {
9210   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9211 
9212   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9213   std::pair<SDValue, SDValue> Res =
9214     TSI.EmitTargetCodeForStrcpy(DAG, getCurSDLoc(), getRoot(),
9215                                 getValue(Arg0), getValue(Arg1),
9216                                 MachinePointerInfo(Arg0),
9217                                 MachinePointerInfo(Arg1), isStpcpy);
9218   if (Res.first.getNode()) {
9219     setValue(&I, Res.first);
9220     DAG.setRoot(Res.second);
9221     return true;
9222   }
9223 
9224   return false;
9225 }
9226 
9227 /// See if we can lower a strcmp call into an optimized form.  If so, return
9228 /// true and lower it, otherwise return false and it will be lowered like a
9229 /// normal call.
9230 /// The caller already checked that \p I calls the appropriate LibFunc with a
9231 /// correct prototype.
9232 bool SelectionDAGBuilder::visitStrCmpCall(const CallInst &I) {
9233   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9234 
9235   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9236   std::pair<SDValue, SDValue> Res =
9237     TSI.EmitTargetCodeForStrcmp(DAG, getCurSDLoc(), DAG.getRoot(),
9238                                 getValue(Arg0), getValue(Arg1),
9239                                 MachinePointerInfo(Arg0),
9240                                 MachinePointerInfo(Arg1));
9241   if (Res.first.getNode()) {
9242     processIntegerCallValue(I, Res.first, true);
9243     PendingLoads.push_back(Res.second);
9244     return true;
9245   }
9246 
9247   return false;
9248 }
9249 
9250 /// See if we can lower a strlen call into an optimized form.  If so, return
9251 /// true and lower it, otherwise return false and it will be lowered like a
9252 /// normal call.
9253 /// The caller already checked that \p I calls the appropriate LibFunc with a
9254 /// correct prototype.
9255 bool SelectionDAGBuilder::visitStrLenCall(const CallInst &I) {
9256   const Value *Arg0 = I.getArgOperand(0);
9257 
9258   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9259   std::pair<SDValue, SDValue> Res =
9260     TSI.EmitTargetCodeForStrlen(DAG, getCurSDLoc(), DAG.getRoot(),
9261                                 getValue(Arg0), MachinePointerInfo(Arg0));
9262   if (Res.first.getNode()) {
9263     processIntegerCallValue(I, Res.first, false);
9264     PendingLoads.push_back(Res.second);
9265     return true;
9266   }
9267 
9268   return false;
9269 }
9270 
9271 /// See if we can lower a strnlen call into an optimized form.  If so, return
9272 /// true and lower it, otherwise return false and it will be lowered like a
9273 /// normal call.
9274 /// The caller already checked that \p I calls the appropriate LibFunc with a
9275 /// correct prototype.
9276 bool SelectionDAGBuilder::visitStrNLenCall(const CallInst &I) {
9277   const Value *Arg0 = I.getArgOperand(0), *Arg1 = I.getArgOperand(1);
9278 
9279   const SelectionDAGTargetInfo &TSI = DAG.getSelectionDAGInfo();
9280   std::pair<SDValue, SDValue> Res =
9281     TSI.EmitTargetCodeForStrnlen(DAG, getCurSDLoc(), DAG.getRoot(),
9282                                  getValue(Arg0), getValue(Arg1),
9283                                  MachinePointerInfo(Arg0));
9284   if (Res.first.getNode()) {
9285     processIntegerCallValue(I, Res.first, false);
9286     PendingLoads.push_back(Res.second);
9287     return true;
9288   }
9289 
9290   return false;
9291 }
9292 
9293 /// See if we can lower a unary floating-point operation into an SDNode with
9294 /// the specified Opcode.  If so, return true and lower it, otherwise return
9295 /// false and it will be lowered like a normal call.
9296 /// The caller already checked that \p I calls the appropriate LibFunc with a
9297 /// correct prototype.
9298 bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
9299                                               unsigned Opcode) {
9300   // We already checked this call's prototype; verify it doesn't modify errno.
9301   if (!I.onlyReadsMemory())
9302     return false;
9303 
9304   SDNodeFlags Flags;
9305   Flags.copyFMF(cast<FPMathOperator>(I));
9306 
9307   SDValue Tmp = getValue(I.getArgOperand(0));
9308   setValue(&I,
9309            DAG.getNode(Opcode, getCurSDLoc(), Tmp.getValueType(), Tmp, Flags));
9310   return true;
9311 }
9312 
9313 /// See if we can lower a binary floating-point operation into an SDNode with
9314 /// the specified Opcode. If so, return true and lower it. Otherwise return
9315 /// false, and it will be lowered like a normal call.
9316 /// The caller already checked that \p I calls the appropriate LibFunc with a
9317 /// correct prototype.
9318 bool SelectionDAGBuilder::visitBinaryFloatCall(const CallInst &I,
9319                                                unsigned Opcode) {
9320   // We already checked this call's prototype; verify it doesn't modify errno.
9321   if (!I.onlyReadsMemory())
9322     return false;
9323 
9324   SDNodeFlags Flags;
9325   Flags.copyFMF(cast<FPMathOperator>(I));
9326 
9327   SDValue Tmp0 = getValue(I.getArgOperand(0));
9328   SDValue Tmp1 = getValue(I.getArgOperand(1));
9329   EVT VT = Tmp0.getValueType();
9330   setValue(&I, DAG.getNode(Opcode, getCurSDLoc(), VT, Tmp0, Tmp1, Flags));
9331   return true;
9332 }
9333 
9334 void SelectionDAGBuilder::visitCall(const CallInst &I) {
9335   // Handle inline assembly differently.
9336   if (I.isInlineAsm()) {
9337     visitInlineAsm(I);
9338     return;
9339   }
9340 
9341   diagnoseDontCall(I);
9342 
9343   if (Function *F = I.getCalledFunction()) {
9344     if (F->isDeclaration()) {
9345       // Is this an LLVM intrinsic or a target-specific intrinsic?
9346       unsigned IID = F->getIntrinsicID();
9347       if (!IID)
9348         if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo())
9349           IID = II->getIntrinsicID(F);
9350 
9351       if (IID) {
9352         visitIntrinsicCall(I, IID);
9353         return;
9354       }
9355     }
9356 
9357     // Check for well-known libc/libm calls.  If the function is internal, it
9358     // can't be a library call.  Don't do the check if marked as nobuiltin for
9359     // some reason or the call site requires strict floating point semantics.
9360     LibFunc Func;
9361     if (!I.isNoBuiltin() && !I.isStrictFP() && !F->hasLocalLinkage() &&
9362         F->hasName() && LibInfo->getLibFunc(*F, Func) &&
9363         LibInfo->hasOptimizedCodeGen(Func)) {
9364       switch (Func) {
9365       default: break;
9366       case LibFunc_bcmp:
9367         if (visitMemCmpBCmpCall(I))
9368           return;
9369         break;
9370       case LibFunc_copysign:
9371       case LibFunc_copysignf:
9372       case LibFunc_copysignl:
9373         // We already checked this call's prototype; verify it doesn't modify
9374         // errno.
9375         if (I.onlyReadsMemory()) {
9376           SDValue LHS = getValue(I.getArgOperand(0));
9377           SDValue RHS = getValue(I.getArgOperand(1));
9378           setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurSDLoc(),
9379                                    LHS.getValueType(), LHS, RHS));
9380           return;
9381         }
9382         break;
9383       case LibFunc_fabs:
9384       case LibFunc_fabsf:
9385       case LibFunc_fabsl:
9386         if (visitUnaryFloatCall(I, ISD::FABS))
9387           return;
9388         break;
9389       case LibFunc_fmin:
9390       case LibFunc_fminf:
9391       case LibFunc_fminl:
9392         if (visitBinaryFloatCall(I, ISD::FMINNUM))
9393           return;
9394         break;
9395       case LibFunc_fmax:
9396       case LibFunc_fmaxf:
9397       case LibFunc_fmaxl:
9398         if (visitBinaryFloatCall(I, ISD::FMAXNUM))
9399           return;
9400         break;
9401       case LibFunc_fminimum_num:
9402       case LibFunc_fminimum_numf:
9403       case LibFunc_fminimum_numl:
9404         if (visitBinaryFloatCall(I, ISD::FMINIMUMNUM))
9405           return;
9406         break;
9407       case LibFunc_fmaximum_num:
9408       case LibFunc_fmaximum_numf:
9409       case LibFunc_fmaximum_numl:
9410         if (visitBinaryFloatCall(I, ISD::FMAXIMUMNUM))
9411           return;
9412         break;
9413       case LibFunc_sin:
9414       case LibFunc_sinf:
9415       case LibFunc_sinl:
9416         if (visitUnaryFloatCall(I, ISD::FSIN))
9417           return;
9418         break;
9419       case LibFunc_cos:
9420       case LibFunc_cosf:
9421       case LibFunc_cosl:
9422         if (visitUnaryFloatCall(I, ISD::FCOS))
9423           return;
9424         break;
9425       case LibFunc_tan:
9426       case LibFunc_tanf:
9427       case LibFunc_tanl:
9428         if (visitUnaryFloatCall(I, ISD::FTAN))
9429           return;
9430         break;
9431       case LibFunc_asin:
9432       case LibFunc_asinf:
9433       case LibFunc_asinl:
9434         if (visitUnaryFloatCall(I, ISD::FASIN))
9435           return;
9436         break;
9437       case LibFunc_acos:
9438       case LibFunc_acosf:
9439       case LibFunc_acosl:
9440         if (visitUnaryFloatCall(I, ISD::FACOS))
9441           return;
9442         break;
9443       case LibFunc_atan:
9444       case LibFunc_atanf:
9445       case LibFunc_atanl:
9446         if (visitUnaryFloatCall(I, ISD::FATAN))
9447           return;
9448         break;
9449       case LibFunc_atan2:
9450       case LibFunc_atan2f:
9451       case LibFunc_atan2l:
9452         if (visitBinaryFloatCall(I, ISD::FATAN2))
9453           return;
9454         break;
9455       case LibFunc_sinh:
9456       case LibFunc_sinhf:
9457       case LibFunc_sinhl:
9458         if (visitUnaryFloatCall(I, ISD::FSINH))
9459           return;
9460         break;
9461       case LibFunc_cosh:
9462       case LibFunc_coshf:
9463       case LibFunc_coshl:
9464         if (visitUnaryFloatCall(I, ISD::FCOSH))
9465           return;
9466         break;
9467       case LibFunc_tanh:
9468       case LibFunc_tanhf:
9469       case LibFunc_tanhl:
9470         if (visitUnaryFloatCall(I, ISD::FTANH))
9471           return;
9472         break;
9473       case LibFunc_sqrt:
9474       case LibFunc_sqrtf:
9475       case LibFunc_sqrtl:
9476       case LibFunc_sqrt_finite:
9477       case LibFunc_sqrtf_finite:
9478       case LibFunc_sqrtl_finite:
9479         if (visitUnaryFloatCall(I, ISD::FSQRT))
9480           return;
9481         break;
9482       case LibFunc_floor:
9483       case LibFunc_floorf:
9484       case LibFunc_floorl:
9485         if (visitUnaryFloatCall(I, ISD::FFLOOR))
9486           return;
9487         break;
9488       case LibFunc_nearbyint:
9489       case LibFunc_nearbyintf:
9490       case LibFunc_nearbyintl:
9491         if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
9492           return;
9493         break;
9494       case LibFunc_ceil:
9495       case LibFunc_ceilf:
9496       case LibFunc_ceill:
9497         if (visitUnaryFloatCall(I, ISD::FCEIL))
9498           return;
9499         break;
9500       case LibFunc_rint:
9501       case LibFunc_rintf:
9502       case LibFunc_rintl:
9503         if (visitUnaryFloatCall(I, ISD::FRINT))
9504           return;
9505         break;
9506       case LibFunc_round:
9507       case LibFunc_roundf:
9508       case LibFunc_roundl:
9509         if (visitUnaryFloatCall(I, ISD::FROUND))
9510           return;
9511         break;
9512       case LibFunc_trunc:
9513       case LibFunc_truncf:
9514       case LibFunc_truncl:
9515         if (visitUnaryFloatCall(I, ISD::FTRUNC))
9516           return;
9517         break;
9518       case LibFunc_log2:
9519       case LibFunc_log2f:
9520       case LibFunc_log2l:
9521         if (visitUnaryFloatCall(I, ISD::FLOG2))
9522           return;
9523         break;
9524       case LibFunc_exp2:
9525       case LibFunc_exp2f:
9526       case LibFunc_exp2l:
9527         if (visitUnaryFloatCall(I, ISD::FEXP2))
9528           return;
9529         break;
9530       case LibFunc_exp10:
9531       case LibFunc_exp10f:
9532       case LibFunc_exp10l:
9533         if (visitUnaryFloatCall(I, ISD::FEXP10))
9534           return;
9535         break;
9536       case LibFunc_ldexp:
9537       case LibFunc_ldexpf:
9538       case LibFunc_ldexpl:
9539         if (visitBinaryFloatCall(I, ISD::FLDEXP))
9540           return;
9541         break;
9542       case LibFunc_memcmp:
9543         if (visitMemCmpBCmpCall(I))
9544           return;
9545         break;
9546       case LibFunc_mempcpy:
9547         if (visitMemPCpyCall(I))
9548           return;
9549         break;
9550       case LibFunc_memchr:
9551         if (visitMemChrCall(I))
9552           return;
9553         break;
9554       case LibFunc_strcpy:
9555         if (visitStrCpyCall(I, false))
9556           return;
9557         break;
9558       case LibFunc_stpcpy:
9559         if (visitStrCpyCall(I, true))
9560           return;
9561         break;
9562       case LibFunc_strcmp:
9563         if (visitStrCmpCall(I))
9564           return;
9565         break;
9566       case LibFunc_strlen:
9567         if (visitStrLenCall(I))
9568           return;
9569         break;
9570       case LibFunc_strnlen:
9571         if (visitStrNLenCall(I))
9572           return;
9573         break;
9574       }
9575     }
9576   }
9577 
9578   if (I.countOperandBundlesOfType(LLVMContext::OB_ptrauth)) {
9579     LowerCallSiteWithPtrAuthBundle(cast<CallBase>(I), /*EHPadBB=*/nullptr);
9580     return;
9581   }
9582 
9583   // Deopt bundles are lowered in LowerCallSiteWithDeoptBundle, and we don't
9584   // have to do anything here to lower funclet bundles.
9585   // CFGuardTarget bundles are lowered in LowerCallTo.
9586   assert(!I.hasOperandBundlesOtherThan(
9587              {LLVMContext::OB_deopt, LLVMContext::OB_funclet,
9588               LLVMContext::OB_cfguardtarget, LLVMContext::OB_preallocated,
9589               LLVMContext::OB_clang_arc_attachedcall, LLVMContext::OB_kcfi,
9590               LLVMContext::OB_convergencectrl}) &&
9591          "Cannot lower calls with arbitrary operand bundles!");
9592 
9593   SDValue Callee = getValue(I.getCalledOperand());
9594 
9595   if (I.hasDeoptState())
9596     LowerCallSiteWithDeoptBundle(&I, Callee, nullptr);
9597   else
9598     // Check if we can potentially perform a tail call. More detailed checking
9599     // is be done within LowerCallTo, after more information about the call is
9600     // known.
9601     LowerCallTo(I, Callee, I.isTailCall(), I.isMustTailCall());
9602 }
9603 
9604 void SelectionDAGBuilder::LowerCallSiteWithPtrAuthBundle(
9605     const CallBase &CB, const BasicBlock *EHPadBB) {
9606   auto PAB = CB.getOperandBundle("ptrauth");
9607   const Value *CalleeV = CB.getCalledOperand();
9608 
9609   // Gather the call ptrauth data from the operand bundle:
9610   //   [ i32 <key>, i64 <discriminator> ]
9611   const auto *Key = cast<ConstantInt>(PAB->Inputs[0]);
9612   const Value *Discriminator = PAB->Inputs[1];
9613 
9614   assert(Key->getType()->isIntegerTy(32) && "Invalid ptrauth key");
9615   assert(Discriminator->getType()->isIntegerTy(64) &&
9616          "Invalid ptrauth discriminator");
9617 
9618   // Look through ptrauth constants to find the raw callee.
9619   // Do a direct unauthenticated call if we found it and everything matches.
9620   if (const auto *CalleeCPA = dyn_cast<ConstantPtrAuth>(CalleeV))
9621     if (CalleeCPA->isKnownCompatibleWith(Key, Discriminator,
9622                                          DAG.getDataLayout()))
9623       return LowerCallTo(CB, getValue(CalleeCPA->getPointer()), CB.isTailCall(),
9624                          CB.isMustTailCall(), EHPadBB);
9625 
9626   // Functions should never be ptrauth-called directly.
9627   assert(!isa<Function>(CalleeV) && "invalid direct ptrauth call");
9628 
9629   // Otherwise, do an authenticated indirect call.
9630   TargetLowering::PtrAuthInfo PAI = {Key->getZExtValue(),
9631                                      getValue(Discriminator)};
9632 
9633   LowerCallTo(CB, getValue(CalleeV), CB.isTailCall(), CB.isMustTailCall(),
9634               EHPadBB, &PAI);
9635 }
9636 
9637 namespace {
9638 
9639 /// AsmOperandInfo - This contains information for each constraint that we are
9640 /// lowering.
9641 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
9642 public:
9643   /// CallOperand - If this is the result output operand or a clobber
9644   /// this is null, otherwise it is the incoming operand to the CallInst.
9645   /// This gets modified as the asm is processed.
9646   SDValue CallOperand;
9647 
9648   /// AssignedRegs - If this is a register or register class operand, this
9649   /// contains the set of register corresponding to the operand.
9650   RegsForValue AssignedRegs;
9651 
9652   explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
9653     : TargetLowering::AsmOperandInfo(info), CallOperand(nullptr, 0) {
9654   }
9655 
9656   /// Whether or not this operand accesses memory
9657   bool hasMemory(const TargetLowering &TLI) const {
9658     // Indirect operand accesses access memory.
9659     if (isIndirect)
9660       return true;
9661 
9662     for (const auto &Code : Codes)
9663       if (TLI.getConstraintType(Code) == TargetLowering::C_Memory)
9664         return true;
9665 
9666     return false;
9667   }
9668 };
9669 
9670 
9671 } // end anonymous namespace
9672 
9673 /// Make sure that the output operand \p OpInfo and its corresponding input
9674 /// operand \p MatchingOpInfo have compatible constraint types (otherwise error
9675 /// out).
9676 static void patchMatchingInput(const SDISelAsmOperandInfo &OpInfo,
9677                                SDISelAsmOperandInfo &MatchingOpInfo,
9678                                SelectionDAG &DAG) {
9679   if (OpInfo.ConstraintVT == MatchingOpInfo.ConstraintVT)
9680     return;
9681 
9682   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
9683   const auto &TLI = DAG.getTargetLoweringInfo();
9684 
9685   std::pair<unsigned, const TargetRegisterClass *> MatchRC =
9686       TLI.getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
9687                                        OpInfo.ConstraintVT);
9688   std::pair<unsigned, const TargetRegisterClass *> InputRC =
9689       TLI.getRegForInlineAsmConstraint(TRI, MatchingOpInfo.ConstraintCode,
9690                                        MatchingOpInfo.ConstraintVT);
9691   const bool OutOpIsIntOrFP =
9692       OpInfo.ConstraintVT.isInteger() || OpInfo.ConstraintVT.isFloatingPoint();
9693   const bool InOpIsIntOrFP = MatchingOpInfo.ConstraintVT.isInteger() ||
9694                              MatchingOpInfo.ConstraintVT.isFloatingPoint();
9695   if ((OutOpIsIntOrFP != InOpIsIntOrFP) || (MatchRC.second != InputRC.second)) {
9696     // FIXME: error out in a more elegant fashion
9697     report_fatal_error("Unsupported asm: input constraint"
9698                        " with a matching output constraint of"
9699                        " incompatible type!");
9700   }
9701   MatchingOpInfo.ConstraintVT = OpInfo.ConstraintVT;
9702 }
9703 
9704 /// Get a direct memory input to behave well as an indirect operand.
9705 /// This may introduce stores, hence the need for a \p Chain.
9706 /// \return The (possibly updated) chain.
9707 static SDValue getAddressForMemoryInput(SDValue Chain, const SDLoc &Location,
9708                                         SDISelAsmOperandInfo &OpInfo,
9709                                         SelectionDAG &DAG) {
9710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9711 
9712   // If we don't have an indirect input, put it in the constpool if we can,
9713   // otherwise spill it to a stack slot.
9714   // TODO: This isn't quite right. We need to handle these according to
9715   // the addressing mode that the constraint wants. Also, this may take
9716   // an additional register for the computation and we don't want that
9717   // either.
9718 
9719   // If the operand is a float, integer, or vector constant, spill to a
9720   // constant pool entry to get its address.
9721   const Value *OpVal = OpInfo.CallOperandVal;
9722   if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
9723       isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
9724     OpInfo.CallOperand = DAG.getConstantPool(
9725         cast<Constant>(OpVal), TLI.getPointerTy(DAG.getDataLayout()));
9726     return Chain;
9727   }
9728 
9729   // Otherwise, create a stack slot and emit a store to it before the asm.
9730   Type *Ty = OpVal->getType();
9731   auto &DL = DAG.getDataLayout();
9732   TypeSize TySize = DL.getTypeAllocSize(Ty);
9733   MachineFunction &MF = DAG.getMachineFunction();
9734   const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
9735   int StackID = 0;
9736   if (TySize.isScalable())
9737     StackID = TFI->getStackIDForScalableVectors();
9738   int SSFI = MF.getFrameInfo().CreateStackObject(TySize.getKnownMinValue(),
9739                                                  DL.getPrefTypeAlign(Ty), false,
9740                                                  nullptr, StackID);
9741   SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getFrameIndexTy(DL));
9742   Chain = DAG.getTruncStore(Chain, Location, OpInfo.CallOperand, StackSlot,
9743                             MachinePointerInfo::getFixedStack(MF, SSFI),
9744                             TLI.getMemValueType(DL, Ty));
9745   OpInfo.CallOperand = StackSlot;
9746 
9747   return Chain;
9748 }
9749 
9750 /// GetRegistersForValue - Assign registers (virtual or physical) for the
9751 /// specified operand.  We prefer to assign virtual registers, to allow the
9752 /// register allocator to handle the assignment process.  However, if the asm
9753 /// uses features that we can't model on machineinstrs, we have SDISel do the
9754 /// allocation.  This produces generally horrible, but correct, code.
9755 ///
9756 ///   OpInfo describes the operand
9757 ///   RefOpInfo describes the matching operand if any, the operand otherwise
9758 static std::optional<unsigned>
9759 getRegistersForValue(SelectionDAG &DAG, const SDLoc &DL,
9760                      SDISelAsmOperandInfo &OpInfo,
9761                      SDISelAsmOperandInfo &RefOpInfo) {
9762   LLVMContext &Context = *DAG.getContext();
9763   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9764 
9765   MachineFunction &MF = DAG.getMachineFunction();
9766   SmallVector<Register, 4> Regs;
9767   const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
9768 
9769   // No work to do for memory/address operands.
9770   if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9771       OpInfo.ConstraintType == TargetLowering::C_Address)
9772     return std::nullopt;
9773 
9774   // If this is a constraint for a single physreg, or a constraint for a
9775   // register class, find it.
9776   unsigned AssignedReg;
9777   const TargetRegisterClass *RC;
9778   std::tie(AssignedReg, RC) = TLI.getRegForInlineAsmConstraint(
9779       &TRI, RefOpInfo.ConstraintCode, RefOpInfo.ConstraintVT);
9780   // RC is unset only on failure. Return immediately.
9781   if (!RC)
9782     return std::nullopt;
9783 
9784   // Get the actual register value type.  This is important, because the user
9785   // may have asked for (e.g.) the AX register in i32 type.  We need to
9786   // remember that AX is actually i16 to get the right extension.
9787   const MVT RegVT = *TRI.legalclasstypes_begin(*RC);
9788 
9789   if (OpInfo.ConstraintVT != MVT::Other && RegVT != MVT::Untyped) {
9790     // If this is an FP operand in an integer register (or visa versa), or more
9791     // generally if the operand value disagrees with the register class we plan
9792     // to stick it in, fix the operand type.
9793     //
9794     // If this is an input value, the bitcast to the new type is done now.
9795     // Bitcast for output value is done at the end of visitInlineAsm().
9796     if ((OpInfo.Type == InlineAsm::isOutput ||
9797          OpInfo.Type == InlineAsm::isInput) &&
9798         !TRI.isTypeLegalForClass(*RC, OpInfo.ConstraintVT)) {
9799       // Try to convert to the first EVT that the reg class contains.  If the
9800       // types are identical size, use a bitcast to convert (e.g. two differing
9801       // vector types).  Note: output bitcast is done at the end of
9802       // visitInlineAsm().
9803       if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
9804         // Exclude indirect inputs while they are unsupported because the code
9805         // to perform the load is missing and thus OpInfo.CallOperand still
9806         // refers to the input address rather than the pointed-to value.
9807         if (OpInfo.Type == InlineAsm::isInput && !OpInfo.isIndirect)
9808           OpInfo.CallOperand =
9809               DAG.getNode(ISD::BITCAST, DL, RegVT, OpInfo.CallOperand);
9810         OpInfo.ConstraintVT = RegVT;
9811         // If the operand is an FP value and we want it in integer registers,
9812         // use the corresponding integer type. This turns an f64 value into
9813         // i64, which can be passed with two i32 values on a 32-bit machine.
9814       } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
9815         MVT VT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
9816         if (OpInfo.Type == InlineAsm::isInput)
9817           OpInfo.CallOperand =
9818               DAG.getNode(ISD::BITCAST, DL, VT, OpInfo.CallOperand);
9819         OpInfo.ConstraintVT = VT;
9820       }
9821     }
9822   }
9823 
9824   // No need to allocate a matching input constraint since the constraint it's
9825   // matching to has already been allocated.
9826   if (OpInfo.isMatchingInputConstraint())
9827     return std::nullopt;
9828 
9829   EVT ValueVT = OpInfo.ConstraintVT;
9830   if (OpInfo.ConstraintVT == MVT::Other)
9831     ValueVT = RegVT;
9832 
9833   // Initialize NumRegs.
9834   unsigned NumRegs = 1;
9835   if (OpInfo.ConstraintVT != MVT::Other)
9836     NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT, RegVT);
9837 
9838   // If this is a constraint for a specific physical register, like {r17},
9839   // assign it now.
9840 
9841   // If this associated to a specific register, initialize iterator to correct
9842   // place. If virtual, make sure we have enough registers
9843 
9844   // Initialize iterator if necessary
9845   TargetRegisterClass::iterator I = RC->begin();
9846   MachineRegisterInfo &RegInfo = MF.getRegInfo();
9847 
9848   // Do not check for single registers.
9849   if (AssignedReg) {
9850     I = std::find(I, RC->end(), AssignedReg);
9851     if (I == RC->end()) {
9852       // RC does not contain the selected register, which indicates a
9853       // mismatch between the register and the required type/bitwidth.
9854       return {AssignedReg};
9855     }
9856   }
9857 
9858   for (; NumRegs; --NumRegs, ++I) {
9859     assert(I != RC->end() && "Ran out of registers to allocate!");
9860     Register R = AssignedReg ? Register(*I) : RegInfo.createVirtualRegister(RC);
9861     Regs.push_back(R);
9862   }
9863 
9864   OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
9865   return std::nullopt;
9866 }
9867 
9868 static unsigned
9869 findMatchingInlineAsmOperand(unsigned OperandNo,
9870                              const std::vector<SDValue> &AsmNodeOperands) {
9871   // Scan until we find the definition we already emitted of this operand.
9872   unsigned CurOp = InlineAsm::Op_FirstOperand;
9873   for (; OperandNo; --OperandNo) {
9874     // Advance to the next operand.
9875     unsigned OpFlag = AsmNodeOperands[CurOp]->getAsZExtVal();
9876     const InlineAsm::Flag F(OpFlag);
9877     assert(
9878         (F.isRegDefKind() || F.isRegDefEarlyClobberKind() || F.isMemKind()) &&
9879         "Skipped past definitions?");
9880     CurOp += F.getNumOperandRegisters() + 1;
9881   }
9882   return CurOp;
9883 }
9884 
9885 namespace {
9886 
9887 class ExtraFlags {
9888   unsigned Flags = 0;
9889 
9890 public:
9891   explicit ExtraFlags(const CallBase &Call) {
9892     const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9893     if (IA->hasSideEffects())
9894       Flags |= InlineAsm::Extra_HasSideEffects;
9895     if (IA->isAlignStack())
9896       Flags |= InlineAsm::Extra_IsAlignStack;
9897     if (Call.isConvergent())
9898       Flags |= InlineAsm::Extra_IsConvergent;
9899     Flags |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
9900   }
9901 
9902   void update(const TargetLowering::AsmOperandInfo &OpInfo) {
9903     // Ideally, we would only check against memory constraints.  However, the
9904     // meaning of an Other constraint can be target-specific and we can't easily
9905     // reason about it.  Therefore, be conservative and set MayLoad/MayStore
9906     // for Other constraints as well.
9907     if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
9908         OpInfo.ConstraintType == TargetLowering::C_Other) {
9909       if (OpInfo.Type == InlineAsm::isInput)
9910         Flags |= InlineAsm::Extra_MayLoad;
9911       else if (OpInfo.Type == InlineAsm::isOutput)
9912         Flags |= InlineAsm::Extra_MayStore;
9913       else if (OpInfo.Type == InlineAsm::isClobber)
9914         Flags |= (InlineAsm::Extra_MayLoad | InlineAsm::Extra_MayStore);
9915     }
9916   }
9917 
9918   unsigned get() const { return Flags; }
9919 };
9920 
9921 } // end anonymous namespace
9922 
9923 static bool isFunction(SDValue Op) {
9924   if (Op && Op.getOpcode() == ISD::GlobalAddress) {
9925     if (auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
9926       auto Fn = dyn_cast_or_null<Function>(GA->getGlobal());
9927 
9928       // In normal "call dllimport func" instruction (non-inlineasm) it force
9929       // indirect access by specifing call opcode. And usually specially print
9930       // asm with indirect symbol (i.g: "*") according to opcode. Inline asm can
9931       // not do in this way now. (In fact, this is similar with "Data Access"
9932       // action). So here we ignore dllimport function.
9933       if (Fn && !Fn->hasDLLImportStorageClass())
9934         return true;
9935     }
9936   }
9937   return false;
9938 }
9939 
9940 /// visitInlineAsm - Handle a call to an InlineAsm object.
9941 void SelectionDAGBuilder::visitInlineAsm(const CallBase &Call,
9942                                          const BasicBlock *EHPadBB) {
9943   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
9944 
9945   /// ConstraintOperands - Information about all of the constraints.
9946   SmallVector<SDISelAsmOperandInfo, 16> ConstraintOperands;
9947 
9948   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9949   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(
9950       DAG.getDataLayout(), DAG.getSubtarget().getRegisterInfo(), Call);
9951 
9952   // First Pass: Calculate HasSideEffects and ExtraFlags (AlignStack,
9953   // AsmDialect, MayLoad, MayStore).
9954   bool HasSideEffect = IA->hasSideEffects();
9955   ExtraFlags ExtraInfo(Call);
9956 
9957   for (auto &T : TargetConstraints) {
9958     ConstraintOperands.push_back(SDISelAsmOperandInfo(T));
9959     SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
9960 
9961     if (OpInfo.CallOperandVal)
9962       OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
9963 
9964     if (!HasSideEffect)
9965       HasSideEffect = OpInfo.hasMemory(TLI);
9966 
9967     // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
9968     // FIXME: Could we compute this on OpInfo rather than T?
9969 
9970     // Compute the constraint code and ConstraintType to use.
9971     TLI.ComputeConstraintToUse(T, SDValue());
9972 
9973     if (T.ConstraintType == TargetLowering::C_Immediate &&
9974         OpInfo.CallOperand && !isa<ConstantSDNode>(OpInfo.CallOperand))
9975       // We've delayed emitting a diagnostic like the "n" constraint because
9976       // inlining could cause an integer showing up.
9977       return emitInlineAsmError(Call, "constraint '" + Twine(T.ConstraintCode) +
9978                                           "' expects an integer constant "
9979                                           "expression");
9980 
9981     ExtraInfo.update(T);
9982   }
9983 
9984   // We won't need to flush pending loads if this asm doesn't touch
9985   // memory and is nonvolatile.
9986   SDValue Glue, Chain = (HasSideEffect) ? getRoot() : DAG.getRoot();
9987 
9988   bool EmitEHLabels = isa<InvokeInst>(Call);
9989   if (EmitEHLabels) {
9990     assert(EHPadBB && "InvokeInst must have an EHPadBB");
9991   }
9992   bool IsCallBr = isa<CallBrInst>(Call);
9993 
9994   if (IsCallBr || EmitEHLabels) {
9995     // If this is a callbr or invoke we need to flush pending exports since
9996     // inlineasm_br and invoke are terminators.
9997     // We need to do this before nodes are glued to the inlineasm_br node.
9998     Chain = getControlRoot();
9999   }
10000 
10001   MCSymbol *BeginLabel = nullptr;
10002   if (EmitEHLabels) {
10003     Chain = lowerStartEH(Chain, EHPadBB, BeginLabel);
10004   }
10005 
10006   int OpNo = -1;
10007   SmallVector<StringRef> AsmStrs;
10008   IA->collectAsmStrs(AsmStrs);
10009 
10010   // Second pass over the constraints: compute which constraint option to use.
10011   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10012     if (OpInfo.hasArg() || OpInfo.Type == InlineAsm::isOutput)
10013       OpNo++;
10014 
10015     // If this is an output operand with a matching input operand, look up the
10016     // matching input. If their types mismatch, e.g. one is an integer, the
10017     // other is floating point, or their sizes are different, flag it as an
10018     // error.
10019     if (OpInfo.hasMatchingInput()) {
10020       SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
10021       patchMatchingInput(OpInfo, Input, DAG);
10022     }
10023 
10024     // Compute the constraint code and ConstraintType to use.
10025     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
10026 
10027     if ((OpInfo.ConstraintType == TargetLowering::C_Memory &&
10028          OpInfo.Type == InlineAsm::isClobber) ||
10029         OpInfo.ConstraintType == TargetLowering::C_Address)
10030       continue;
10031 
10032     // In Linux PIC model, there are 4 cases about value/label addressing:
10033     //
10034     // 1: Function call or Label jmp inside the module.
10035     // 2: Data access (such as global variable, static variable) inside module.
10036     // 3: Function call or Label jmp outside the module.
10037     // 4: Data access (such as global variable) outside the module.
10038     //
10039     // Due to current llvm inline asm architecture designed to not "recognize"
10040     // the asm code, there are quite troubles for us to treat mem addressing
10041     // differently for same value/adress used in different instuctions.
10042     // For example, in pic model, call a func may in plt way or direclty
10043     // pc-related, but lea/mov a function adress may use got.
10044     //
10045     // Here we try to "recognize" function call for the case 1 and case 3 in
10046     // inline asm. And try to adjust the constraint for them.
10047     //
10048     // TODO: Due to current inline asm didn't encourage to jmp to the outsider
10049     // label, so here we don't handle jmp function label now, but we need to
10050     // enhance it (especilly in PIC model) if we meet meaningful requirements.
10051     if (OpInfo.isIndirect && isFunction(OpInfo.CallOperand) &&
10052         TLI.isInlineAsmTargetBranch(AsmStrs, OpNo) &&
10053         TM.getCodeModel() != CodeModel::Large) {
10054       OpInfo.isIndirect = false;
10055       OpInfo.ConstraintType = TargetLowering::C_Address;
10056     }
10057 
10058     // If this is a memory input, and if the operand is not indirect, do what we
10059     // need to provide an address for the memory input.
10060     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
10061         !OpInfo.isIndirect) {
10062       assert((OpInfo.isMultipleAlternative ||
10063               (OpInfo.Type == InlineAsm::isInput)) &&
10064              "Can only indirectify direct input operands!");
10065 
10066       // Memory operands really want the address of the value.
10067       Chain = getAddressForMemoryInput(Chain, getCurSDLoc(), OpInfo, DAG);
10068 
10069       // There is no longer a Value* corresponding to this operand.
10070       OpInfo.CallOperandVal = nullptr;
10071 
10072       // It is now an indirect operand.
10073       OpInfo.isIndirect = true;
10074     }
10075 
10076   }
10077 
10078   // AsmNodeOperands - The operands for the ISD::INLINEASM node.
10079   std::vector<SDValue> AsmNodeOperands;
10080   AsmNodeOperands.push_back(SDValue());  // reserve space for input chain
10081   AsmNodeOperands.push_back(DAG.getTargetExternalSymbol(
10082       IA->getAsmString().c_str(), TLI.getProgramPointerTy(DAG.getDataLayout())));
10083 
10084   // If we have a !srcloc metadata node associated with it, we want to attach
10085   // this to the ultimately generated inline asm machineinstr.  To do this, we
10086   // pass in the third operand as this (potentially null) inline asm MDNode.
10087   const MDNode *SrcLoc = Call.getMetadata("srcloc");
10088   AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
10089 
10090   // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
10091   // bits as operand 3.
10092   AsmNodeOperands.push_back(DAG.getTargetConstant(
10093       ExtraInfo.get(), getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10094 
10095   // Third pass: Loop over operands to prepare DAG-level operands.. As part of
10096   // this, assign virtual and physical registers for inputs and otput.
10097   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10098     // Assign Registers.
10099     SDISelAsmOperandInfo &RefOpInfo =
10100         OpInfo.isMatchingInputConstraint()
10101             ? ConstraintOperands[OpInfo.getMatchedOperand()]
10102             : OpInfo;
10103     const auto RegError =
10104         getRegistersForValue(DAG, getCurSDLoc(), OpInfo, RefOpInfo);
10105     if (RegError) {
10106       const MachineFunction &MF = DAG.getMachineFunction();
10107       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10108       const char *RegName = TRI.getName(*RegError);
10109       emitInlineAsmError(Call, "register '" + Twine(RegName) +
10110                                    "' allocated for constraint '" +
10111                                    Twine(OpInfo.ConstraintCode) +
10112                                    "' does not match required type");
10113       return;
10114     }
10115 
10116     auto DetectWriteToReservedRegister = [&]() {
10117       const MachineFunction &MF = DAG.getMachineFunction();
10118       const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10119       for (unsigned Reg : OpInfo.AssignedRegs.Regs) {
10120         if (Register::isPhysicalRegister(Reg) &&
10121             TRI.isInlineAsmReadOnlyReg(MF, Reg)) {
10122           const char *RegName = TRI.getName(Reg);
10123           emitInlineAsmError(Call, "write to reserved register '" +
10124                                        Twine(RegName) + "'");
10125           return true;
10126         }
10127       }
10128       return false;
10129     };
10130     assert((OpInfo.ConstraintType != TargetLowering::C_Address ||
10131             (OpInfo.Type == InlineAsm::isInput &&
10132              !OpInfo.isMatchingInputConstraint())) &&
10133            "Only address as input operand is allowed.");
10134 
10135     switch (OpInfo.Type) {
10136     case InlineAsm::isOutput:
10137       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10138         const InlineAsm::ConstraintCode ConstraintID =
10139             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10140         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10141                "Failed to convert memory constraint code to constraint id.");
10142 
10143         // Add information to the INLINEASM node to know about this output.
10144         InlineAsm::Flag OpFlags(InlineAsm::Kind::Mem, 1);
10145         OpFlags.setMemConstraint(ConstraintID);
10146         AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags, getCurSDLoc(),
10147                                                         MVT::i32));
10148         AsmNodeOperands.push_back(OpInfo.CallOperand);
10149       } else {
10150         // Otherwise, this outputs to a register (directly for C_Register /
10151         // C_RegisterClass, and a target-defined fashion for
10152         // C_Immediate/C_Other). Find a register that we can use.
10153         if (OpInfo.AssignedRegs.Regs.empty()) {
10154           emitInlineAsmError(
10155               Call, "couldn't allocate output register for constraint '" +
10156                         Twine(OpInfo.ConstraintCode) + "'");
10157           return;
10158         }
10159 
10160         if (DetectWriteToReservedRegister())
10161           return;
10162 
10163         // Add information to the INLINEASM node to know that this register is
10164         // set.
10165         OpInfo.AssignedRegs.AddInlineAsmOperands(
10166             OpInfo.isEarlyClobber ? InlineAsm::Kind::RegDefEarlyClobber
10167                                   : InlineAsm::Kind::RegDef,
10168             false, 0, getCurSDLoc(), DAG, AsmNodeOperands);
10169       }
10170       break;
10171 
10172     case InlineAsm::isInput:
10173     case InlineAsm::isLabel: {
10174       SDValue InOperandVal = OpInfo.CallOperand;
10175 
10176       if (OpInfo.isMatchingInputConstraint()) {
10177         // If this is required to match an output register we have already set,
10178         // just use its register.
10179         auto CurOp = findMatchingInlineAsmOperand(OpInfo.getMatchedOperand(),
10180                                                   AsmNodeOperands);
10181         InlineAsm::Flag Flag(AsmNodeOperands[CurOp]->getAsZExtVal());
10182         if (Flag.isRegDefKind() || Flag.isRegDefEarlyClobberKind()) {
10183           if (OpInfo.isIndirect) {
10184             // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
10185             emitInlineAsmError(Call, "inline asm not supported yet: "
10186                                      "don't know how to handle tied "
10187                                      "indirect register inputs");
10188             return;
10189           }
10190 
10191           SmallVector<Register, 4> Regs;
10192           MachineFunction &MF = DAG.getMachineFunction();
10193           MachineRegisterInfo &MRI = MF.getRegInfo();
10194           const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
10195           auto *R = cast<RegisterSDNode>(AsmNodeOperands[CurOp+1]);
10196           Register TiedReg = R->getReg();
10197           MVT RegVT = R->getSimpleValueType(0);
10198           const TargetRegisterClass *RC =
10199               TiedReg.isVirtual()     ? MRI.getRegClass(TiedReg)
10200               : RegVT != MVT::Untyped ? TLI.getRegClassFor(RegVT)
10201                                       : TRI.getMinimalPhysRegClass(TiedReg);
10202           for (unsigned i = 0, e = Flag.getNumOperandRegisters(); i != e; ++i)
10203             Regs.push_back(MRI.createVirtualRegister(RC));
10204 
10205           RegsForValue MatchedRegs(Regs, RegVT, InOperandVal.getValueType());
10206 
10207           SDLoc dl = getCurSDLoc();
10208           // Use the produced MatchedRegs object to
10209           MatchedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue, &Call);
10210           MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, true,
10211                                            OpInfo.getMatchedOperand(), dl, DAG,
10212                                            AsmNodeOperands);
10213           break;
10214         }
10215 
10216         assert(Flag.isMemKind() && "Unknown matching constraint!");
10217         assert(Flag.getNumOperandRegisters() == 1 &&
10218                "Unexpected number of operands");
10219         // Add information to the INLINEASM node to know about this input.
10220         // See InlineAsm.h isUseOperandTiedToDef.
10221         Flag.clearMemConstraint();
10222         Flag.setMatchingOp(OpInfo.getMatchedOperand());
10223         AsmNodeOperands.push_back(DAG.getTargetConstant(
10224             Flag, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10225         AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
10226         break;
10227       }
10228 
10229       // Treat indirect 'X' constraint as memory.
10230       if (OpInfo.ConstraintType == TargetLowering::C_Other &&
10231           OpInfo.isIndirect)
10232         OpInfo.ConstraintType = TargetLowering::C_Memory;
10233 
10234       if (OpInfo.ConstraintType == TargetLowering::C_Immediate ||
10235           OpInfo.ConstraintType == TargetLowering::C_Other) {
10236         std::vector<SDValue> Ops;
10237         TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
10238                                           Ops, DAG);
10239         if (Ops.empty()) {
10240           if (OpInfo.ConstraintType == TargetLowering::C_Immediate)
10241             if (isa<ConstantSDNode>(InOperandVal)) {
10242               emitInlineAsmError(Call, "value out of range for constraint '" +
10243                                            Twine(OpInfo.ConstraintCode) + "'");
10244               return;
10245             }
10246 
10247           emitInlineAsmError(Call,
10248                              "invalid operand for inline asm constraint '" +
10249                                  Twine(OpInfo.ConstraintCode) + "'");
10250           return;
10251         }
10252 
10253         // Add information to the INLINEASM node to know about this input.
10254         InlineAsm::Flag ResOpType(InlineAsm::Kind::Imm, Ops.size());
10255         AsmNodeOperands.push_back(DAG.getTargetConstant(
10256             ResOpType, getCurSDLoc(), TLI.getPointerTy(DAG.getDataLayout())));
10257         llvm::append_range(AsmNodeOperands, Ops);
10258         break;
10259       }
10260 
10261       if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
10262         assert((OpInfo.isIndirect ||
10263                 OpInfo.ConstraintType != TargetLowering::C_Memory) &&
10264                "Operand must be indirect to be a mem!");
10265         assert(InOperandVal.getValueType() ==
10266                    TLI.getPointerTy(DAG.getDataLayout()) &&
10267                "Memory operands expect pointer values");
10268 
10269         const InlineAsm::ConstraintCode ConstraintID =
10270             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10271         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10272                "Failed to convert memory constraint code to constraint id.");
10273 
10274         // Add information to the INLINEASM node to know about this input.
10275         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10276         ResOpType.setMemConstraint(ConstraintID);
10277         AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
10278                                                         getCurSDLoc(),
10279                                                         MVT::i32));
10280         AsmNodeOperands.push_back(InOperandVal);
10281         break;
10282       }
10283 
10284       if (OpInfo.ConstraintType == TargetLowering::C_Address) {
10285         const InlineAsm::ConstraintCode ConstraintID =
10286             TLI.getInlineAsmMemConstraint(OpInfo.ConstraintCode);
10287         assert(ConstraintID != InlineAsm::ConstraintCode::Unknown &&
10288                "Failed to convert memory constraint code to constraint id.");
10289 
10290         InlineAsm::Flag ResOpType(InlineAsm::Kind::Mem, 1);
10291 
10292         SDValue AsmOp = InOperandVal;
10293         if (isFunction(InOperandVal)) {
10294           auto *GA = cast<GlobalAddressSDNode>(InOperandVal);
10295           ResOpType = InlineAsm::Flag(InlineAsm::Kind::Func, 1);
10296           AsmOp = DAG.getTargetGlobalAddress(GA->getGlobal(), getCurSDLoc(),
10297                                              InOperandVal.getValueType(),
10298                                              GA->getOffset());
10299         }
10300 
10301         // Add information to the INLINEASM node to know about this input.
10302         ResOpType.setMemConstraint(ConstraintID);
10303 
10304         AsmNodeOperands.push_back(
10305             DAG.getTargetConstant(ResOpType, getCurSDLoc(), MVT::i32));
10306 
10307         AsmNodeOperands.push_back(AsmOp);
10308         break;
10309       }
10310 
10311       if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
10312           OpInfo.ConstraintType != TargetLowering::C_Register) {
10313         emitInlineAsmError(Call, "unknown asm constraint '" +
10314                                      Twine(OpInfo.ConstraintCode) + "'");
10315         return;
10316       }
10317 
10318       // TODO: Support this.
10319       if (OpInfo.isIndirect) {
10320         emitInlineAsmError(
10321             Call, "Don't know how to handle indirect register inputs yet "
10322                   "for constraint '" +
10323                       Twine(OpInfo.ConstraintCode) + "'");
10324         return;
10325       }
10326 
10327       // Copy the input into the appropriate registers.
10328       if (OpInfo.AssignedRegs.Regs.empty()) {
10329         emitInlineAsmError(Call,
10330                            "couldn't allocate input reg for constraint '" +
10331                                Twine(OpInfo.ConstraintCode) + "'");
10332         return;
10333       }
10334 
10335       if (DetectWriteToReservedRegister())
10336         return;
10337 
10338       SDLoc dl = getCurSDLoc();
10339 
10340       OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, dl, Chain, &Glue,
10341                                         &Call);
10342 
10343       OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::RegUse, false,
10344                                                0, dl, DAG, AsmNodeOperands);
10345       break;
10346     }
10347     case InlineAsm::isClobber:
10348       // Add the clobbered value to the operand list, so that the register
10349       // allocator is aware that the physreg got clobbered.
10350       if (!OpInfo.AssignedRegs.Regs.empty())
10351         OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind::Clobber,
10352                                                  false, 0, getCurSDLoc(), DAG,
10353                                                  AsmNodeOperands);
10354       break;
10355     }
10356   }
10357 
10358   // Finish up input operands.  Set the input chain and add the flag last.
10359   AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
10360   if (Glue.getNode()) AsmNodeOperands.push_back(Glue);
10361 
10362   unsigned ISDOpc = IsCallBr ? ISD::INLINEASM_BR : ISD::INLINEASM;
10363   Chain = DAG.getNode(ISDOpc, getCurSDLoc(),
10364                       DAG.getVTList(MVT::Other, MVT::Glue), AsmNodeOperands);
10365   Glue = Chain.getValue(1);
10366 
10367   // Do additional work to generate outputs.
10368 
10369   SmallVector<EVT, 1> ResultVTs;
10370   SmallVector<SDValue, 1> ResultValues;
10371   SmallVector<SDValue, 8> OutChains;
10372 
10373   llvm::Type *CallResultType = Call.getType();
10374   ArrayRef<Type *> ResultTypes;
10375   if (StructType *StructResult = dyn_cast<StructType>(CallResultType))
10376     ResultTypes = StructResult->elements();
10377   else if (!CallResultType->isVoidTy())
10378     ResultTypes = ArrayRef(CallResultType);
10379 
10380   auto CurResultType = ResultTypes.begin();
10381   auto handleRegAssign = [&](SDValue V) {
10382     assert(CurResultType != ResultTypes.end() && "Unexpected value");
10383     assert((*CurResultType)->isSized() && "Unexpected unsized type");
10384     EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), *CurResultType);
10385     ++CurResultType;
10386     // If the type of the inline asm call site return value is different but has
10387     // same size as the type of the asm output bitcast it.  One example of this
10388     // is for vectors with different width / number of elements.  This can
10389     // happen for register classes that can contain multiple different value
10390     // types.  The preg or vreg allocated may not have the same VT as was
10391     // expected.
10392     //
10393     // This can also happen for a return value that disagrees with the register
10394     // class it is put in, eg. a double in a general-purpose register on a
10395     // 32-bit machine.
10396     if (ResultVT != V.getValueType() &&
10397         ResultVT.getSizeInBits() == V.getValueSizeInBits())
10398       V = DAG.getNode(ISD::BITCAST, getCurSDLoc(), ResultVT, V);
10399     else if (ResultVT != V.getValueType() && ResultVT.isInteger() &&
10400              V.getValueType().isInteger()) {
10401       // If a result value was tied to an input value, the computed result
10402       // may have a wider width than the expected result.  Extract the
10403       // relevant portion.
10404       V = DAG.getNode(ISD::TRUNCATE, getCurSDLoc(), ResultVT, V);
10405     }
10406     assert(ResultVT == V.getValueType() && "Asm result value mismatch!");
10407     ResultVTs.push_back(ResultVT);
10408     ResultValues.push_back(V);
10409   };
10410 
10411   // Deal with output operands.
10412   for (SDISelAsmOperandInfo &OpInfo : ConstraintOperands) {
10413     if (OpInfo.Type == InlineAsm::isOutput) {
10414       SDValue Val;
10415       // Skip trivial output operands.
10416       if (OpInfo.AssignedRegs.Regs.empty())
10417         continue;
10418 
10419       switch (OpInfo.ConstraintType) {
10420       case TargetLowering::C_Register:
10421       case TargetLowering::C_RegisterClass:
10422         Val = OpInfo.AssignedRegs.getCopyFromRegs(DAG, FuncInfo, getCurSDLoc(),
10423                                                   Chain, &Glue, &Call);
10424         break;
10425       case TargetLowering::C_Immediate:
10426       case TargetLowering::C_Other:
10427         Val = TLI.LowerAsmOutputForConstraint(Chain, Glue, getCurSDLoc(),
10428                                               OpInfo, DAG);
10429         break;
10430       case TargetLowering::C_Memory:
10431         break; // Already handled.
10432       case TargetLowering::C_Address:
10433         break; // Silence warning.
10434       case TargetLowering::C_Unknown:
10435         assert(false && "Unexpected unknown constraint");
10436       }
10437 
10438       // Indirect output manifest as stores. Record output chains.
10439       if (OpInfo.isIndirect) {
10440         const Value *Ptr = OpInfo.CallOperandVal;
10441         assert(Ptr && "Expected value CallOperandVal for indirect asm operand");
10442         SDValue Store = DAG.getStore(Chain, getCurSDLoc(), Val, getValue(Ptr),
10443                                      MachinePointerInfo(Ptr));
10444         OutChains.push_back(Store);
10445       } else {
10446         // generate CopyFromRegs to associated registers.
10447         assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
10448         if (Val.getOpcode() == ISD::MERGE_VALUES) {
10449           for (const SDValue &V : Val->op_values())
10450             handleRegAssign(V);
10451         } else
10452           handleRegAssign(Val);
10453       }
10454     }
10455   }
10456 
10457   // Set results.
10458   if (!ResultValues.empty()) {
10459     assert(CurResultType == ResultTypes.end() &&
10460            "Mismatch in number of ResultTypes");
10461     assert(ResultValues.size() == ResultTypes.size() &&
10462            "Mismatch in number of output operands in asm result");
10463 
10464     SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
10465                             DAG.getVTList(ResultVTs), ResultValues);
10466     setValue(&Call, V);
10467   }
10468 
10469   // Collect store chains.
10470   if (!OutChains.empty())
10471     Chain = DAG.getNode(ISD::TokenFactor, getCurSDLoc(), MVT::Other, OutChains);
10472 
10473   if (EmitEHLabels) {
10474     Chain = lowerEndEH(Chain, cast<InvokeInst>(&Call), EHPadBB, BeginLabel);
10475   }
10476 
10477   // Only Update Root if inline assembly has a memory effect.
10478   if (ResultValues.empty() || HasSideEffect || !OutChains.empty() || IsCallBr ||
10479       EmitEHLabels)
10480     DAG.setRoot(Chain);
10481 }
10482 
10483 void SelectionDAGBuilder::emitInlineAsmError(const CallBase &Call,
10484                                              const Twine &Message) {
10485   LLVMContext &Ctx = *DAG.getContext();
10486   Ctx.diagnose(DiagnosticInfoInlineAsm(Call, Message));
10487 
10488   // Make sure we leave the DAG in a valid state
10489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10490   SmallVector<EVT, 1> ValueVTs;
10491   ComputeValueVTs(TLI, DAG.getDataLayout(), Call.getType(), ValueVTs);
10492 
10493   if (ValueVTs.empty())
10494     return;
10495 
10496   SmallVector<SDValue, 1> Ops;
10497   for (const EVT &VT : ValueVTs)
10498     Ops.push_back(DAG.getUNDEF(VT));
10499 
10500   setValue(&Call, DAG.getMergeValues(Ops, getCurSDLoc()));
10501 }
10502 
10503 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
10504   DAG.setRoot(DAG.getNode(ISD::VASTART, getCurSDLoc(),
10505                           MVT::Other, getRoot(),
10506                           getValue(I.getArgOperand(0)),
10507                           DAG.getSrcValue(I.getArgOperand(0))));
10508 }
10509 
10510 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
10511   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10512   const DataLayout &DL = DAG.getDataLayout();
10513   SDValue V = DAG.getVAArg(
10514       TLI.getMemValueType(DAG.getDataLayout(), I.getType()), getCurSDLoc(),
10515       getRoot(), getValue(I.getOperand(0)), DAG.getSrcValue(I.getOperand(0)),
10516       DL.getABITypeAlign(I.getType()).value());
10517   DAG.setRoot(V.getValue(1));
10518 
10519   if (I.getType()->isPointerTy())
10520     V = DAG.getPtrExtOrTrunc(
10521         V, getCurSDLoc(), TLI.getValueType(DAG.getDataLayout(), I.getType()));
10522   setValue(&I, V);
10523 }
10524 
10525 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
10526   DAG.setRoot(DAG.getNode(ISD::VAEND, getCurSDLoc(),
10527                           MVT::Other, getRoot(),
10528                           getValue(I.getArgOperand(0)),
10529                           DAG.getSrcValue(I.getArgOperand(0))));
10530 }
10531 
10532 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
10533   DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurSDLoc(),
10534                           MVT::Other, getRoot(),
10535                           getValue(I.getArgOperand(0)),
10536                           getValue(I.getArgOperand(1)),
10537                           DAG.getSrcValue(I.getArgOperand(0)),
10538                           DAG.getSrcValue(I.getArgOperand(1))));
10539 }
10540 
10541 SDValue SelectionDAGBuilder::lowerRangeToAssertZExt(SelectionDAG &DAG,
10542                                                     const Instruction &I,
10543                                                     SDValue Op) {
10544   std::optional<ConstantRange> CR = getRange(I);
10545 
10546   if (!CR || CR->isFullSet() || CR->isEmptySet() || CR->isUpperWrapped())
10547     return Op;
10548 
10549   APInt Lo = CR->getUnsignedMin();
10550   if (!Lo.isMinValue())
10551     return Op;
10552 
10553   APInt Hi = CR->getUnsignedMax();
10554   unsigned Bits = std::max(Hi.getActiveBits(),
10555                            static_cast<unsigned>(IntegerType::MIN_INT_BITS));
10556 
10557   EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
10558 
10559   SDLoc SL = getCurSDLoc();
10560 
10561   SDValue ZExt = DAG.getNode(ISD::AssertZext, SL, Op.getValueType(), Op,
10562                              DAG.getValueType(SmallVT));
10563   unsigned NumVals = Op.getNode()->getNumValues();
10564   if (NumVals == 1)
10565     return ZExt;
10566 
10567   SmallVector<SDValue, 4> Ops;
10568 
10569   Ops.push_back(ZExt);
10570   for (unsigned I = 1; I != NumVals; ++I)
10571     Ops.push_back(Op.getValue(I));
10572 
10573   return DAG.getMergeValues(Ops, SL);
10574 }
10575 
10576 /// Populate a CallLowerinInfo (into \p CLI) based on the properties of
10577 /// the call being lowered.
10578 ///
10579 /// This is a helper for lowering intrinsics that follow a target calling
10580 /// convention or require stack pointer adjustment. Only a subset of the
10581 /// intrinsic's operands need to participate in the calling convention.
10582 void SelectionDAGBuilder::populateCallLoweringInfo(
10583     TargetLowering::CallLoweringInfo &CLI, const CallBase *Call,
10584     unsigned ArgIdx, unsigned NumArgs, SDValue Callee, Type *ReturnTy,
10585     AttributeSet RetAttrs, bool IsPatchPoint) {
10586   TargetLowering::ArgListTy Args;
10587   Args.reserve(NumArgs);
10588 
10589   // Populate the argument list.
10590   // Attributes for args start at offset 1, after the return attribute.
10591   for (unsigned ArgI = ArgIdx, ArgE = ArgIdx + NumArgs;
10592        ArgI != ArgE; ++ArgI) {
10593     const Value *V = Call->getOperand(ArgI);
10594 
10595     assert(!V->getType()->isEmptyTy() && "Empty type passed to intrinsic.");
10596 
10597     TargetLowering::ArgListEntry Entry;
10598     Entry.Node = getValue(V);
10599     Entry.Ty = V->getType();
10600     Entry.setAttributes(Call, ArgI);
10601     Args.push_back(Entry);
10602   }
10603 
10604   CLI.setDebugLoc(getCurSDLoc())
10605       .setChain(getRoot())
10606       .setCallee(Call->getCallingConv(), ReturnTy, Callee, std::move(Args),
10607                  RetAttrs)
10608       .setDiscardResult(Call->use_empty())
10609       .setIsPatchPoint(IsPatchPoint)
10610       .setIsPreallocated(
10611           Call->countOperandBundlesOfType(LLVMContext::OB_preallocated) != 0);
10612 }
10613 
10614 /// Add a stack map intrinsic call's live variable operands to a stackmap
10615 /// or patchpoint target node's operand list.
10616 ///
10617 /// Constants are converted to TargetConstants purely as an optimization to
10618 /// avoid constant materialization and register allocation.
10619 ///
10620 /// FrameIndex operands are converted to TargetFrameIndex so that ISEL does not
10621 /// generate addess computation nodes, and so FinalizeISel can convert the
10622 /// TargetFrameIndex into a DirectMemRefOp StackMap location. This avoids
10623 /// address materialization and register allocation, but may also be required
10624 /// for correctness. If a StackMap (or PatchPoint) intrinsic directly uses an
10625 /// alloca in the entry block, then the runtime may assume that the alloca's
10626 /// StackMap location can be read immediately after compilation and that the
10627 /// location is valid at any point during execution (this is similar to the
10628 /// assumption made by the llvm.gcroot intrinsic). If the alloca's location were
10629 /// only available in a register, then the runtime would need to trap when
10630 /// execution reaches the StackMap in order to read the alloca's location.
10631 static void addStackMapLiveVars(const CallBase &Call, unsigned StartIdx,
10632                                 const SDLoc &DL, SmallVectorImpl<SDValue> &Ops,
10633                                 SelectionDAGBuilder &Builder) {
10634   SelectionDAG &DAG = Builder.DAG;
10635   for (unsigned I = StartIdx; I < Call.arg_size(); I++) {
10636     SDValue Op = Builder.getValue(Call.getArgOperand(I));
10637 
10638     // Things on the stack are pointer-typed, meaning that they are already
10639     // legal and can be emitted directly to target nodes.
10640     if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
10641       Ops.push_back(DAG.getTargetFrameIndex(FI->getIndex(), Op.getValueType()));
10642     } else {
10643       // Otherwise emit a target independent node to be legalised.
10644       Ops.push_back(Builder.getValue(Call.getArgOperand(I)));
10645     }
10646   }
10647 }
10648 
10649 /// Lower llvm.experimental.stackmap.
10650 void SelectionDAGBuilder::visitStackmap(const CallInst &CI) {
10651   // void @llvm.experimental.stackmap(i64 <id>, i32 <numShadowBytes>,
10652   //                                  [live variables...])
10653 
10654   assert(CI.getType()->isVoidTy() && "Stackmap cannot return a value.");
10655 
10656   SDValue Chain, InGlue, Callee;
10657   SmallVector<SDValue, 32> Ops;
10658 
10659   SDLoc DL = getCurSDLoc();
10660   Callee = getValue(CI.getCalledOperand());
10661 
10662   // The stackmap intrinsic only records the live variables (the arguments
10663   // passed to it) and emits NOPS (if requested). Unlike the patchpoint
10664   // intrinsic, this won't be lowered to a function call. This means we don't
10665   // have to worry about calling conventions and target specific lowering code.
10666   // Instead we perform the call lowering right here.
10667   //
10668   // chain, flag = CALLSEQ_START(chain, 0, 0)
10669   // chain, flag = STACKMAP(id, nbytes, ..., chain, flag)
10670   // chain, flag = CALLSEQ_END(chain, 0, 0, flag)
10671   //
10672   Chain = DAG.getCALLSEQ_START(getRoot(), 0, 0, DL);
10673   InGlue = Chain.getValue(1);
10674 
10675   // Add the STACKMAP operands, starting with DAG house-keeping.
10676   Ops.push_back(Chain);
10677   Ops.push_back(InGlue);
10678 
10679   // Add the <id>, <numShadowBytes> operands.
10680   //
10681   // These do not require legalisation, and can be emitted directly to target
10682   // constant nodes.
10683   SDValue ID = getValue(CI.getArgOperand(0));
10684   assert(ID.getValueType() == MVT::i64);
10685   SDValue IDConst =
10686       DAG.getTargetConstant(ID->getAsZExtVal(), DL, ID.getValueType());
10687   Ops.push_back(IDConst);
10688 
10689   SDValue Shad = getValue(CI.getArgOperand(1));
10690   assert(Shad.getValueType() == MVT::i32);
10691   SDValue ShadConst =
10692       DAG.getTargetConstant(Shad->getAsZExtVal(), DL, Shad.getValueType());
10693   Ops.push_back(ShadConst);
10694 
10695   // Add the live variables.
10696   addStackMapLiveVars(CI, 2, DL, Ops, *this);
10697 
10698   // Create the STACKMAP node.
10699   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10700   Chain = DAG.getNode(ISD::STACKMAP, DL, NodeTys, Ops);
10701   InGlue = Chain.getValue(1);
10702 
10703   Chain = DAG.getCALLSEQ_END(Chain, 0, 0, InGlue, DL);
10704 
10705   // Stackmaps don't generate values, so nothing goes into the NodeMap.
10706 
10707   // Set the root to the target-lowered call chain.
10708   DAG.setRoot(Chain);
10709 
10710   // Inform the Frame Information that we have a stackmap in this function.
10711   FuncInfo.MF->getFrameInfo().setHasStackMap();
10712 }
10713 
10714 /// Lower llvm.experimental.patchpoint directly to its target opcode.
10715 void SelectionDAGBuilder::visitPatchpoint(const CallBase &CB,
10716                                           const BasicBlock *EHPadBB) {
10717   // <ty> @llvm.experimental.patchpoint.<ty>(i64 <id>,
10718   //                                         i32 <numBytes>,
10719   //                                         i8* <target>,
10720   //                                         i32 <numArgs>,
10721   //                                         [Args...],
10722   //                                         [live variables...])
10723 
10724   CallingConv::ID CC = CB.getCallingConv();
10725   bool IsAnyRegCC = CC == CallingConv::AnyReg;
10726   bool HasDef = !CB.getType()->isVoidTy();
10727   SDLoc dl = getCurSDLoc();
10728   SDValue Callee = getValue(CB.getArgOperand(PatchPointOpers::TargetPos));
10729 
10730   // Handle immediate and symbolic callees.
10731   if (auto* ConstCallee = dyn_cast<ConstantSDNode>(Callee))
10732     Callee = DAG.getIntPtrConstant(ConstCallee->getZExtValue(), dl,
10733                                    /*isTarget=*/true);
10734   else if (auto* SymbolicCallee = dyn_cast<GlobalAddressSDNode>(Callee))
10735     Callee =  DAG.getTargetGlobalAddress(SymbolicCallee->getGlobal(),
10736                                          SDLoc(SymbolicCallee),
10737                                          SymbolicCallee->getValueType(0));
10738 
10739   // Get the real number of arguments participating in the call <numArgs>
10740   SDValue NArgVal = getValue(CB.getArgOperand(PatchPointOpers::NArgPos));
10741   unsigned NumArgs = NArgVal->getAsZExtVal();
10742 
10743   // Skip the four meta args: <id>, <numNopBytes>, <target>, <numArgs>
10744   // Intrinsics include all meta-operands up to but not including CC.
10745   unsigned NumMetaOpers = PatchPointOpers::CCPos;
10746   assert(CB.arg_size() >= NumMetaOpers + NumArgs &&
10747          "Not enough arguments provided to the patchpoint intrinsic");
10748 
10749   // For AnyRegCC the arguments are lowered later on manually.
10750   unsigned NumCallArgs = IsAnyRegCC ? 0 : NumArgs;
10751   Type *ReturnTy =
10752       IsAnyRegCC ? Type::getVoidTy(*DAG.getContext()) : CB.getType();
10753 
10754   TargetLowering::CallLoweringInfo CLI(DAG);
10755   populateCallLoweringInfo(CLI, &CB, NumMetaOpers, NumCallArgs, Callee,
10756                            ReturnTy, CB.getAttributes().getRetAttrs(), true);
10757   std::pair<SDValue, SDValue> Result = lowerInvokable(CLI, EHPadBB);
10758 
10759   SDNode *CallEnd = Result.second.getNode();
10760   if (CallEnd->getOpcode() == ISD::EH_LABEL)
10761     CallEnd = CallEnd->getOperand(0).getNode();
10762   if (HasDef && (CallEnd->getOpcode() == ISD::CopyFromReg))
10763     CallEnd = CallEnd->getOperand(0).getNode();
10764 
10765   /// Get a call instruction from the call sequence chain.
10766   /// Tail calls are not allowed.
10767   assert(CallEnd->getOpcode() == ISD::CALLSEQ_END &&
10768          "Expected a callseq node.");
10769   SDNode *Call = CallEnd->getOperand(0).getNode();
10770   bool HasGlue = Call->getGluedNode();
10771 
10772   // Replace the target specific call node with the patchable intrinsic.
10773   SmallVector<SDValue, 8> Ops;
10774 
10775   // Push the chain.
10776   Ops.push_back(*(Call->op_begin()));
10777 
10778   // Optionally, push the glue (if any).
10779   if (HasGlue)
10780     Ops.push_back(*(Call->op_end() - 1));
10781 
10782   // Push the register mask info.
10783   if (HasGlue)
10784     Ops.push_back(*(Call->op_end() - 2));
10785   else
10786     Ops.push_back(*(Call->op_end() - 1));
10787 
10788   // Add the <id> and <numBytes> constants.
10789   SDValue IDVal = getValue(CB.getArgOperand(PatchPointOpers::IDPos));
10790   Ops.push_back(DAG.getTargetConstant(IDVal->getAsZExtVal(), dl, MVT::i64));
10791   SDValue NBytesVal = getValue(CB.getArgOperand(PatchPointOpers::NBytesPos));
10792   Ops.push_back(DAG.getTargetConstant(NBytesVal->getAsZExtVal(), dl, MVT::i32));
10793 
10794   // Add the callee.
10795   Ops.push_back(Callee);
10796 
10797   // Adjust <numArgs> to account for any arguments that have been passed on the
10798   // stack instead.
10799   // Call Node: Chain, Target, {Args}, RegMask, [Glue]
10800   unsigned NumCallRegArgs = Call->getNumOperands() - (HasGlue ? 4 : 3);
10801   NumCallRegArgs = IsAnyRegCC ? NumArgs : NumCallRegArgs;
10802   Ops.push_back(DAG.getTargetConstant(NumCallRegArgs, dl, MVT::i32));
10803 
10804   // Add the calling convention
10805   Ops.push_back(DAG.getTargetConstant((unsigned)CC, dl, MVT::i32));
10806 
10807   // Add the arguments we omitted previously. The register allocator should
10808   // place these in any free register.
10809   if (IsAnyRegCC)
10810     for (unsigned i = NumMetaOpers, e = NumMetaOpers + NumArgs; i != e; ++i)
10811       Ops.push_back(getValue(CB.getArgOperand(i)));
10812 
10813   // Push the arguments from the call instruction.
10814   SDNode::op_iterator e = HasGlue ? Call->op_end()-2 : Call->op_end()-1;
10815   Ops.append(Call->op_begin() + 2, e);
10816 
10817   // Push live variables for the stack map.
10818   addStackMapLiveVars(CB, NumMetaOpers + NumArgs, dl, Ops, *this);
10819 
10820   SDVTList NodeTys;
10821   if (IsAnyRegCC && HasDef) {
10822     // Create the return types based on the intrinsic definition
10823     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10824     SmallVector<EVT, 3> ValueVTs;
10825     ComputeValueVTs(TLI, DAG.getDataLayout(), CB.getType(), ValueVTs);
10826     assert(ValueVTs.size() == 1 && "Expected only one return value type.");
10827 
10828     // There is always a chain and a glue type at the end
10829     ValueVTs.push_back(MVT::Other);
10830     ValueVTs.push_back(MVT::Glue);
10831     NodeTys = DAG.getVTList(ValueVTs);
10832   } else
10833     NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10834 
10835   // Replace the target specific call node with a PATCHPOINT node.
10836   SDValue PPV = DAG.getNode(ISD::PATCHPOINT, dl, NodeTys, Ops);
10837 
10838   // Update the NodeMap.
10839   if (HasDef) {
10840     if (IsAnyRegCC)
10841       setValue(&CB, SDValue(PPV.getNode(), 0));
10842     else
10843       setValue(&CB, Result.first);
10844   }
10845 
10846   // Fixup the consumers of the intrinsic. The chain and glue may be used in the
10847   // call sequence. Furthermore the location of the chain and glue can change
10848   // when the AnyReg calling convention is used and the intrinsic returns a
10849   // value.
10850   if (IsAnyRegCC && HasDef) {
10851     SDValue From[] = {SDValue(Call, 0), SDValue(Call, 1)};
10852     SDValue To[] = {PPV.getValue(1), PPV.getValue(2)};
10853     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10854   } else
10855     DAG.ReplaceAllUsesWith(Call, PPV.getNode());
10856   DAG.DeleteNode(Call);
10857 
10858   // Inform the Frame Information that we have a patchpoint in this function.
10859   FuncInfo.MF->getFrameInfo().setHasPatchPoint();
10860 }
10861 
10862 void SelectionDAGBuilder::visitVectorReduce(const CallInst &I,
10863                                             unsigned Intrinsic) {
10864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10865   SDValue Op1 = getValue(I.getArgOperand(0));
10866   SDValue Op2;
10867   if (I.arg_size() > 1)
10868     Op2 = getValue(I.getArgOperand(1));
10869   SDLoc dl = getCurSDLoc();
10870   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
10871   SDValue Res;
10872   SDNodeFlags SDFlags;
10873   if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
10874     SDFlags.copyFMF(*FPMO);
10875 
10876   switch (Intrinsic) {
10877   case Intrinsic::vector_reduce_fadd:
10878     if (SDFlags.hasAllowReassociation())
10879       Res = DAG.getNode(ISD::FADD, dl, VT, Op1,
10880                         DAG.getNode(ISD::VECREDUCE_FADD, dl, VT, Op2, SDFlags),
10881                         SDFlags);
10882     else
10883       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FADD, dl, VT, Op1, Op2, SDFlags);
10884     break;
10885   case Intrinsic::vector_reduce_fmul:
10886     if (SDFlags.hasAllowReassociation())
10887       Res = DAG.getNode(ISD::FMUL, dl, VT, Op1,
10888                         DAG.getNode(ISD::VECREDUCE_FMUL, dl, VT, Op2, SDFlags),
10889                         SDFlags);
10890     else
10891       Res = DAG.getNode(ISD::VECREDUCE_SEQ_FMUL, dl, VT, Op1, Op2, SDFlags);
10892     break;
10893   case Intrinsic::vector_reduce_add:
10894     Res = DAG.getNode(ISD::VECREDUCE_ADD, dl, VT, Op1);
10895     break;
10896   case Intrinsic::vector_reduce_mul:
10897     Res = DAG.getNode(ISD::VECREDUCE_MUL, dl, VT, Op1);
10898     break;
10899   case Intrinsic::vector_reduce_and:
10900     Res = DAG.getNode(ISD::VECREDUCE_AND, dl, VT, Op1);
10901     break;
10902   case Intrinsic::vector_reduce_or:
10903     Res = DAG.getNode(ISD::VECREDUCE_OR, dl, VT, Op1);
10904     break;
10905   case Intrinsic::vector_reduce_xor:
10906     Res = DAG.getNode(ISD::VECREDUCE_XOR, dl, VT, Op1);
10907     break;
10908   case Intrinsic::vector_reduce_smax:
10909     Res = DAG.getNode(ISD::VECREDUCE_SMAX, dl, VT, Op1);
10910     break;
10911   case Intrinsic::vector_reduce_smin:
10912     Res = DAG.getNode(ISD::VECREDUCE_SMIN, dl, VT, Op1);
10913     break;
10914   case Intrinsic::vector_reduce_umax:
10915     Res = DAG.getNode(ISD::VECREDUCE_UMAX, dl, VT, Op1);
10916     break;
10917   case Intrinsic::vector_reduce_umin:
10918     Res = DAG.getNode(ISD::VECREDUCE_UMIN, dl, VT, Op1);
10919     break;
10920   case Intrinsic::vector_reduce_fmax:
10921     Res = DAG.getNode(ISD::VECREDUCE_FMAX, dl, VT, Op1, SDFlags);
10922     break;
10923   case Intrinsic::vector_reduce_fmin:
10924     Res = DAG.getNode(ISD::VECREDUCE_FMIN, dl, VT, Op1, SDFlags);
10925     break;
10926   case Intrinsic::vector_reduce_fmaximum:
10927     Res = DAG.getNode(ISD::VECREDUCE_FMAXIMUM, dl, VT, Op1, SDFlags);
10928     break;
10929   case Intrinsic::vector_reduce_fminimum:
10930     Res = DAG.getNode(ISD::VECREDUCE_FMINIMUM, dl, VT, Op1, SDFlags);
10931     break;
10932   default:
10933     llvm_unreachable("Unhandled vector reduce intrinsic");
10934   }
10935   setValue(&I, Res);
10936 }
10937 
10938 /// Returns an AttributeList representing the attributes applied to the return
10939 /// value of the given call.
10940 static AttributeList getReturnAttrs(TargetLowering::CallLoweringInfo &CLI) {
10941   SmallVector<Attribute::AttrKind, 2> Attrs;
10942   if (CLI.RetSExt)
10943     Attrs.push_back(Attribute::SExt);
10944   if (CLI.RetZExt)
10945     Attrs.push_back(Attribute::ZExt);
10946   if (CLI.IsInReg)
10947     Attrs.push_back(Attribute::InReg);
10948 
10949   return AttributeList::get(CLI.RetTy->getContext(), AttributeList::ReturnIndex,
10950                             Attrs);
10951 }
10952 
10953 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
10954 /// implementation, which just calls LowerCall.
10955 /// FIXME: When all targets are
10956 /// migrated to using LowerCall, this hook should be integrated into SDISel.
10957 std::pair<SDValue, SDValue>
10958 TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
10959   // Handle the incoming return values from the call.
10960   CLI.Ins.clear();
10961   SmallVector<EVT, 4> RetTys;
10962   SmallVector<TypeSize, 4> Offsets;
10963   auto &DL = CLI.DAG.getDataLayout();
10964   ComputeValueVTs(*this, DL, CLI.RetTy, RetTys, &Offsets);
10965 
10966   if (CLI.IsPostTypeLegalization) {
10967     // If we are lowering a libcall after legalization, split the return type.
10968     SmallVector<EVT, 4> OldRetTys;
10969     SmallVector<TypeSize, 4> OldOffsets;
10970     RetTys.swap(OldRetTys);
10971     Offsets.swap(OldOffsets);
10972 
10973     for (size_t i = 0, e = OldRetTys.size(); i != e; ++i) {
10974       EVT RetVT = OldRetTys[i];
10975       uint64_t Offset = OldOffsets[i];
10976       MVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), RetVT);
10977       unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), RetVT);
10978       unsigned RegisterVTByteSZ = RegisterVT.getSizeInBits() / 8;
10979       RetTys.append(NumRegs, RegisterVT);
10980       for (unsigned j = 0; j != NumRegs; ++j)
10981         Offsets.push_back(TypeSize::getFixed(Offset + j * RegisterVTByteSZ));
10982     }
10983   }
10984 
10985   SmallVector<ISD::OutputArg, 4> Outs;
10986   GetReturnInfo(CLI.CallConv, CLI.RetTy, getReturnAttrs(CLI), Outs, *this, DL);
10987 
10988   bool CanLowerReturn =
10989       this->CanLowerReturn(CLI.CallConv, CLI.DAG.getMachineFunction(),
10990                            CLI.IsVarArg, Outs, CLI.RetTy->getContext(), CLI.RetTy);
10991 
10992   SDValue DemoteStackSlot;
10993   int DemoteStackIdx = -100;
10994   if (!CanLowerReturn) {
10995     // FIXME: equivalent assert?
10996     // assert(!CS.hasInAllocaArgument() &&
10997     //        "sret demotion is incompatible with inalloca");
10998     uint64_t TySize = DL.getTypeAllocSize(CLI.RetTy);
10999     Align Alignment = DL.getPrefTypeAlign(CLI.RetTy);
11000     MachineFunction &MF = CLI.DAG.getMachineFunction();
11001     DemoteStackIdx =
11002         MF.getFrameInfo().CreateStackObject(TySize, Alignment, false);
11003     Type *StackSlotPtrType =
11004         PointerType::get(CLI.RetTy->getContext(), DL.getAllocaAddrSpace());
11005 
11006     DemoteStackSlot = CLI.DAG.getFrameIndex(DemoteStackIdx, getFrameIndexTy(DL));
11007     ArgListEntry Entry;
11008     Entry.Node = DemoteStackSlot;
11009     Entry.Ty = StackSlotPtrType;
11010     Entry.IsSExt = false;
11011     Entry.IsZExt = false;
11012     Entry.IsInReg = false;
11013     Entry.IsSRet = true;
11014     Entry.IsNest = false;
11015     Entry.IsByVal = false;
11016     Entry.IsByRef = false;
11017     Entry.IsReturned = false;
11018     Entry.IsSwiftSelf = false;
11019     Entry.IsSwiftAsync = false;
11020     Entry.IsSwiftError = false;
11021     Entry.IsCFGuardTarget = false;
11022     Entry.Alignment = Alignment;
11023     CLI.getArgs().insert(CLI.getArgs().begin(), Entry);
11024     CLI.NumFixedArgs += 1;
11025     CLI.getArgs()[0].IndirectType = CLI.RetTy;
11026     CLI.RetTy = Type::getVoidTy(CLI.RetTy->getContext());
11027 
11028     // sret demotion isn't compatible with tail-calls, since the sret argument
11029     // points into the callers stack frame.
11030     CLI.IsTailCall = false;
11031   } else {
11032     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11033         CLI.RetTy, CLI.CallConv, CLI.IsVarArg, DL);
11034     for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
11035       ISD::ArgFlagsTy Flags;
11036       if (NeedsRegBlock) {
11037         Flags.setInConsecutiveRegs();
11038         if (I == RetTys.size() - 1)
11039           Flags.setInConsecutiveRegsLast();
11040       }
11041       EVT VT = RetTys[I];
11042       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11043                                                      CLI.CallConv, VT);
11044       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11045                                                        CLI.CallConv, VT);
11046       for (unsigned i = 0; i != NumRegs; ++i) {
11047         ISD::InputArg MyFlags;
11048         MyFlags.Flags = Flags;
11049         MyFlags.VT = RegisterVT;
11050         MyFlags.ArgVT = VT;
11051         MyFlags.Used = CLI.IsReturnValueUsed;
11052         if (CLI.RetTy->isPointerTy()) {
11053           MyFlags.Flags.setPointer();
11054           MyFlags.Flags.setPointerAddrSpace(
11055               cast<PointerType>(CLI.RetTy)->getAddressSpace());
11056         }
11057         if (CLI.RetSExt)
11058           MyFlags.Flags.setSExt();
11059         if (CLI.RetZExt)
11060           MyFlags.Flags.setZExt();
11061         if (CLI.IsInReg)
11062           MyFlags.Flags.setInReg();
11063         CLI.Ins.push_back(MyFlags);
11064       }
11065     }
11066   }
11067 
11068   // We push in swifterror return as the last element of CLI.Ins.
11069   ArgListTy &Args = CLI.getArgs();
11070   if (supportSwiftError()) {
11071     for (const ArgListEntry &Arg : Args) {
11072       if (Arg.IsSwiftError) {
11073         ISD::InputArg MyFlags;
11074         MyFlags.VT = getPointerTy(DL);
11075         MyFlags.ArgVT = EVT(getPointerTy(DL));
11076         MyFlags.Flags.setSwiftError();
11077         CLI.Ins.push_back(MyFlags);
11078       }
11079     }
11080   }
11081 
11082   // Handle all of the outgoing arguments.
11083   CLI.Outs.clear();
11084   CLI.OutVals.clear();
11085   for (unsigned i = 0, e = Args.size(); i != e; ++i) {
11086     SmallVector<EVT, 4> ValueVTs;
11087     ComputeValueVTs(*this, DL, Args[i].Ty, ValueVTs);
11088     // FIXME: Split arguments if CLI.IsPostTypeLegalization
11089     Type *FinalType = Args[i].Ty;
11090     if (Args[i].IsByVal)
11091       FinalType = Args[i].IndirectType;
11092     bool NeedsRegBlock = functionArgumentNeedsConsecutiveRegisters(
11093         FinalType, CLI.CallConv, CLI.IsVarArg, DL);
11094     for (unsigned Value = 0, NumValues = ValueVTs.size(); Value != NumValues;
11095          ++Value) {
11096       EVT VT = ValueVTs[Value];
11097       Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
11098       SDValue Op = SDValue(Args[i].Node.getNode(),
11099                            Args[i].Node.getResNo() + Value);
11100       ISD::ArgFlagsTy Flags;
11101 
11102       // Certain targets (such as MIPS), may have a different ABI alignment
11103       // for a type depending on the context. Give the target a chance to
11104       // specify the alignment it wants.
11105       const Align OriginalAlignment(getABIAlignmentForCallingConv(ArgTy, DL));
11106       Flags.setOrigAlign(OriginalAlignment);
11107 
11108       if (Args[i].Ty->isPointerTy()) {
11109         Flags.setPointer();
11110         Flags.setPointerAddrSpace(
11111             cast<PointerType>(Args[i].Ty)->getAddressSpace());
11112       }
11113       if (Args[i].IsZExt)
11114         Flags.setZExt();
11115       if (Args[i].IsSExt)
11116         Flags.setSExt();
11117       if (Args[i].IsNoExt)
11118         Flags.setNoExt();
11119       if (Args[i].IsInReg) {
11120         // If we are using vectorcall calling convention, a structure that is
11121         // passed InReg - is surely an HVA
11122         if (CLI.CallConv == CallingConv::X86_VectorCall &&
11123             isa<StructType>(FinalType)) {
11124           // The first value of a structure is marked
11125           if (0 == Value)
11126             Flags.setHvaStart();
11127           Flags.setHva();
11128         }
11129         // Set InReg Flag
11130         Flags.setInReg();
11131       }
11132       if (Args[i].IsSRet)
11133         Flags.setSRet();
11134       if (Args[i].IsSwiftSelf)
11135         Flags.setSwiftSelf();
11136       if (Args[i].IsSwiftAsync)
11137         Flags.setSwiftAsync();
11138       if (Args[i].IsSwiftError)
11139         Flags.setSwiftError();
11140       if (Args[i].IsCFGuardTarget)
11141         Flags.setCFGuardTarget();
11142       if (Args[i].IsByVal)
11143         Flags.setByVal();
11144       if (Args[i].IsByRef)
11145         Flags.setByRef();
11146       if (Args[i].IsPreallocated) {
11147         Flags.setPreallocated();
11148         // Set the byval flag for CCAssignFn callbacks that don't know about
11149         // preallocated.  This way we can know how many bytes we should've
11150         // allocated and how many bytes a callee cleanup function will pop.  If
11151         // we port preallocated to more targets, we'll have to add custom
11152         // preallocated handling in the various CC lowering callbacks.
11153         Flags.setByVal();
11154       }
11155       if (Args[i].IsInAlloca) {
11156         Flags.setInAlloca();
11157         // Set the byval flag for CCAssignFn callbacks that don't know about
11158         // inalloca.  This way we can know how many bytes we should've allocated
11159         // and how many bytes a callee cleanup function will pop.  If we port
11160         // inalloca to more targets, we'll have to add custom inalloca handling
11161         // in the various CC lowering callbacks.
11162         Flags.setByVal();
11163       }
11164       Align MemAlign;
11165       if (Args[i].IsByVal || Args[i].IsInAlloca || Args[i].IsPreallocated) {
11166         unsigned FrameSize = DL.getTypeAllocSize(Args[i].IndirectType);
11167         Flags.setByValSize(FrameSize);
11168 
11169         // info is not there but there are cases it cannot get right.
11170         if (auto MA = Args[i].Alignment)
11171           MemAlign = *MA;
11172         else
11173           MemAlign = getByValTypeAlignment(Args[i].IndirectType, DL);
11174       } else if (auto MA = Args[i].Alignment) {
11175         MemAlign = *MA;
11176       } else {
11177         MemAlign = OriginalAlignment;
11178       }
11179       Flags.setMemAlign(MemAlign);
11180       if (Args[i].IsNest)
11181         Flags.setNest();
11182       if (NeedsRegBlock)
11183         Flags.setInConsecutiveRegs();
11184 
11185       MVT PartVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11186                                                  CLI.CallConv, VT);
11187       unsigned NumParts = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11188                                                         CLI.CallConv, VT);
11189       SmallVector<SDValue, 4> Parts(NumParts);
11190       ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
11191 
11192       if (Args[i].IsSExt)
11193         ExtendKind = ISD::SIGN_EXTEND;
11194       else if (Args[i].IsZExt)
11195         ExtendKind = ISD::ZERO_EXTEND;
11196 
11197       // Conservatively only handle 'returned' on non-vectors that can be lowered,
11198       // for now.
11199       if (Args[i].IsReturned && !Op.getValueType().isVector() &&
11200           CanLowerReturn) {
11201         assert((CLI.RetTy == Args[i].Ty ||
11202                 (CLI.RetTy->isPointerTy() && Args[i].Ty->isPointerTy() &&
11203                  CLI.RetTy->getPointerAddressSpace() ==
11204                      Args[i].Ty->getPointerAddressSpace())) &&
11205                RetTys.size() == NumValues && "unexpected use of 'returned'");
11206         // Before passing 'returned' to the target lowering code, ensure that
11207         // either the register MVT and the actual EVT are the same size or that
11208         // the return value and argument are extended in the same way; in these
11209         // cases it's safe to pass the argument register value unchanged as the
11210         // return register value (although it's at the target's option whether
11211         // to do so)
11212         // TODO: allow code generation to take advantage of partially preserved
11213         // registers rather than clobbering the entire register when the
11214         // parameter extension method is not compatible with the return
11215         // extension method
11216         if ((NumParts * PartVT.getSizeInBits() == VT.getSizeInBits()) ||
11217             (ExtendKind != ISD::ANY_EXTEND && CLI.RetSExt == Args[i].IsSExt &&
11218              CLI.RetZExt == Args[i].IsZExt))
11219           Flags.setReturned();
11220       }
11221 
11222       getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts, PartVT, CLI.CB,
11223                      CLI.CallConv, ExtendKind);
11224 
11225       for (unsigned j = 0; j != NumParts; ++j) {
11226         // if it isn't first piece, alignment must be 1
11227         // For scalable vectors the scalable part is currently handled
11228         // by individual targets, so we just use the known minimum size here.
11229         ISD::OutputArg MyFlags(
11230             Flags, Parts[j].getValueType().getSimpleVT(), VT,
11231             i < CLI.NumFixedArgs, i,
11232             j * Parts[j].getValueType().getStoreSize().getKnownMinValue());
11233         if (NumParts > 1 && j == 0)
11234           MyFlags.Flags.setSplit();
11235         else if (j != 0) {
11236           MyFlags.Flags.setOrigAlign(Align(1));
11237           if (j == NumParts - 1)
11238             MyFlags.Flags.setSplitEnd();
11239         }
11240 
11241         CLI.Outs.push_back(MyFlags);
11242         CLI.OutVals.push_back(Parts[j]);
11243       }
11244 
11245       if (NeedsRegBlock && Value == NumValues - 1)
11246         CLI.Outs[CLI.Outs.size() - 1].Flags.setInConsecutiveRegsLast();
11247     }
11248   }
11249 
11250   SmallVector<SDValue, 4> InVals;
11251   CLI.Chain = LowerCall(CLI, InVals);
11252 
11253   // Update CLI.InVals to use outside of this function.
11254   CLI.InVals = InVals;
11255 
11256   // Verify that the target's LowerCall behaved as expected.
11257   assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
11258          "LowerCall didn't return a valid chain!");
11259   assert((!CLI.IsTailCall || InVals.empty()) &&
11260          "LowerCall emitted a return value for a tail call!");
11261   assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
11262          "LowerCall didn't emit the correct number of values!");
11263 
11264   // For a tail call, the return value is merely live-out and there aren't
11265   // any nodes in the DAG representing it. Return a special value to
11266   // indicate that a tail call has been emitted and no more Instructions
11267   // should be processed in the current block.
11268   if (CLI.IsTailCall) {
11269     CLI.DAG.setRoot(CLI.Chain);
11270     return std::make_pair(SDValue(), SDValue());
11271   }
11272 
11273 #ifndef NDEBUG
11274   for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
11275     assert(InVals[i].getNode() && "LowerCall emitted a null value!");
11276     assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
11277            "LowerCall emitted a value with the wrong type!");
11278   }
11279 #endif
11280 
11281   SmallVector<SDValue, 4> ReturnValues;
11282   if (!CanLowerReturn) {
11283     // The instruction result is the result of loading from the
11284     // hidden sret parameter.
11285     MVT PtrVT = getPointerTy(DL, DL.getAllocaAddrSpace());
11286 
11287     unsigned NumValues = RetTys.size();
11288     ReturnValues.resize(NumValues);
11289     SmallVector<SDValue, 4> Chains(NumValues);
11290 
11291     // An aggregate return value cannot wrap around the address space, so
11292     // offsets to its parts don't wrap either.
11293     MachineFunction &MF = CLI.DAG.getMachineFunction();
11294     Align HiddenSRetAlign = MF.getFrameInfo().getObjectAlign(DemoteStackIdx);
11295     for (unsigned i = 0; i < NumValues; ++i) {
11296       SDValue Add =
11297           CLI.DAG.getNode(ISD::ADD, CLI.DL, PtrVT, DemoteStackSlot,
11298                           CLI.DAG.getConstant(Offsets[i], CLI.DL, PtrVT),
11299                           SDNodeFlags::NoUnsignedWrap);
11300       SDValue L = CLI.DAG.getLoad(
11301           RetTys[i], CLI.DL, CLI.Chain, Add,
11302           MachinePointerInfo::getFixedStack(CLI.DAG.getMachineFunction(),
11303                                             DemoteStackIdx, Offsets[i]),
11304           HiddenSRetAlign);
11305       ReturnValues[i] = L;
11306       Chains[i] = L.getValue(1);
11307     }
11308 
11309     CLI.Chain = CLI.DAG.getNode(ISD::TokenFactor, CLI.DL, MVT::Other, Chains);
11310   } else {
11311     // Collect the legal value parts into potentially illegal values
11312     // that correspond to the original function's return values.
11313     std::optional<ISD::NodeType> AssertOp;
11314     if (CLI.RetSExt)
11315       AssertOp = ISD::AssertSext;
11316     else if (CLI.RetZExt)
11317       AssertOp = ISD::AssertZext;
11318     unsigned CurReg = 0;
11319     for (EVT VT : RetTys) {
11320       MVT RegisterVT = getRegisterTypeForCallingConv(CLI.RetTy->getContext(),
11321                                                      CLI.CallConv, VT);
11322       unsigned NumRegs = getNumRegistersForCallingConv(CLI.RetTy->getContext(),
11323                                                        CLI.CallConv, VT);
11324 
11325       ReturnValues.push_back(getCopyFromParts(
11326           CLI.DAG, CLI.DL, &InVals[CurReg], NumRegs, RegisterVT, VT, nullptr,
11327           CLI.Chain, CLI.CallConv, AssertOp));
11328       CurReg += NumRegs;
11329     }
11330 
11331     // For a function returning void, there is no return value. We can't create
11332     // such a node, so we just return a null return value in that case. In
11333     // that case, nothing will actually look at the value.
11334     if (ReturnValues.empty())
11335       return std::make_pair(SDValue(), CLI.Chain);
11336   }
11337 
11338   SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
11339                                 CLI.DAG.getVTList(RetTys), ReturnValues);
11340   return std::make_pair(Res, CLI.Chain);
11341 }
11342 
11343 /// Places new result values for the node in Results (their number
11344 /// and types must exactly match those of the original return values of
11345 /// the node), or leaves Results empty, which indicates that the node is not
11346 /// to be custom lowered after all.
11347 void TargetLowering::LowerOperationWrapper(SDNode *N,
11348                                            SmallVectorImpl<SDValue> &Results,
11349                                            SelectionDAG &DAG) const {
11350   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
11351 
11352   if (!Res.getNode())
11353     return;
11354 
11355   // If the original node has one result, take the return value from
11356   // LowerOperation as is. It might not be result number 0.
11357   if (N->getNumValues() == 1) {
11358     Results.push_back(Res);
11359     return;
11360   }
11361 
11362   // If the original node has multiple results, then the return node should
11363   // have the same number of results.
11364   assert((N->getNumValues() == Res->getNumValues()) &&
11365       "Lowering returned the wrong number of results!");
11366 
11367   // Places new result values base on N result number.
11368   for (unsigned I = 0, E = N->getNumValues(); I != E; ++I)
11369     Results.push_back(Res.getValue(I));
11370 }
11371 
11372 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
11373   llvm_unreachable("LowerOperation not implemented for this target!");
11374 }
11375 
11376 void SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V,
11377                                                      unsigned Reg,
11378                                                      ISD::NodeType ExtendType) {
11379   SDValue Op = getNonRegisterValue(V);
11380   assert((Op.getOpcode() != ISD::CopyFromReg ||
11381           cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
11382          "Copy from a reg to the same reg!");
11383   assert(!Register::isPhysicalRegister(Reg) && "Is a physreg");
11384 
11385   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11386   // If this is an InlineAsm we have to match the registers required, not the
11387   // notional registers required by the type.
11388 
11389   RegsForValue RFV(V->getContext(), TLI, DAG.getDataLayout(), Reg, V->getType(),
11390                    std::nullopt); // This is not an ABI copy.
11391   SDValue Chain = DAG.getEntryNode();
11392 
11393   if (ExtendType == ISD::ANY_EXTEND) {
11394     auto PreferredExtendIt = FuncInfo.PreferredExtendType.find(V);
11395     if (PreferredExtendIt != FuncInfo.PreferredExtendType.end())
11396       ExtendType = PreferredExtendIt->second;
11397   }
11398   RFV.getCopyToRegs(Op, DAG, getCurSDLoc(), Chain, nullptr, V, ExtendType);
11399   PendingExports.push_back(Chain);
11400 }
11401 
11402 #include "llvm/CodeGen/SelectionDAGISel.h"
11403 
11404 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
11405 /// entry block, return true.  This includes arguments used by switches, since
11406 /// the switch may expand into multiple basic blocks.
11407 static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
11408   // With FastISel active, we may be splitting blocks, so force creation
11409   // of virtual registers for all non-dead arguments.
11410   if (FastISel)
11411     return A->use_empty();
11412 
11413   const BasicBlock &Entry = A->getParent()->front();
11414   for (const User *U : A->users())
11415     if (cast<Instruction>(U)->getParent() != &Entry || isa<SwitchInst>(U))
11416       return false;  // Use not in entry block.
11417 
11418   return true;
11419 }
11420 
11421 using ArgCopyElisionMapTy =
11422     DenseMap<const Argument *,
11423              std::pair<const AllocaInst *, const StoreInst *>>;
11424 
11425 /// Scan the entry block of the function in FuncInfo for arguments that look
11426 /// like copies into a local alloca. Record any copied arguments in
11427 /// ArgCopyElisionCandidates.
11428 static void
11429 findArgumentCopyElisionCandidates(const DataLayout &DL,
11430                                   FunctionLoweringInfo *FuncInfo,
11431                                   ArgCopyElisionMapTy &ArgCopyElisionCandidates) {
11432   // Record the state of every static alloca used in the entry block. Argument
11433   // allocas are all used in the entry block, so we need approximately as many
11434   // entries as we have arguments.
11435   enum StaticAllocaInfo { Unknown, Clobbered, Elidable };
11436   SmallDenseMap<const AllocaInst *, StaticAllocaInfo, 8> StaticAllocas;
11437   unsigned NumArgs = FuncInfo->Fn->arg_size();
11438   StaticAllocas.reserve(NumArgs * 2);
11439 
11440   auto GetInfoIfStaticAlloca = [&](const Value *V) -> StaticAllocaInfo * {
11441     if (!V)
11442       return nullptr;
11443     V = V->stripPointerCasts();
11444     const auto *AI = dyn_cast<AllocaInst>(V);
11445     if (!AI || !AI->isStaticAlloca() || !FuncInfo->StaticAllocaMap.count(AI))
11446       return nullptr;
11447     auto Iter = StaticAllocas.insert({AI, Unknown});
11448     return &Iter.first->second;
11449   };
11450 
11451   // Look for stores of arguments to static allocas. Look through bitcasts and
11452   // GEPs to handle type coercions, as long as the alloca is fully initialized
11453   // by the store. Any non-store use of an alloca escapes it and any subsequent
11454   // unanalyzed store might write it.
11455   // FIXME: Handle structs initialized with multiple stores.
11456   for (const Instruction &I : FuncInfo->Fn->getEntryBlock()) {
11457     // Look for stores, and handle non-store uses conservatively.
11458     const auto *SI = dyn_cast<StoreInst>(&I);
11459     if (!SI) {
11460       // We will look through cast uses, so ignore them completely.
11461       if (I.isCast())
11462         continue;
11463       // Ignore debug info and pseudo op intrinsics, they don't escape or store
11464       // to allocas.
11465       if (I.isDebugOrPseudoInst())
11466         continue;
11467       // This is an unknown instruction. Assume it escapes or writes to all
11468       // static alloca operands.
11469       for (const Use &U : I.operands()) {
11470         if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(U))
11471           *Info = StaticAllocaInfo::Clobbered;
11472       }
11473       continue;
11474     }
11475 
11476     // If the stored value is a static alloca, mark it as escaped.
11477     if (StaticAllocaInfo *Info = GetInfoIfStaticAlloca(SI->getValueOperand()))
11478       *Info = StaticAllocaInfo::Clobbered;
11479 
11480     // Check if the destination is a static alloca.
11481     const Value *Dst = SI->getPointerOperand()->stripPointerCasts();
11482     StaticAllocaInfo *Info = GetInfoIfStaticAlloca(Dst);
11483     if (!Info)
11484       continue;
11485     const AllocaInst *AI = cast<AllocaInst>(Dst);
11486 
11487     // Skip allocas that have been initialized or clobbered.
11488     if (*Info != StaticAllocaInfo::Unknown)
11489       continue;
11490 
11491     // Check if the stored value is an argument, and that this store fully
11492     // initializes the alloca.
11493     // If the argument type has padding bits we can't directly forward a pointer
11494     // as the upper bits may contain garbage.
11495     // Don't elide copies from the same argument twice.
11496     const Value *Val = SI->getValueOperand()->stripPointerCasts();
11497     const auto *Arg = dyn_cast<Argument>(Val);
11498     if (!Arg || Arg->hasPassPointeeByValueCopyAttr() ||
11499         Arg->getType()->isEmptyTy() ||
11500         DL.getTypeStoreSize(Arg->getType()) !=
11501             DL.getTypeAllocSize(AI->getAllocatedType()) ||
11502         !DL.typeSizeEqualsStoreSize(Arg->getType()) ||
11503         ArgCopyElisionCandidates.count(Arg)) {
11504       *Info = StaticAllocaInfo::Clobbered;
11505       continue;
11506     }
11507 
11508     LLVM_DEBUG(dbgs() << "Found argument copy elision candidate: " << *AI
11509                       << '\n');
11510 
11511     // Mark this alloca and store for argument copy elision.
11512     *Info = StaticAllocaInfo::Elidable;
11513     ArgCopyElisionCandidates.insert({Arg, {AI, SI}});
11514 
11515     // Stop scanning if we've seen all arguments. This will happen early in -O0
11516     // builds, which is useful, because -O0 builds have large entry blocks and
11517     // many allocas.
11518     if (ArgCopyElisionCandidates.size() == NumArgs)
11519       break;
11520   }
11521 }
11522 
11523 /// Try to elide argument copies from memory into a local alloca. Succeeds if
11524 /// ArgVal is a load from a suitable fixed stack object.
11525 static void tryToElideArgumentCopy(
11526     FunctionLoweringInfo &FuncInfo, SmallVectorImpl<SDValue> &Chains,
11527     DenseMap<int, int> &ArgCopyElisionFrameIndexMap,
11528     SmallPtrSetImpl<const Instruction *> &ElidedArgCopyInstrs,
11529     ArgCopyElisionMapTy &ArgCopyElisionCandidates, const Argument &Arg,
11530     ArrayRef<SDValue> ArgVals, bool &ArgHasUses) {
11531   // Check if this is a load from a fixed stack object.
11532   auto *LNode = dyn_cast<LoadSDNode>(ArgVals[0]);
11533   if (!LNode)
11534     return;
11535   auto *FINode = dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode());
11536   if (!FINode)
11537     return;
11538 
11539   // Check that the fixed stack object is the right size and alignment.
11540   // Look at the alignment that the user wrote on the alloca instead of looking
11541   // at the stack object.
11542   auto ArgCopyIter = ArgCopyElisionCandidates.find(&Arg);
11543   assert(ArgCopyIter != ArgCopyElisionCandidates.end());
11544   const AllocaInst *AI = ArgCopyIter->second.first;
11545   int FixedIndex = FINode->getIndex();
11546   int &AllocaIndex = FuncInfo.StaticAllocaMap[AI];
11547   int OldIndex = AllocaIndex;
11548   MachineFrameInfo &MFI = FuncInfo.MF->getFrameInfo();
11549   if (MFI.getObjectSize(FixedIndex) != MFI.getObjectSize(OldIndex)) {
11550     LLVM_DEBUG(
11551         dbgs() << "  argument copy elision failed due to bad fixed stack "
11552                   "object size\n");
11553     return;
11554   }
11555   Align RequiredAlignment = AI->getAlign();
11556   if (MFI.getObjectAlign(FixedIndex) < RequiredAlignment) {
11557     LLVM_DEBUG(dbgs() << "  argument copy elision failed: alignment of alloca "
11558                          "greater than stack argument alignment ("
11559                       << DebugStr(RequiredAlignment) << " vs "
11560                       << DebugStr(MFI.getObjectAlign(FixedIndex)) << ")\n");
11561     return;
11562   }
11563 
11564   // Perform the elision. Delete the old stack object and replace its only use
11565   // in the variable info map. Mark the stack object as mutable and aliased.
11566   LLVM_DEBUG({
11567     dbgs() << "Eliding argument copy from " << Arg << " to " << *AI << '\n'
11568            << "  Replacing frame index " << OldIndex << " with " << FixedIndex
11569            << '\n';
11570   });
11571   MFI.RemoveStackObject(OldIndex);
11572   MFI.setIsImmutableObjectIndex(FixedIndex, false);
11573   MFI.setIsAliasedObjectIndex(FixedIndex, true);
11574   AllocaIndex = FixedIndex;
11575   ArgCopyElisionFrameIndexMap.insert({OldIndex, FixedIndex});
11576   for (SDValue ArgVal : ArgVals)
11577     Chains.push_back(ArgVal.getValue(1));
11578 
11579   // Avoid emitting code for the store implementing the copy.
11580   const StoreInst *SI = ArgCopyIter->second.second;
11581   ElidedArgCopyInstrs.insert(SI);
11582 
11583   // Check for uses of the argument again so that we can avoid exporting ArgVal
11584   // if it is't used by anything other than the store.
11585   for (const Value *U : Arg.users()) {
11586     if (U != SI) {
11587       ArgHasUses = true;
11588       break;
11589     }
11590   }
11591 }
11592 
11593 void SelectionDAGISel::LowerArguments(const Function &F) {
11594   SelectionDAG &DAG = SDB->DAG;
11595   SDLoc dl = SDB->getCurSDLoc();
11596   const DataLayout &DL = DAG.getDataLayout();
11597   SmallVector<ISD::InputArg, 16> Ins;
11598 
11599   // In Naked functions we aren't going to save any registers.
11600   if (F.hasFnAttribute(Attribute::Naked))
11601     return;
11602 
11603   if (!FuncInfo->CanLowerReturn) {
11604     // Put in an sret pointer parameter before all the other parameters.
11605     MVT ValueVT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
11606 
11607     ISD::ArgFlagsTy Flags;
11608     Flags.setSRet();
11609     MVT RegisterVT = TLI->getRegisterType(*DAG.getContext(), ValueVT);
11610     ISD::InputArg RetArg(Flags, RegisterVT, ValueVT, true,
11611                          ISD::InputArg::NoArgIndex, 0);
11612     Ins.push_back(RetArg);
11613   }
11614 
11615   // Look for stores of arguments to static allocas. Mark such arguments with a
11616   // flag to ask the target to give us the memory location of that argument if
11617   // available.
11618   ArgCopyElisionMapTy ArgCopyElisionCandidates;
11619   findArgumentCopyElisionCandidates(DL, FuncInfo.get(),
11620                                     ArgCopyElisionCandidates);
11621 
11622   // Set up the incoming argument description vector.
11623   for (const Argument &Arg : F.args()) {
11624     unsigned ArgNo = Arg.getArgNo();
11625     SmallVector<EVT, 4> ValueVTs;
11626     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11627     bool isArgValueUsed = !Arg.use_empty();
11628     unsigned PartBase = 0;
11629     Type *FinalType = Arg.getType();
11630     if (Arg.hasAttribute(Attribute::ByVal))
11631       FinalType = Arg.getParamByValType();
11632     bool NeedsRegBlock = TLI->functionArgumentNeedsConsecutiveRegisters(
11633         FinalType, F.getCallingConv(), F.isVarArg(), DL);
11634     for (unsigned Value = 0, NumValues = ValueVTs.size();
11635          Value != NumValues; ++Value) {
11636       EVT VT = ValueVTs[Value];
11637       Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
11638       ISD::ArgFlagsTy Flags;
11639 
11640 
11641       if (Arg.getType()->isPointerTy()) {
11642         Flags.setPointer();
11643         Flags.setPointerAddrSpace(
11644             cast<PointerType>(Arg.getType())->getAddressSpace());
11645       }
11646       if (Arg.hasAttribute(Attribute::ZExt))
11647         Flags.setZExt();
11648       if (Arg.hasAttribute(Attribute::SExt))
11649         Flags.setSExt();
11650       if (Arg.hasAttribute(Attribute::InReg)) {
11651         // If we are using vectorcall calling convention, a structure that is
11652         // passed InReg - is surely an HVA
11653         if (F.getCallingConv() == CallingConv::X86_VectorCall &&
11654             isa<StructType>(Arg.getType())) {
11655           // The first value of a structure is marked
11656           if (0 == Value)
11657             Flags.setHvaStart();
11658           Flags.setHva();
11659         }
11660         // Set InReg Flag
11661         Flags.setInReg();
11662       }
11663       if (Arg.hasAttribute(Attribute::StructRet))
11664         Flags.setSRet();
11665       if (Arg.hasAttribute(Attribute::SwiftSelf))
11666         Flags.setSwiftSelf();
11667       if (Arg.hasAttribute(Attribute::SwiftAsync))
11668         Flags.setSwiftAsync();
11669       if (Arg.hasAttribute(Attribute::SwiftError))
11670         Flags.setSwiftError();
11671       if (Arg.hasAttribute(Attribute::ByVal))
11672         Flags.setByVal();
11673       if (Arg.hasAttribute(Attribute::ByRef))
11674         Flags.setByRef();
11675       if (Arg.hasAttribute(Attribute::InAlloca)) {
11676         Flags.setInAlloca();
11677         // Set the byval flag for CCAssignFn callbacks that don't know about
11678         // inalloca.  This way we can know how many bytes we should've allocated
11679         // and how many bytes a callee cleanup function will pop.  If we port
11680         // inalloca to more targets, we'll have to add custom inalloca handling
11681         // in the various CC lowering callbacks.
11682         Flags.setByVal();
11683       }
11684       if (Arg.hasAttribute(Attribute::Preallocated)) {
11685         Flags.setPreallocated();
11686         // Set the byval flag for CCAssignFn callbacks that don't know about
11687         // preallocated.  This way we can know how many bytes we should've
11688         // allocated and how many bytes a callee cleanup function will pop.  If
11689         // we port preallocated to more targets, we'll have to add custom
11690         // preallocated handling in the various CC lowering callbacks.
11691         Flags.setByVal();
11692       }
11693 
11694       // Certain targets (such as MIPS), may have a different ABI alignment
11695       // for a type depending on the context. Give the target a chance to
11696       // specify the alignment it wants.
11697       const Align OriginalAlignment(
11698           TLI->getABIAlignmentForCallingConv(ArgTy, DL));
11699       Flags.setOrigAlign(OriginalAlignment);
11700 
11701       Align MemAlign;
11702       Type *ArgMemTy = nullptr;
11703       if (Flags.isByVal() || Flags.isInAlloca() || Flags.isPreallocated() ||
11704           Flags.isByRef()) {
11705         if (!ArgMemTy)
11706           ArgMemTy = Arg.getPointeeInMemoryValueType();
11707 
11708         uint64_t MemSize = DL.getTypeAllocSize(ArgMemTy);
11709 
11710         // For in-memory arguments, size and alignment should be passed from FE.
11711         // BE will guess if this info is not there but there are cases it cannot
11712         // get right.
11713         if (auto ParamAlign = Arg.getParamStackAlign())
11714           MemAlign = *ParamAlign;
11715         else if ((ParamAlign = Arg.getParamAlign()))
11716           MemAlign = *ParamAlign;
11717         else
11718           MemAlign = TLI->getByValTypeAlignment(ArgMemTy, DL);
11719         if (Flags.isByRef())
11720           Flags.setByRefSize(MemSize);
11721         else
11722           Flags.setByValSize(MemSize);
11723       } else if (auto ParamAlign = Arg.getParamStackAlign()) {
11724         MemAlign = *ParamAlign;
11725       } else {
11726         MemAlign = OriginalAlignment;
11727       }
11728       Flags.setMemAlign(MemAlign);
11729 
11730       if (Arg.hasAttribute(Attribute::Nest))
11731         Flags.setNest();
11732       if (NeedsRegBlock)
11733         Flags.setInConsecutiveRegs();
11734       if (ArgCopyElisionCandidates.count(&Arg))
11735         Flags.setCopyElisionCandidate();
11736       if (Arg.hasAttribute(Attribute::Returned))
11737         Flags.setReturned();
11738 
11739       MVT RegisterVT = TLI->getRegisterTypeForCallingConv(
11740           *CurDAG->getContext(), F.getCallingConv(), VT);
11741       unsigned NumRegs = TLI->getNumRegistersForCallingConv(
11742           *CurDAG->getContext(), F.getCallingConv(), VT);
11743       for (unsigned i = 0; i != NumRegs; ++i) {
11744         // For scalable vectors, use the minimum size; individual targets
11745         // are responsible for handling scalable vector arguments and
11746         // return values.
11747         ISD::InputArg MyFlags(
11748             Flags, RegisterVT, VT, isArgValueUsed, ArgNo,
11749             PartBase + i * RegisterVT.getStoreSize().getKnownMinValue());
11750         if (NumRegs > 1 && i == 0)
11751           MyFlags.Flags.setSplit();
11752         // if it isn't first piece, alignment must be 1
11753         else if (i > 0) {
11754           MyFlags.Flags.setOrigAlign(Align(1));
11755           if (i == NumRegs - 1)
11756             MyFlags.Flags.setSplitEnd();
11757         }
11758         Ins.push_back(MyFlags);
11759       }
11760       if (NeedsRegBlock && Value == NumValues - 1)
11761         Ins[Ins.size() - 1].Flags.setInConsecutiveRegsLast();
11762       PartBase += VT.getStoreSize().getKnownMinValue();
11763     }
11764   }
11765 
11766   // Call the target to set up the argument values.
11767   SmallVector<SDValue, 8> InVals;
11768   SDValue NewRoot = TLI->LowerFormalArguments(
11769       DAG.getRoot(), F.getCallingConv(), F.isVarArg(), Ins, dl, DAG, InVals);
11770 
11771   // Verify that the target's LowerFormalArguments behaved as expected.
11772   assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
11773          "LowerFormalArguments didn't return a valid chain!");
11774   assert(InVals.size() == Ins.size() &&
11775          "LowerFormalArguments didn't emit the correct number of values!");
11776   LLVM_DEBUG({
11777     for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
11778       assert(InVals[i].getNode() &&
11779              "LowerFormalArguments emitted a null value!");
11780       assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
11781              "LowerFormalArguments emitted a value with the wrong type!");
11782     }
11783   });
11784 
11785   // Update the DAG with the new chain value resulting from argument lowering.
11786   DAG.setRoot(NewRoot);
11787 
11788   // Set up the argument values.
11789   unsigned i = 0;
11790   if (!FuncInfo->CanLowerReturn) {
11791     // Create a virtual register for the sret pointer, and put in a copy
11792     // from the sret argument into it.
11793     MVT VT = TLI->getPointerTy(DL, DL.getAllocaAddrSpace());
11794     MVT RegVT = TLI->getRegisterType(*CurDAG->getContext(), VT);
11795     std::optional<ISD::NodeType> AssertOp;
11796     SDValue ArgValue =
11797         getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT, VT, nullptr, NewRoot,
11798                          F.getCallingConv(), AssertOp);
11799 
11800     MachineFunction& MF = SDB->DAG.getMachineFunction();
11801     MachineRegisterInfo& RegInfo = MF.getRegInfo();
11802     Register SRetReg =
11803         RegInfo.createVirtualRegister(TLI->getRegClassFor(RegVT));
11804     FuncInfo->DemoteRegister = SRetReg;
11805     NewRoot =
11806         SDB->DAG.getCopyToReg(NewRoot, SDB->getCurSDLoc(), SRetReg, ArgValue);
11807     DAG.setRoot(NewRoot);
11808 
11809     // i indexes lowered arguments.  Bump it past the hidden sret argument.
11810     ++i;
11811   }
11812 
11813   SmallVector<SDValue, 4> Chains;
11814   DenseMap<int, int> ArgCopyElisionFrameIndexMap;
11815   for (const Argument &Arg : F.args()) {
11816     SmallVector<SDValue, 4> ArgValues;
11817     SmallVector<EVT, 4> ValueVTs;
11818     ComputeValueVTs(*TLI, DAG.getDataLayout(), Arg.getType(), ValueVTs);
11819     unsigned NumValues = ValueVTs.size();
11820     if (NumValues == 0)
11821       continue;
11822 
11823     bool ArgHasUses = !Arg.use_empty();
11824 
11825     // Elide the copying store if the target loaded this argument from a
11826     // suitable fixed stack object.
11827     if (Ins[i].Flags.isCopyElisionCandidate()) {
11828       unsigned NumParts = 0;
11829       for (EVT VT : ValueVTs)
11830         NumParts += TLI->getNumRegistersForCallingConv(*CurDAG->getContext(),
11831                                                        F.getCallingConv(), VT);
11832 
11833       tryToElideArgumentCopy(*FuncInfo, Chains, ArgCopyElisionFrameIndexMap,
11834                              ElidedArgCopyInstrs, ArgCopyElisionCandidates, Arg,
11835                              ArrayRef(&InVals[i], NumParts), ArgHasUses);
11836     }
11837 
11838     // If this argument is unused then remember its value. It is used to generate
11839     // debugging information.
11840     bool isSwiftErrorArg =
11841         TLI->supportSwiftError() &&
11842         Arg.hasAttribute(Attribute::SwiftError);
11843     if (!ArgHasUses && !isSwiftErrorArg) {
11844       SDB->setUnusedArgValue(&Arg, InVals[i]);
11845 
11846       // Also remember any frame index for use in FastISel.
11847       if (FrameIndexSDNode *FI =
11848           dyn_cast<FrameIndexSDNode>(InVals[i].getNode()))
11849         FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11850     }
11851 
11852     for (unsigned Val = 0; Val != NumValues; ++Val) {
11853       EVT VT = ValueVTs[Val];
11854       MVT PartVT = TLI->getRegisterTypeForCallingConv(*CurDAG->getContext(),
11855                                                       F.getCallingConv(), VT);
11856       unsigned NumParts = TLI->getNumRegistersForCallingConv(
11857           *CurDAG->getContext(), F.getCallingConv(), VT);
11858 
11859       // Even an apparent 'unused' swifterror argument needs to be returned. So
11860       // we do generate a copy for it that can be used on return from the
11861       // function.
11862       if (ArgHasUses || isSwiftErrorArg) {
11863         std::optional<ISD::NodeType> AssertOp;
11864         if (Arg.hasAttribute(Attribute::SExt))
11865           AssertOp = ISD::AssertSext;
11866         else if (Arg.hasAttribute(Attribute::ZExt))
11867           AssertOp = ISD::AssertZext;
11868 
11869         ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
11870                                              PartVT, VT, nullptr, NewRoot,
11871                                              F.getCallingConv(), AssertOp));
11872       }
11873 
11874       i += NumParts;
11875     }
11876 
11877     // We don't need to do anything else for unused arguments.
11878     if (ArgValues.empty())
11879       continue;
11880 
11881     // Note down frame index.
11882     if (FrameIndexSDNode *FI =
11883         dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
11884       FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11885 
11886     SDValue Res = DAG.getMergeValues(ArrayRef(ArgValues.data(), NumValues),
11887                                      SDB->getCurSDLoc());
11888 
11889     SDB->setValue(&Arg, Res);
11890     if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
11891       // We want to associate the argument with the frame index, among
11892       // involved operands, that correspond to the lowest address. The
11893       // getCopyFromParts function, called earlier, is swapping the order of
11894       // the operands to BUILD_PAIR depending on endianness. The result of
11895       // that swapping is that the least significant bits of the argument will
11896       // be in the first operand of the BUILD_PAIR node, and the most
11897       // significant bits will be in the second operand.
11898       unsigned LowAddressOp = DAG.getDataLayout().isBigEndian() ? 1 : 0;
11899       if (LoadSDNode *LNode =
11900           dyn_cast<LoadSDNode>(Res.getOperand(LowAddressOp).getNode()))
11901         if (FrameIndexSDNode *FI =
11902             dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
11903           FuncInfo->setArgumentFrameIndex(&Arg, FI->getIndex());
11904     }
11905 
11906     // Analyses past this point are naive and don't expect an assertion.
11907     if (Res.getOpcode() == ISD::AssertZext)
11908       Res = Res.getOperand(0);
11909 
11910     // Update the SwiftErrorVRegDefMap.
11911     if (Res.getOpcode() == ISD::CopyFromReg && isSwiftErrorArg) {
11912       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11913       if (Reg.isVirtual())
11914         SwiftError->setCurrentVReg(FuncInfo->MBB, SwiftError->getFunctionArg(),
11915                                    Reg);
11916     }
11917 
11918     // If this argument is live outside of the entry block, insert a copy from
11919     // wherever we got it to the vreg that other BB's will reference it as.
11920     if (Res.getOpcode() == ISD::CopyFromReg) {
11921       // If we can, though, try to skip creating an unnecessary vreg.
11922       // FIXME: This isn't very clean... it would be nice to make this more
11923       // general.
11924       Register Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
11925       if (Reg.isVirtual()) {
11926         FuncInfo->ValueMap[&Arg] = Reg;
11927         continue;
11928       }
11929     }
11930     if (!isOnlyUsedInEntryBlock(&Arg, TM.Options.EnableFastISel)) {
11931       FuncInfo->InitializeRegForValue(&Arg);
11932       SDB->CopyToExportRegsIfNeeded(&Arg);
11933     }
11934   }
11935 
11936   if (!Chains.empty()) {
11937     Chains.push_back(NewRoot);
11938     NewRoot = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
11939   }
11940 
11941   DAG.setRoot(NewRoot);
11942 
11943   assert(i == InVals.size() && "Argument register count mismatch!");
11944 
11945   // If any argument copy elisions occurred and we have debug info, update the
11946   // stale frame indices used in the dbg.declare variable info table.
11947   if (!ArgCopyElisionFrameIndexMap.empty()) {
11948     for (MachineFunction::VariableDbgInfo &VI :
11949          MF->getInStackSlotVariableDbgInfo()) {
11950       auto I = ArgCopyElisionFrameIndexMap.find(VI.getStackSlot());
11951       if (I != ArgCopyElisionFrameIndexMap.end())
11952         VI.updateStackSlot(I->second);
11953     }
11954   }
11955 
11956   // Finally, if the target has anything special to do, allow it to do so.
11957   emitFunctionEntryCode();
11958 }
11959 
11960 /// Handle PHI nodes in successor blocks.  Emit code into the SelectionDAG to
11961 /// ensure constants are generated when needed.  Remember the virtual registers
11962 /// that need to be added to the Machine PHI nodes as input.  We cannot just
11963 /// directly add them, because expansion might result in multiple MBB's for one
11964 /// BB.  As such, the start of the BB might correspond to a different MBB than
11965 /// the end.
11966 void
11967 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
11968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11969 
11970   SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
11971 
11972   // Check PHI nodes in successors that expect a value to be available from this
11973   // block.
11974   for (const BasicBlock *SuccBB : successors(LLVMBB->getTerminator())) {
11975     if (!isa<PHINode>(SuccBB->begin())) continue;
11976     MachineBasicBlock *SuccMBB = FuncInfo.getMBB(SuccBB);
11977 
11978     // If this terminator has multiple identical successors (common for
11979     // switches), only handle each succ once.
11980     if (!SuccsHandled.insert(SuccMBB).second)
11981       continue;
11982 
11983     MachineBasicBlock::iterator MBBI = SuccMBB->begin();
11984 
11985     // At this point we know that there is a 1-1 correspondence between LLVM PHI
11986     // nodes and Machine PHI nodes, but the incoming operands have not been
11987     // emitted yet.
11988     for (const PHINode &PN : SuccBB->phis()) {
11989       // Ignore dead phi's.
11990       if (PN.use_empty())
11991         continue;
11992 
11993       // Skip empty types
11994       if (PN.getType()->isEmptyTy())
11995         continue;
11996 
11997       unsigned Reg;
11998       const Value *PHIOp = PN.getIncomingValueForBlock(LLVMBB);
11999 
12000       if (const auto *C = dyn_cast<Constant>(PHIOp)) {
12001         unsigned &RegOut = ConstantsOut[C];
12002         if (RegOut == 0) {
12003           RegOut = FuncInfo.CreateRegs(C);
12004           // We need to zero/sign extend ConstantInt phi operands to match
12005           // assumptions in FunctionLoweringInfo::ComputePHILiveOutRegInfo.
12006           ISD::NodeType ExtendType = ISD::ANY_EXTEND;
12007           if (auto *CI = dyn_cast<ConstantInt>(C))
12008             ExtendType = TLI.signExtendConstant(CI) ? ISD::SIGN_EXTEND
12009                                                     : ISD::ZERO_EXTEND;
12010           CopyValueToVirtualRegister(C, RegOut, ExtendType);
12011         }
12012         Reg = RegOut;
12013       } else {
12014         DenseMap<const Value *, Register>::iterator I =
12015           FuncInfo.ValueMap.find(PHIOp);
12016         if (I != FuncInfo.ValueMap.end())
12017           Reg = I->second;
12018         else {
12019           assert(isa<AllocaInst>(PHIOp) &&
12020                  FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
12021                  "Didn't codegen value into a register!??");
12022           Reg = FuncInfo.CreateRegs(PHIOp);
12023           CopyValueToVirtualRegister(PHIOp, Reg);
12024         }
12025       }
12026 
12027       // Remember that this register needs to added to the machine PHI node as
12028       // the input for this MBB.
12029       SmallVector<EVT, 4> ValueVTs;
12030       ComputeValueVTs(TLI, DAG.getDataLayout(), PN.getType(), ValueVTs);
12031       for (EVT VT : ValueVTs) {
12032         const unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
12033         for (unsigned i = 0; i != NumRegisters; ++i)
12034           FuncInfo.PHINodesToUpdate.push_back(
12035               std::make_pair(&*MBBI++, Reg + i));
12036         Reg += NumRegisters;
12037       }
12038     }
12039   }
12040 
12041   ConstantsOut.clear();
12042 }
12043 
12044 MachineBasicBlock *SelectionDAGBuilder::NextBlock(MachineBasicBlock *MBB) {
12045   MachineFunction::iterator I(MBB);
12046   if (++I == FuncInfo.MF->end())
12047     return nullptr;
12048   return &*I;
12049 }
12050 
12051 /// During lowering new call nodes can be created (such as memset, etc.).
12052 /// Those will become new roots of the current DAG, but complications arise
12053 /// when they are tail calls. In such cases, the call lowering will update
12054 /// the root, but the builder still needs to know that a tail call has been
12055 /// lowered in order to avoid generating an additional return.
12056 void SelectionDAGBuilder::updateDAGForMaybeTailCall(SDValue MaybeTC) {
12057   // If the node is null, we do have a tail call.
12058   if (MaybeTC.getNode() != nullptr)
12059     DAG.setRoot(MaybeTC);
12060   else
12061     HasTailCall = true;
12062 }
12063 
12064 void SelectionDAGBuilder::lowerWorkItem(SwitchWorkListItem W, Value *Cond,
12065                                         MachineBasicBlock *SwitchMBB,
12066                                         MachineBasicBlock *DefaultMBB) {
12067   MachineFunction *CurMF = FuncInfo.MF;
12068   MachineBasicBlock *NextMBB = nullptr;
12069   MachineFunction::iterator BBI(W.MBB);
12070   if (++BBI != FuncInfo.MF->end())
12071     NextMBB = &*BBI;
12072 
12073   unsigned Size = W.LastCluster - W.FirstCluster + 1;
12074 
12075   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12076 
12077   if (Size == 2 && W.MBB == SwitchMBB) {
12078     // If any two of the cases has the same destination, and if one value
12079     // is the same as the other, but has one bit unset that the other has set,
12080     // use bit manipulation to do two compares at once.  For example:
12081     // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
12082     // TODO: This could be extended to merge any 2 cases in switches with 3
12083     // cases.
12084     // TODO: Handle cases where W.CaseBB != SwitchBB.
12085     CaseCluster &Small = *W.FirstCluster;
12086     CaseCluster &Big = *W.LastCluster;
12087 
12088     if (Small.Low == Small.High && Big.Low == Big.High &&
12089         Small.MBB == Big.MBB) {
12090       const APInt &SmallValue = Small.Low->getValue();
12091       const APInt &BigValue = Big.Low->getValue();
12092 
12093       // Check that there is only one bit different.
12094       APInt CommonBit = BigValue ^ SmallValue;
12095       if (CommonBit.isPowerOf2()) {
12096         SDValue CondLHS = getValue(Cond);
12097         EVT VT = CondLHS.getValueType();
12098         SDLoc DL = getCurSDLoc();
12099 
12100         SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
12101                                  DAG.getConstant(CommonBit, DL, VT));
12102         SDValue Cond = DAG.getSetCC(
12103             DL, MVT::i1, Or, DAG.getConstant(BigValue | SmallValue, DL, VT),
12104             ISD::SETEQ);
12105 
12106         // Update successor info.
12107         // Both Small and Big will jump to Small.BB, so we sum up the
12108         // probabilities.
12109         addSuccessorWithProb(SwitchMBB, Small.MBB, Small.Prob + Big.Prob);
12110         if (BPI)
12111           addSuccessorWithProb(
12112               SwitchMBB, DefaultMBB,
12113               // The default destination is the first successor in IR.
12114               BPI->getEdgeProbability(SwitchMBB->getBasicBlock(), (unsigned)0));
12115         else
12116           addSuccessorWithProb(SwitchMBB, DefaultMBB);
12117 
12118         // Insert the true branch.
12119         SDValue BrCond =
12120             DAG.getNode(ISD::BRCOND, DL, MVT::Other, getControlRoot(), Cond,
12121                         DAG.getBasicBlock(Small.MBB));
12122         // Insert the false branch.
12123         BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
12124                              DAG.getBasicBlock(DefaultMBB));
12125 
12126         DAG.setRoot(BrCond);
12127         return;
12128       }
12129     }
12130   }
12131 
12132   if (TM.getOptLevel() != CodeGenOptLevel::None) {
12133     // Here, we order cases by probability so the most likely case will be
12134     // checked first. However, two clusters can have the same probability in
12135     // which case their relative ordering is non-deterministic. So we use Low
12136     // as a tie-breaker as clusters are guaranteed to never overlap.
12137     llvm::sort(W.FirstCluster, W.LastCluster + 1,
12138                [](const CaseCluster &a, const CaseCluster &b) {
12139       return a.Prob != b.Prob ?
12140              a.Prob > b.Prob :
12141              a.Low->getValue().slt(b.Low->getValue());
12142     });
12143 
12144     // Rearrange the case blocks so that the last one falls through if possible
12145     // without changing the order of probabilities.
12146     for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster; ) {
12147       --I;
12148       if (I->Prob > W.LastCluster->Prob)
12149         break;
12150       if (I->Kind == CC_Range && I->MBB == NextMBB) {
12151         std::swap(*I, *W.LastCluster);
12152         break;
12153       }
12154     }
12155   }
12156 
12157   // Compute total probability.
12158   BranchProbability DefaultProb = W.DefaultProb;
12159   BranchProbability UnhandledProbs = DefaultProb;
12160   for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I)
12161     UnhandledProbs += I->Prob;
12162 
12163   MachineBasicBlock *CurMBB = W.MBB;
12164   for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) {
12165     bool FallthroughUnreachable = false;
12166     MachineBasicBlock *Fallthrough;
12167     if (I == W.LastCluster) {
12168       // For the last cluster, fall through to the default destination.
12169       Fallthrough = DefaultMBB;
12170       FallthroughUnreachable = isa<UnreachableInst>(
12171           DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg());
12172     } else {
12173       Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock());
12174       CurMF->insert(BBI, Fallthrough);
12175       // Put Cond in a virtual register to make it available from the new blocks.
12176       ExportFromCurrentBlock(Cond);
12177     }
12178     UnhandledProbs -= I->Prob;
12179 
12180     switch (I->Kind) {
12181       case CC_JumpTable: {
12182         // FIXME: Optimize away range check based on pivot comparisons.
12183         JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first;
12184         SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second;
12185 
12186         // The jump block hasn't been inserted yet; insert it here.
12187         MachineBasicBlock *JumpMBB = JT->MBB;
12188         CurMF->insert(BBI, JumpMBB);
12189 
12190         auto JumpProb = I->Prob;
12191         auto FallthroughProb = UnhandledProbs;
12192 
12193         // If the default statement is a target of the jump table, we evenly
12194         // distribute the default probability to successors of CurMBB. Also
12195         // update the probability on the edge from JumpMBB to Fallthrough.
12196         for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(),
12197                                               SE = JumpMBB->succ_end();
12198              SI != SE; ++SI) {
12199           if (*SI == DefaultMBB) {
12200             JumpProb += DefaultProb / 2;
12201             FallthroughProb -= DefaultProb / 2;
12202             JumpMBB->setSuccProbability(SI, DefaultProb / 2);
12203             JumpMBB->normalizeSuccProbs();
12204             break;
12205           }
12206         }
12207 
12208         // If the default clause is unreachable, propagate that knowledge into
12209         // JTH->FallthroughUnreachable which will use it to suppress the range
12210         // check.
12211         //
12212         // However, don't do this if we're doing branch target enforcement,
12213         // because a table branch _without_ a range check can be a tempting JOP
12214         // gadget - out-of-bounds inputs that are impossible in correct
12215         // execution become possible again if an attacker can influence the
12216         // control flow. So if an attacker doesn't already have a BTI bypass
12217         // available, we don't want them to be able to get one out of this
12218         // table branch.
12219         if (FallthroughUnreachable) {
12220           Function &CurFunc = CurMF->getFunction();
12221           if (!CurFunc.hasFnAttribute("branch-target-enforcement"))
12222             JTH->FallthroughUnreachable = true;
12223         }
12224 
12225         if (!JTH->FallthroughUnreachable)
12226           addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb);
12227         addSuccessorWithProb(CurMBB, JumpMBB, JumpProb);
12228         CurMBB->normalizeSuccProbs();
12229 
12230         // The jump table header will be inserted in our current block, do the
12231         // range check, and fall through to our fallthrough block.
12232         JTH->HeaderBB = CurMBB;
12233         JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader.
12234 
12235         // If we're in the right place, emit the jump table header right now.
12236         if (CurMBB == SwitchMBB) {
12237           visitJumpTableHeader(*JT, *JTH, SwitchMBB);
12238           JTH->Emitted = true;
12239         }
12240         break;
12241       }
12242       case CC_BitTests: {
12243         // FIXME: Optimize away range check based on pivot comparisons.
12244         BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex];
12245 
12246         // The bit test blocks haven't been inserted yet; insert them here.
12247         for (BitTestCase &BTC : BTB->Cases)
12248           CurMF->insert(BBI, BTC.ThisBB);
12249 
12250         // Fill in fields of the BitTestBlock.
12251         BTB->Parent = CurMBB;
12252         BTB->Default = Fallthrough;
12253 
12254         BTB->DefaultProb = UnhandledProbs;
12255         // If the cases in bit test don't form a contiguous range, we evenly
12256         // distribute the probability on the edge to Fallthrough to two
12257         // successors of CurMBB.
12258         if (!BTB->ContiguousRange) {
12259           BTB->Prob += DefaultProb / 2;
12260           BTB->DefaultProb -= DefaultProb / 2;
12261         }
12262 
12263         if (FallthroughUnreachable)
12264           BTB->FallthroughUnreachable = true;
12265 
12266         // If we're in the right place, emit the bit test header right now.
12267         if (CurMBB == SwitchMBB) {
12268           visitBitTestHeader(*BTB, SwitchMBB);
12269           BTB->Emitted = true;
12270         }
12271         break;
12272       }
12273       case CC_Range: {
12274         const Value *RHS, *LHS, *MHS;
12275         ISD::CondCode CC;
12276         if (I->Low == I->High) {
12277           // Check Cond == I->Low.
12278           CC = ISD::SETEQ;
12279           LHS = Cond;
12280           RHS=I->Low;
12281           MHS = nullptr;
12282         } else {
12283           // Check I->Low <= Cond <= I->High.
12284           CC = ISD::SETLE;
12285           LHS = I->Low;
12286           MHS = Cond;
12287           RHS = I->High;
12288         }
12289 
12290         // If Fallthrough is unreachable, fold away the comparison.
12291         if (FallthroughUnreachable)
12292           CC = ISD::SETTRUE;
12293 
12294         // The false probability is the sum of all unhandled cases.
12295         CaseBlock CB(CC, LHS, RHS, MHS, I->MBB, Fallthrough, CurMBB,
12296                      getCurSDLoc(), I->Prob, UnhandledProbs);
12297 
12298         if (CurMBB == SwitchMBB)
12299           visitSwitchCase(CB, SwitchMBB);
12300         else
12301           SL->SwitchCases.push_back(CB);
12302 
12303         break;
12304       }
12305     }
12306     CurMBB = Fallthrough;
12307   }
12308 }
12309 
12310 void SelectionDAGBuilder::splitWorkItem(SwitchWorkList &WorkList,
12311                                         const SwitchWorkListItem &W,
12312                                         Value *Cond,
12313                                         MachineBasicBlock *SwitchMBB) {
12314   assert(W.FirstCluster->Low->getValue().slt(W.LastCluster->Low->getValue()) &&
12315          "Clusters not sorted?");
12316   assert(W.LastCluster - W.FirstCluster + 1 >= 2 && "Too small to split!");
12317 
12318   auto [LastLeft, FirstRight, LeftProb, RightProb] =
12319       SL->computeSplitWorkItemInfo(W);
12320 
12321   // Use the first element on the right as pivot since we will make less-than
12322   // comparisons against it.
12323   CaseClusterIt PivotCluster = FirstRight;
12324   assert(PivotCluster > W.FirstCluster);
12325   assert(PivotCluster <= W.LastCluster);
12326 
12327   CaseClusterIt FirstLeft = W.FirstCluster;
12328   CaseClusterIt LastRight = W.LastCluster;
12329 
12330   const ConstantInt *Pivot = PivotCluster->Low;
12331 
12332   // New blocks will be inserted immediately after the current one.
12333   MachineFunction::iterator BBI(W.MBB);
12334   ++BBI;
12335 
12336   // We will branch to the LHS if Value < Pivot. If LHS is a single cluster,
12337   // we can branch to its destination directly if it's squeezed exactly in
12338   // between the known lower bound and Pivot - 1.
12339   MachineBasicBlock *LeftMBB;
12340   if (FirstLeft == LastLeft && FirstLeft->Kind == CC_Range &&
12341       FirstLeft->Low == W.GE &&
12342       (FirstLeft->High->getValue() + 1LL) == Pivot->getValue()) {
12343     LeftMBB = FirstLeft->MBB;
12344   } else {
12345     LeftMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12346     FuncInfo.MF->insert(BBI, LeftMBB);
12347     WorkList.push_back(
12348         {LeftMBB, FirstLeft, LastLeft, W.GE, Pivot, W.DefaultProb / 2});
12349     // Put Cond in a virtual register to make it available from the new blocks.
12350     ExportFromCurrentBlock(Cond);
12351   }
12352 
12353   // Similarly, we will branch to the RHS if Value >= Pivot. If RHS is a
12354   // single cluster, RHS.Low == Pivot, and we can branch to its destination
12355   // directly if RHS.High equals the current upper bound.
12356   MachineBasicBlock *RightMBB;
12357   if (FirstRight == LastRight && FirstRight->Kind == CC_Range &&
12358       W.LT && (FirstRight->High->getValue() + 1ULL) == W.LT->getValue()) {
12359     RightMBB = FirstRight->MBB;
12360   } else {
12361     RightMBB = FuncInfo.MF->CreateMachineBasicBlock(W.MBB->getBasicBlock());
12362     FuncInfo.MF->insert(BBI, RightMBB);
12363     WorkList.push_back(
12364         {RightMBB, FirstRight, LastRight, Pivot, W.LT, W.DefaultProb / 2});
12365     // Put Cond in a virtual register to make it available from the new blocks.
12366     ExportFromCurrentBlock(Cond);
12367   }
12368 
12369   // Create the CaseBlock record that will be used to lower the branch.
12370   CaseBlock CB(ISD::SETLT, Cond, Pivot, nullptr, LeftMBB, RightMBB, W.MBB,
12371                getCurSDLoc(), LeftProb, RightProb);
12372 
12373   if (W.MBB == SwitchMBB)
12374     visitSwitchCase(CB, SwitchMBB);
12375   else
12376     SL->SwitchCases.push_back(CB);
12377 }
12378 
12379 // Scale CaseProb after peeling a case with the probablity of PeeledCaseProb
12380 // from the swith statement.
12381 static BranchProbability scaleCaseProbality(BranchProbability CaseProb,
12382                                             BranchProbability PeeledCaseProb) {
12383   if (PeeledCaseProb == BranchProbability::getOne())
12384     return BranchProbability::getZero();
12385   BranchProbability SwitchProb = PeeledCaseProb.getCompl();
12386 
12387   uint32_t Numerator = CaseProb.getNumerator();
12388   uint32_t Denominator = SwitchProb.scale(CaseProb.getDenominator());
12389   return BranchProbability(Numerator, std::max(Numerator, Denominator));
12390 }
12391 
12392 // Try to peel the top probability case if it exceeds the threshold.
12393 // Return current MachineBasicBlock for the switch statement if the peeling
12394 // does not occur.
12395 // If the peeling is performed, return the newly created MachineBasicBlock
12396 // for the peeled switch statement. Also update Clusters to remove the peeled
12397 // case. PeeledCaseProb is the BranchProbability for the peeled case.
12398 MachineBasicBlock *SelectionDAGBuilder::peelDominantCaseCluster(
12399     const SwitchInst &SI, CaseClusterVector &Clusters,
12400     BranchProbability &PeeledCaseProb) {
12401   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12402   // Don't perform if there is only one cluster or optimizing for size.
12403   if (SwitchPeelThreshold > 100 || !FuncInfo.BPI || Clusters.size() < 2 ||
12404       TM.getOptLevel() == CodeGenOptLevel::None ||
12405       SwitchMBB->getParent()->getFunction().hasMinSize())
12406     return SwitchMBB;
12407 
12408   BranchProbability TopCaseProb = BranchProbability(SwitchPeelThreshold, 100);
12409   unsigned PeeledCaseIndex = 0;
12410   bool SwitchPeeled = false;
12411   for (unsigned Index = 0; Index < Clusters.size(); ++Index) {
12412     CaseCluster &CC = Clusters[Index];
12413     if (CC.Prob < TopCaseProb)
12414       continue;
12415     TopCaseProb = CC.Prob;
12416     PeeledCaseIndex = Index;
12417     SwitchPeeled = true;
12418   }
12419   if (!SwitchPeeled)
12420     return SwitchMBB;
12421 
12422   LLVM_DEBUG(dbgs() << "Peeled one top case in switch stmt, prob: "
12423                     << TopCaseProb << "\n");
12424 
12425   // Record the MBB for the peeled switch statement.
12426   MachineFunction::iterator BBI(SwitchMBB);
12427   ++BBI;
12428   MachineBasicBlock *PeeledSwitchMBB =
12429       FuncInfo.MF->CreateMachineBasicBlock(SwitchMBB->getBasicBlock());
12430   FuncInfo.MF->insert(BBI, PeeledSwitchMBB);
12431 
12432   ExportFromCurrentBlock(SI.getCondition());
12433   auto PeeledCaseIt = Clusters.begin() + PeeledCaseIndex;
12434   SwitchWorkListItem W = {SwitchMBB, PeeledCaseIt, PeeledCaseIt,
12435                           nullptr,   nullptr,      TopCaseProb.getCompl()};
12436   lowerWorkItem(W, SI.getCondition(), SwitchMBB, PeeledSwitchMBB);
12437 
12438   Clusters.erase(PeeledCaseIt);
12439   for (CaseCluster &CC : Clusters) {
12440     LLVM_DEBUG(
12441         dbgs() << "Scale the probablity for one cluster, before scaling: "
12442                << CC.Prob << "\n");
12443     CC.Prob = scaleCaseProbality(CC.Prob, TopCaseProb);
12444     LLVM_DEBUG(dbgs() << "After scaling: " << CC.Prob << "\n");
12445   }
12446   PeeledCaseProb = TopCaseProb;
12447   return PeeledSwitchMBB;
12448 }
12449 
12450 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
12451   // Extract cases from the switch.
12452   BranchProbabilityInfo *BPI = FuncInfo.BPI;
12453   CaseClusterVector Clusters;
12454   Clusters.reserve(SI.getNumCases());
12455   for (auto I : SI.cases()) {
12456     MachineBasicBlock *Succ = FuncInfo.getMBB(I.getCaseSuccessor());
12457     const ConstantInt *CaseVal = I.getCaseValue();
12458     BranchProbability Prob =
12459         BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex())
12460             : BranchProbability(1, SI.getNumCases() + 1);
12461     Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob));
12462   }
12463 
12464   MachineBasicBlock *DefaultMBB = FuncInfo.getMBB(SI.getDefaultDest());
12465 
12466   // Cluster adjacent cases with the same destination. We do this at all
12467   // optimization levels because it's cheap to do and will make codegen faster
12468   // if there are many clusters.
12469   sortAndRangeify(Clusters);
12470 
12471   // The branch probablity of the peeled case.
12472   BranchProbability PeeledCaseProb = BranchProbability::getZero();
12473   MachineBasicBlock *PeeledSwitchMBB =
12474       peelDominantCaseCluster(SI, Clusters, PeeledCaseProb);
12475 
12476   // If there is only the default destination, jump there directly.
12477   MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
12478   if (Clusters.empty()) {
12479     assert(PeeledSwitchMBB == SwitchMBB);
12480     SwitchMBB->addSuccessor(DefaultMBB);
12481     if (DefaultMBB != NextBlock(SwitchMBB)) {
12482       DAG.setRoot(DAG.getNode(ISD::BR, getCurSDLoc(), MVT::Other,
12483                               getControlRoot(), DAG.getBasicBlock(DefaultMBB)));
12484     }
12485     return;
12486   }
12487 
12488   SL->findJumpTables(Clusters, &SI, getCurSDLoc(), DefaultMBB, DAG.getPSI(),
12489                      DAG.getBFI());
12490   SL->findBitTestClusters(Clusters, &SI);
12491 
12492   LLVM_DEBUG({
12493     dbgs() << "Case clusters: ";
12494     for (const CaseCluster &C : Clusters) {
12495       if (C.Kind == CC_JumpTable)
12496         dbgs() << "JT:";
12497       if (C.Kind == CC_BitTests)
12498         dbgs() << "BT:";
12499 
12500       C.Low->getValue().print(dbgs(), true);
12501       if (C.Low != C.High) {
12502         dbgs() << '-';
12503         C.High->getValue().print(dbgs(), true);
12504       }
12505       dbgs() << ' ';
12506     }
12507     dbgs() << '\n';
12508   });
12509 
12510   assert(!Clusters.empty());
12511   SwitchWorkList WorkList;
12512   CaseClusterIt First = Clusters.begin();
12513   CaseClusterIt Last = Clusters.end() - 1;
12514   auto DefaultProb = getEdgeProbability(PeeledSwitchMBB, DefaultMBB);
12515   // Scale the branchprobability for DefaultMBB if the peel occurs and
12516   // DefaultMBB is not replaced.
12517   if (PeeledCaseProb != BranchProbability::getZero() &&
12518       DefaultMBB == FuncInfo.getMBB(SI.getDefaultDest()))
12519     DefaultProb = scaleCaseProbality(DefaultProb, PeeledCaseProb);
12520   WorkList.push_back(
12521       {PeeledSwitchMBB, First, Last, nullptr, nullptr, DefaultProb});
12522 
12523   while (!WorkList.empty()) {
12524     SwitchWorkListItem W = WorkList.pop_back_val();
12525     unsigned NumClusters = W.LastCluster - W.FirstCluster + 1;
12526 
12527     if (NumClusters > 3 && TM.getOptLevel() != CodeGenOptLevel::None &&
12528         !DefaultMBB->getParent()->getFunction().hasMinSize()) {
12529       // For optimized builds, lower large range as a balanced binary tree.
12530       splitWorkItem(WorkList, W, SI.getCondition(), SwitchMBB);
12531       continue;
12532     }
12533 
12534     lowerWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB);
12535   }
12536 }
12537 
12538 void SelectionDAGBuilder::visitStepVector(const CallInst &I) {
12539   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12540   auto DL = getCurSDLoc();
12541   EVT ResultVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12542   setValue(&I, DAG.getStepVector(DL, ResultVT));
12543 }
12544 
12545 void SelectionDAGBuilder::visitVectorReverse(const CallInst &I) {
12546   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12547   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12548 
12549   SDLoc DL = getCurSDLoc();
12550   SDValue V = getValue(I.getOperand(0));
12551   assert(VT == V.getValueType() && "Malformed vector.reverse!");
12552 
12553   if (VT.isScalableVector()) {
12554     setValue(&I, DAG.getNode(ISD::VECTOR_REVERSE, DL, VT, V));
12555     return;
12556   }
12557 
12558   // Use VECTOR_SHUFFLE for the fixed-length vector
12559   // to maintain existing behavior.
12560   SmallVector<int, 8> Mask;
12561   unsigned NumElts = VT.getVectorMinNumElements();
12562   for (unsigned i = 0; i != NumElts; ++i)
12563     Mask.push_back(NumElts - 1 - i);
12564 
12565   setValue(&I, DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), Mask));
12566 }
12567 
12568 void SelectionDAGBuilder::visitVectorDeinterleave(const CallInst &I) {
12569   auto DL = getCurSDLoc();
12570   SDValue InVec = getValue(I.getOperand(0));
12571   EVT OutVT =
12572       InVec.getValueType().getHalfNumVectorElementsVT(*DAG.getContext());
12573 
12574   unsigned OutNumElts = OutVT.getVectorMinNumElements();
12575 
12576   // ISD Node needs the input vectors split into two equal parts
12577   SDValue Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12578                            DAG.getVectorIdxConstant(0, DL));
12579   SDValue Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OutVT, InVec,
12580                            DAG.getVectorIdxConstant(OutNumElts, DL));
12581 
12582   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12583   // legalisation and combines.
12584   if (OutVT.isFixedLengthVector()) {
12585     SDValue Even = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12586                                         createStrideMask(0, 2, OutNumElts));
12587     SDValue Odd = DAG.getVectorShuffle(OutVT, DL, Lo, Hi,
12588                                        createStrideMask(1, 2, OutNumElts));
12589     SDValue Res = DAG.getMergeValues({Even, Odd}, getCurSDLoc());
12590     setValue(&I, Res);
12591     return;
12592   }
12593 
12594   SDValue Res = DAG.getNode(ISD::VECTOR_DEINTERLEAVE, DL,
12595                             DAG.getVTList(OutVT, OutVT), Lo, Hi);
12596   setValue(&I, Res);
12597 }
12598 
12599 void SelectionDAGBuilder::visitVectorInterleave(const CallInst &I) {
12600   auto DL = getCurSDLoc();
12601   EVT InVT = getValue(I.getOperand(0)).getValueType();
12602   SDValue InVec0 = getValue(I.getOperand(0));
12603   SDValue InVec1 = getValue(I.getOperand(1));
12604   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12605   EVT OutVT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12606 
12607   // Use VECTOR_SHUFFLE for fixed-length vectors to benefit from existing
12608   // legalisation and combines.
12609   if (OutVT.isFixedLengthVector()) {
12610     unsigned NumElts = InVT.getVectorMinNumElements();
12611     SDValue V = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, InVec0, InVec1);
12612     setValue(&I, DAG.getVectorShuffle(OutVT, DL, V, DAG.getUNDEF(OutVT),
12613                                       createInterleaveMask(NumElts, 2)));
12614     return;
12615   }
12616 
12617   SDValue Res = DAG.getNode(ISD::VECTOR_INTERLEAVE, DL,
12618                             DAG.getVTList(InVT, InVT), InVec0, InVec1);
12619   Res = DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Res.getValue(0),
12620                     Res.getValue(1));
12621   setValue(&I, Res);
12622 }
12623 
12624 void SelectionDAGBuilder::visitFreeze(const FreezeInst &I) {
12625   SmallVector<EVT, 4> ValueVTs;
12626   ComputeValueVTs(DAG.getTargetLoweringInfo(), DAG.getDataLayout(), I.getType(),
12627                   ValueVTs);
12628   unsigned NumValues = ValueVTs.size();
12629   if (NumValues == 0) return;
12630 
12631   SmallVector<SDValue, 4> Values(NumValues);
12632   SDValue Op = getValue(I.getOperand(0));
12633 
12634   for (unsigned i = 0; i != NumValues; ++i)
12635     Values[i] = DAG.getNode(ISD::FREEZE, getCurSDLoc(), ValueVTs[i],
12636                             SDValue(Op.getNode(), Op.getResNo() + i));
12637 
12638   setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12639                            DAG.getVTList(ValueVTs), Values));
12640 }
12641 
12642 void SelectionDAGBuilder::visitVectorSplice(const CallInst &I) {
12643   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12644   EVT VT = TLI.getValueType(DAG.getDataLayout(), I.getType());
12645 
12646   SDLoc DL = getCurSDLoc();
12647   SDValue V1 = getValue(I.getOperand(0));
12648   SDValue V2 = getValue(I.getOperand(1));
12649   int64_t Imm = cast<ConstantInt>(I.getOperand(2))->getSExtValue();
12650 
12651   // VECTOR_SHUFFLE doesn't support a scalable mask so use a dedicated node.
12652   if (VT.isScalableVector()) {
12653     setValue(
12654         &I, DAG.getNode(ISD::VECTOR_SPLICE, DL, VT, V1, V2,
12655                         DAG.getSignedConstant(
12656                             Imm, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
12657     return;
12658   }
12659 
12660   unsigned NumElts = VT.getVectorNumElements();
12661 
12662   uint64_t Idx = (NumElts + Imm) % NumElts;
12663 
12664   // Use VECTOR_SHUFFLE to maintain original behaviour for fixed-length vectors.
12665   SmallVector<int, 8> Mask;
12666   for (unsigned i = 0; i < NumElts; ++i)
12667     Mask.push_back(Idx + i);
12668   setValue(&I, DAG.getVectorShuffle(VT, DL, V1, V2, Mask));
12669 }
12670 
12671 // Consider the following MIR after SelectionDAG, which produces output in
12672 // phyregs in the first case or virtregs in the second case.
12673 //
12674 // INLINEASM_BR ..., implicit-def $ebx, ..., implicit-def $edx
12675 // %5:gr32 = COPY $ebx
12676 // %6:gr32 = COPY $edx
12677 // %1:gr32 = COPY %6:gr32
12678 // %0:gr32 = COPY %5:gr32
12679 //
12680 // INLINEASM_BR ..., def %5:gr32, ..., def %6:gr32
12681 // %1:gr32 = COPY %6:gr32
12682 // %0:gr32 = COPY %5:gr32
12683 //
12684 // Given %0, we'd like to return $ebx in the first case and %5 in the second.
12685 // Given %1, we'd like to return $edx in the first case and %6 in the second.
12686 //
12687 // If a callbr has outputs, it will have a single mapping in FuncInfo.ValueMap
12688 // to a single virtreg (such as %0). The remaining outputs monotonically
12689 // increase in virtreg number from there. If a callbr has no outputs, then it
12690 // should not have a corresponding callbr landingpad; in fact, the callbr
12691 // landingpad would not even be able to refer to such a callbr.
12692 static Register FollowCopyChain(MachineRegisterInfo &MRI, Register Reg) {
12693   MachineInstr *MI = MRI.def_begin(Reg)->getParent();
12694   // There is definitely at least one copy.
12695   assert(MI->getOpcode() == TargetOpcode::COPY &&
12696          "start of copy chain MUST be COPY");
12697   Reg = MI->getOperand(1).getReg();
12698   MI = MRI.def_begin(Reg)->getParent();
12699   // There may be an optional second copy.
12700   if (MI->getOpcode() == TargetOpcode::COPY) {
12701     assert(Reg.isVirtual() && "expected COPY of virtual register");
12702     Reg = MI->getOperand(1).getReg();
12703     assert(Reg.isPhysical() && "expected COPY of physical register");
12704     MI = MRI.def_begin(Reg)->getParent();
12705   }
12706   // The start of the chain must be an INLINEASM_BR.
12707   assert(MI->getOpcode() == TargetOpcode::INLINEASM_BR &&
12708          "end of copy chain MUST be INLINEASM_BR");
12709   return Reg;
12710 }
12711 
12712 // We must do this walk rather than the simpler
12713 //   setValue(&I, getCopyFromRegs(CBR, CBR->getType()));
12714 // otherwise we will end up with copies of virtregs only valid along direct
12715 // edges.
12716 void SelectionDAGBuilder::visitCallBrLandingPad(const CallInst &I) {
12717   SmallVector<EVT, 8> ResultVTs;
12718   SmallVector<SDValue, 8> ResultValues;
12719   const auto *CBR =
12720       cast<CallBrInst>(I.getParent()->getUniquePredecessor()->getTerminator());
12721 
12722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12723   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
12724   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
12725 
12726   unsigned InitialDef = FuncInfo.ValueMap[CBR];
12727   SDValue Chain = DAG.getRoot();
12728 
12729   // Re-parse the asm constraints string.
12730   TargetLowering::AsmOperandInfoVector TargetConstraints =
12731       TLI.ParseConstraints(DAG.getDataLayout(), TRI, *CBR);
12732   for (auto &T : TargetConstraints) {
12733     SDISelAsmOperandInfo OpInfo(T);
12734     if (OpInfo.Type != InlineAsm::isOutput)
12735       continue;
12736 
12737     // Pencil in OpInfo.ConstraintType and OpInfo.ConstraintVT based on the
12738     // individual constraint.
12739     TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
12740 
12741     switch (OpInfo.ConstraintType) {
12742     case TargetLowering::C_Register:
12743     case TargetLowering::C_RegisterClass: {
12744       // Fill in OpInfo.AssignedRegs.Regs.
12745       getRegistersForValue(DAG, getCurSDLoc(), OpInfo, OpInfo);
12746 
12747       // getRegistersForValue may produce 1 to many registers based on whether
12748       // the OpInfo.ConstraintVT is legal on the target or not.
12749       for (Register &Reg : OpInfo.AssignedRegs.Regs) {
12750         Register OriginalDef = FollowCopyChain(MRI, InitialDef++);
12751         if (OriginalDef.isPhysical())
12752           FuncInfo.MBB->addLiveIn(OriginalDef);
12753         // Update the assigned registers to use the original defs.
12754         Reg = OriginalDef;
12755       }
12756 
12757       SDValue V = OpInfo.AssignedRegs.getCopyFromRegs(
12758           DAG, FuncInfo, getCurSDLoc(), Chain, nullptr, CBR);
12759       ResultValues.push_back(V);
12760       ResultVTs.push_back(OpInfo.ConstraintVT);
12761       break;
12762     }
12763     case TargetLowering::C_Other: {
12764       SDValue Flag;
12765       SDValue V = TLI.LowerAsmOutputForConstraint(Chain, Flag, getCurSDLoc(),
12766                                                   OpInfo, DAG);
12767       ++InitialDef;
12768       ResultValues.push_back(V);
12769       ResultVTs.push_back(OpInfo.ConstraintVT);
12770       break;
12771     }
12772     default:
12773       break;
12774     }
12775   }
12776   SDValue V = DAG.getNode(ISD::MERGE_VALUES, getCurSDLoc(),
12777                           DAG.getVTList(ResultVTs), ResultValues);
12778   setValue(&I, V);
12779 }
12780